如何在 Flutter 中实现可滚动的画布?

Posted

技术标签:

【中文标题】如何在 Flutter 中实现可滚动的画布?【英文标题】:How to achieve scrollable canvas in Flutter? 【发布时间】:2019-01-24 01:55:37 【问题描述】:

我是一位经验丰富的 ios 开发人员,但对 Flutter 完全陌生。现在我在 Flutter 中遇到了 ScrollView 的问题。

我想要实现的是构建一个大的可滚动画布。我之前在iOS上做过,你可以在这里看到截图。

canvas 是一个很大的 UIScrollView,canvas 上的每个 subview 都是可拖动的,所以我可以随意放置。即使文本很长,我也可以滚动画布以查看全部内容。现在我需要使用 Flutter 做同样的事情。

目前,我只能在 Flutter 中拖动文本小部件。但父小部件不可滚动。我知道我需要在 Flutter 中使用可滚动的小部件来获得相同的结果,但我就是无法让它工作。这是我目前拥有的代码。

void main() 
  //debugPaintLayerBordersEnabled = true;
  //debugPaintSizeEnabled = true;
  runApp(new MyApp());


class MyApp extends StatelessWidget 
  @override
  Widget build(BuildContext context) 
    return new MaterialApp(
        title: 'Flutter Demo',
        theme: new ThemeData(
        primarySwatch: Colors.indigo,
      ),
      home: new MyHomePage(title: 'Flutter Demo Drag Box'),
    );
  


class MyHomePage extends StatelessWidget 
  MyHomePage(Key key, this.title) : super(key: key);

  final String title;

  @override
  Widget build(BuildContext context) 
    return new Scaffold(
      appBar: new AppBar(
      title: new Text(title),
    ),
    body: DragBox(Offset(0.0, 0.0)));
  


class DragBox extends StatefulWidget 
  final Offset position; // widget's position
  DragBox(this.position);

  @override
  _DragBoxState createState() => new _DragBoxState();


class _DragBoxState extends State<DragBox> 
  Offset _previousOffset;
  Offset _offset;
  Offset _position;

  @override
  void initState() 
    _offset = Offset.zero;
    _previousOffset = Offset.zero;
    _position = widget.position;
    super.initState();
  

  @override
  Widget build(BuildContext context) 
    return new Container(
      constraints: BoxConstraints.expand(),
      color: Colors.white24,
      child: Stack(
        children: <Widget>[
        buildDraggableBox(1, Colors.red, _offset)
      ],
    )
  );


Widget buildDraggableBox(int boxNumber, Color color, Offset offset) 
  print('buildDraggableBox $boxNumber !');
  return new Stack(
    children: <Widget>[
      new Positioned(
        left: _position.dx,
        top: _position.dy,
        child: Draggable(
          child: _buildBox(color, offset),
          feedback: _buildBox(color, offset),
          //childWhenDragging: _buildBox(color, offset, onlyBorder: true),
          onDragStarted: () 
            print('Drag started !');
            setState(() 
              _previousOffset = _offset;
            );
            print('Start position: $_position');
          ,
          onDragCompleted: () 
            print('Drag complete !');
          ,
          onDraggableCanceled: (Velocity velocity, Offset offset) 
            // update position here
            setState(() 
              Offset _offset = Offset(offset.dx, offset.dy - 80);
              _position = _offset;
              print('Drag canceled position: $_position');
            );
          ,
        ),
      )
    ],
  );


Widget _buildBox(Color color, Offset offset, bool onlyBorder: false) 
  return new Container(
    child: new Text('Flutter widget',
      textAlign: TextAlign.center,
      style: new TextStyle(fontWeight: FontWeight.bold, fontSize: 25.0)),
    );
  

任何建议或代码示例都会对我很有帮助。

PS:请忘记屏幕截图上的标尺,这对我来说不是最重要的。我现在只需要一个大的可滚动画布。

【问题讨论】:

“大”是什么意思? @creativecreatorormaybenot ah,我的错。只是意味着滚动视图将几乎占据整个屏幕。我会修正措辞。 你可以将你的视图包装成一个 SingleChildScollView 【参考方案1】:

下面的代码可能有助于解决您在水平方向滚动自定义画布的问题,如您在示例图像中所示。

     import 'package:flutter/material.dart';

      class MyScroll extends StatelessWidget 
        @override
        Widget build(BuildContext context) 
          return new MaterialApp(
            title: 'Flutter Demo',
            theme: new ThemeData(
              primarySwatch: Colors.blue,
            ),
            home: new MyHomePage(title: 'Canvas Scroller'),
          );
        
      
      class MyHomePage extends StatefulWidget 
        MyHomePage(Key key, this.title) : super(key: key);
        final String title;

        @override
        _MyHomePageState createState() => new _MyHomePageState();
      
      class _MyHomePageState extends State<MyHomePage> 
        @override
        Widget build(BuildContext context) 
          final width = MediaQuery.of(context).size.width;
          final height = MediaQuery.of(context).size.height;
          return new Scaffold(
            appBar: new AppBar(
              title: new Text(widget.title),
            ),
            body: new Center(
              child: new SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: new CustomPaint(
                  painter: new MyCanvasView(),
                  size: new Size(width*2, height/2),
                ),
              ),
            ),
          );
        
      

      class MyCanvasView extends CustomPainter
        @override
        void paint(Canvas canvas, Size size) 
          var paint = new Paint();
          paint..shader = new LinearGradient(colors: [Colors.yellow[700], Colors.redAccent],
             begin: Alignment.centerRight, end: Alignment.centerLeft).createShader(new Offset(0.0, 0.0)&size);
          canvas.drawRect(new Offset(0.0, 0.0)&size, paint);
          var path = new Path();
          path.moveTo(0.0, size.height);
          path.lineTo(1*size.width/4, 0*size.height/4);
          path.lineTo(2*size.width/4, 2*size.height/4);
          path.lineTo(3*size.width/4, 0*size.height/4);
          path.lineTo(4*size.width/4, 4*size.height/4);
          canvas.drawPath(path, new Paint()..color = Colors.yellow ..strokeWidth = 4.0 .. style = PaintingStyle.stroke);
        

        @override
        bool shouldRepaint(CustomPainter oldDelegate) 
          return false;
        

      

【讨论】:

谢谢。我已经实现了我的目标。 SingleChindScrollView 就是这样。顺便说一句,您的自定义绘画看起来很有趣。

以上是关于如何在 Flutter 中实现可滚动的画布?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 UIScrollView 中实现可拖动的 UIView 子类?

如何在 Twitter iOS 7 应用程序中实现可滑动的时间线

如何在 RealmRecyclerViewAdapter 中实现可过滤

如何在pytorch中实现可微的汉明损失?

如何在 Flutter 中实现类似视频流和视频滚动的 Tiktok

如何在底部屏幕上实现可滚动选项卡