使用重绘在 Flutter.Stuck 中绘制应用程序

Draw App in Flutter.Stuck with repaint

这是我的应用程序的 main.dart 文件:

import 'package:flutter/material.dart';

main() {
  runApp(
    new MaterialApp(
      title: 'Flutter Database Test',
      theme: ThemeData(
        textTheme: TextTheme(
          display1: TextStyle(fontSize: 24.0, color: Colors.white),
          display2: TextStyle(fontSize: 24.0, color: Colors.grey),
          display3: TextStyle(fontSize: 18.0, color: Colors.black),
        ),
      ),
      home: new MyHomePage(),
    ),
  );
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<Color> color = [
    Colors.white,
    Colors.black,
    Colors.pink,
    Colors.blue,
    Colors.red,
    Colors.yellow,
    Colors.orange,
    Colors.green,
    Colors.cyan,
    Colors.purple,
    Colors.brown,
    Colors.indigo,
    Colors.teal,
    Colors.grey,
  ];

  Color _pencolor = Colors.white;
  Color _canvasclr = Colors.black;
  bool ispen = true;
  Color bc = Colors.black54;
  List<Offset> points = List<Offset>();
  GlobalKey<ScaffoldState> _skey = GlobalKey<ScaffoldState>();
  int cchanged = change[1];

  static var change = [1, 2, 0];

  @override
  Widget build(BuildContext context) {
    MyPainter _painter = MyPainter(color: cchanged, canvasp: points, changed: color.indexOf(_pencolor));
    _painter.addListener(() {
      print('hello');
    });
    return new Scaffold(
      resizeToAvoidBottomPadding: true,
      key: _skey,
      appBar: AppBar(
        backgroundColor: bc,
        elevation: 0.0,
        title: Text(
          'Draw',
          style: Theme.of(context).textTheme.display1,
        ),
        centerTitle: true,
        actions: <Widget>[
          IconButton(
              icon: Icon(Icons.content_paste),
              onPressed: () {
                _skey.currentState.showSnackBar(SnackBar(
                    backgroundColor: Colors.transparent,
                    content: Center(
                        child: Text(
                      'Choose Canvas Color',
                      textScaleFactor: 0.7,
                      style: Theme.of(context).textTheme.display3,
                    ))));
                ispen = false;
              }),
          IconButton(
              icon: Icon(Icons.edit),
              onPressed: () {
                _skey.currentState.showSnackBar(SnackBar(
                  content: Center(
                      child:
                          Text('Choose Pen Color', textScaleFactor: 0.7, style: Theme.of(context).textTheme.display3)),
                  backgroundColor: Colors.transparent,
                ));
                ispen = true;
              })
        ],
      ),
      drawer: Drawer(
        child: ListView(
          children: <Widget>[
            ListTile(
              title: Text('Create Canvas'),
              leading: Icon(Icons.add),
              onTap: () {
                //TODO
              },
            ),
            ListTile(
              title: Text('Connect to Canvas'),
              leading: Icon(Icons.compare_arrows),
              onTap: () {
                //TODO
              },
            )
          ],
        ),
      ),
      body: Container(
        color: bc,
        child: Column(
          children: <Widget>[
            Expanded(
              child: Padding(
                padding: const EdgeInsets.only(left: 8.0, right: 8.0, top: 10.0),
                child: ClipRRect(
                  child: Container(
                    color: _canvasclr,
                    child: GestureDetector(
                      onPanStart: (DragStartDetails d) {
                        points.add(Offset(d.globalPosition.dx, d.globalPosition.dy - 100));
                        cchanged = change[2];
                        print('${d.globalPosition},$points');
                        setState(() {});
                      },
                      onPanUpdate: (DragUpdateDetails d) {
                        points.add(Offset(d.globalPosition.dx, d.globalPosition.dy - 100));
                        print('${d.globalPosition}');
                        cchanged = change[0];
                        setState(() {});
                      },
                      child: CustomPaint(
                        isComplex: true,
                        willChange: false,
                        child: Container(),
                        painter: _painter,
                      ),
                    ),
                  ),
                  borderRadius: BorderRadius.circular(25.0),
                ),
              ),
            ),
            Container(
              height: 75.0,
              child: ListView.builder(
                scrollDirection: Axis.horizontal,
                shrinkWrap: true,
                itemCount: color.length,
                itemBuilder: (BuildContext context, int index) {
                  return InkWell(
                    splashColor: Colors.white,
                    onTap: () {
                      ispen ? _pencolor = color[index] : _canvasclr = color[index];
                      setState(() {});
                    },
                    child: Padding(
                      padding: const EdgeInsets.all(12.0),
                      child: CircleAvatar(
                        backgroundColor: color[index],
                      ),
                    ),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class MyPainter extends CustomPainter {
  final int color;
  final List<Offset> canvasp;
  Paint p = Paint();
  List<Paint> _paint = [
    Paint()
      ..strokeCap = StrokeCap.round
      ..strokeJoin = StrokeJoin.round
      ..strokeWidth = 2.0
      ..color = Colors.white,
    Paint()
      ..strokeCap = StrokeCap.round
      ..strokeJoin = StrokeJoin.round
      ..strokeWidth = 2.0
      ..color = Colors.black,
    Paint()
      ..strokeCap = StrokeCap.round
      ..strokeJoin = StrokeJoin.round
      ..strokeWidth = 2.0
      ..color = Colors.pink,
    Paint()
      ..strokeCap = StrokeCap.round
      ..strokeJoin = StrokeJoin.round
      ..strokeWidth = 2.0
      ..color = Colors.blue,
    Paint()
      ..strokeCap = StrokeCap.round
      ..strokeJoin = StrokeJoin.round
      ..strokeWidth = 2.0
      ..color = Colors.red,
    Paint()
      ..strokeCap = StrokeCap.round
      ..strokeJoin = StrokeJoin.round
      ..strokeWidth = 2.0
      ..color = Colors.yellow,
    Paint()
      ..strokeCap = StrokeCap.round
      ..strokeJoin = StrokeJoin.round
      ..strokeWidth = 2.0
      ..color = Colors.orange,
    Paint()
      ..strokeCap = StrokeCap.round
      ..strokeJoin = StrokeJoin.round
      ..strokeWidth = 2.0
      ..color = Colors.green,
    Paint()
      ..strokeCap = StrokeCap.round
      ..strokeJoin = StrokeJoin.round
      ..strokeWidth = 2.0
      ..color = Colors.cyan,
    Paint()
      ..strokeCap = StrokeCap.round
      ..strokeJoin = StrokeJoin.round
      ..strokeWidth = 2.0
      ..color = Colors.purple,
    Paint()
      ..strokeCap = StrokeCap.round
      ..strokeJoin = StrokeJoin.round
      ..strokeWidth = 2.0
      ..color = Colors.brown,
    Paint()
      ..strokeCap = StrokeCap.round
      ..strokeJoin = StrokeJoin.round
      ..strokeWidth = 2.0
      ..color = Colors.indigo,
    Paint()
      ..strokeCap = StrokeCap.round
      ..strokeJoin = StrokeJoin.round
      ..strokeWidth = 2.0
      ..color = Colors.teal,
    Paint()
      ..strokeCap = StrokeCap.round
      ..strokeJoin = StrokeJoin.round
      ..strokeWidth = 2.0
      ..color = Colors.grey,
  ];

  final int changed;

  MyPainter({
    this.color,
    this.canvasp,
    this.changed,
  });

  @override
  void paint(Canvas canvas, Size size) {
    print('painting .......     $canvasp');
    for (int i = 0; i < canvasp.length; i++) {
      canvas.drawCircle(canvasp[i], 10.0, _paint[color]);
    }
  }

  @override
  bool shouldRepaint(MyPainter oldDelegate) {
    return oldDelegate.canvasp.length != canvasp.length;
  }
}

此实现显示了我正在尝试构建的应用程序,以在 canvas 上进行绘制。

但是,我无法在触摸屏幕时进行绘制。相反,它仅在我更改墨水瓶中的颜色时才重绘 - 但在书写时或在 GestureDetector 中收到事件时不会重绘。

如果能以更改我现有代码的形式给出答案,我们将不胜感激。

首先我要说请不要把我在这个回答中说的任何话当成个人 - 我知道 be nice Whosebug 一直在努力实现的努力。但我还要说:您需要 清理您的代码。这不是人身攻击,只是想帮助你提高程序员的一些话。

您绝对应该将逻辑分解成更小的块 - 一般规则是,如果您的构建函数在垂直方向上占用的空间超过一个页面,则它可能做得太多了。对于作为程序员的你来说都是如此,对于应用程序的性能也是如此,因为 flutter 使用 state-based 机制进行重建,而这种机制会受到大型构建函数的影响。

另外两个提示是:

  • 尽可能不要使用 GlobalKey。您的 AppBar 应该封装在它自己的小部件中,或者至少使用 Builder 构建,以便它接收包含脚手架的上下文。然后你可以使用 Scaffold.of(....) 而不是全局密钥。

  • 如果你要使用像你的 static var change = [1, 2, 0] 这样的静态变量,你可能最好使用枚举——尤其是没有对其他人来说毫无意义的文档注释在你的代码中(即我=D)。使用枚举将使您的代码更具可读性。另外,请考虑以不同的方式命名 - cchanged 对任何人都没有意义,除了你自己(如果你离开几个星期,甚至可能对你也没有意义)。

  • 画家和小部件中的颜色列表是一个等待发生的编码错误。 Building Paint objects 很便宜,只要你不在循环中执行它 - 只需在构建函数中实例化一个新的而不是保留一个列表,然后直接传递颜色!或者至少,制作一个名为 Palette 或其他名称的 enum 并使用它来做出决定而不是列表 - 至少这样,如果你使用开关,dart 分析器将帮助确保你迎合每个可能的选择。

  • 这是第二段的重复,但重要的是要重复...将您的 class 分解为更多有状态或无状态的小部件...或至少将构建函数分解为多个函数。这将使事情变得不那么复杂,更容易理解,并且性能更高。为什么每次在 canvas 上绘制一个点时,您可能会同时重新绘制标题栏、底部栏和您在屏幕上看到的所有其他内容,因为它们是一体的小部件!您的有状态小部件应该只构建有状态的视觉部分!

  • 使用setState时,实际上是在setState函数内设置状态。 现在,如果你不这样做,事情会成功......但它在语义上并不那么清楚你在做什么,如果 flutter 开发者做一个更改 setState 的工作方式。

  • 因为您在小吃栏中使用 Center,所以它们正在扩展以占据整个屏幕。我很确定这不是您想要的,因此请添加 heightFactor = 1.0,这样它们就不会垂直扩展。我会留给你决定是否要继续使用这个视觉机制来改变你正在改变的颜色 - 我个人认为它不是很好,因为它覆盖了你实际使用的区域 select颜色...

我猜这只是一个为了好玩而组合在一起的快速应用程序,你正在学习 flutter and/or 编码。但是从专业开发人员和临时招聘经理那里获取 - 多花几分钟来确保您的代码可读且易于理解 将在长期 运行 中节省您的时间,并且 即使在一次性项目中也能编写干净的代码将帮助您养成良好的习惯,从而帮助您成为更好的程序员。另外 - 当我检查可能的雇用时,如果我在他们的 public github 存储库之一中看到非常混乱的代码,这就是不给他们面试的另一个原因。我不知道你在 github 上做的每一件事都是为了 public,但代码整洁是一项容易培养的技能,不需要那么长时间,并且可以充分说明你作为一名程序员的能力!

最后一件事 - 考虑到我们在 Whosebug 上免费这样做是因为我们想帮助社区,因此要求以一种特定方式回答您的问题有点粗鲁。我已经缓和了你问题的语气,但请记住这一点,因为要有礼貌 ==> 更好的答案!

现在谈谈你的实际问题 - 这一切都归结为这句话:

@override
bool shouldRepaint(MyPainter oldDelegate) {
  return oldDelegate.canvasp.length != canvasp.length;
}

在 dart(和许多其他编程语言,但不是全部)中,将列表与 != 或 == 进行比较只会做我所说的 'shallow compare';也就是说,它只检查列表是否是同一个列表。因为您每次都在 same 列表中添加一个新点你检测到一个手势,但 不是 re-creating 列表 ,程序语句总是 returns 错误,因此你的 canvas 永远不会 re-draws.

解决此问题的最简单方法是每次添加内容时将列表复制到新列表中 - 这样列表就会比较不同。但是,如果您要处理很多可能会出现在这里的元素,那么这并不是一个特别好的答案。

我的建议是使用一个计数器来跟踪每次更改列表的时间。我在下面的一些代码中进行了更改 - 我称之为 _revision。每次添加到列表时,也会增加 _revision 并将其传递给 canvas。在你的 canvas 中,你只需要检查版本是否相同。我建议制作一个为您递增的方法,并确保正确调用 setState。

import 'package:flutter/material.dart';

main() {
  runApp(
    new MaterialApp(
      title: 'Flutter Database Test',
      theme: ThemeData(
        textTheme: TextTheme(
          display1: TextStyle(fontSize: 24.0, color: Colors.white),
          display2: TextStyle(fontSize: 24.0, color: Colors.grey),
          display3: TextStyle(fontSize: 18.0, color: Colors.black),
        ),
      ),
      home: new MyHomePage(),
    ),
  );
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<Color> color = [
    Colors.white,
    Colors.black,
    Colors.pink,
    Colors.blue,
    Colors.red,
    Colors.yellow,
    Colors.orange,
    Colors.green,
    Colors.cyan,
    Colors.purple,
    Colors.brown,
    Colors.indigo,
    Colors.teal,
    Colors.grey,
  ];

  Color _pencolor = Colors.white;
  Color _canvasclr = Colors.black;
  bool ispen = true;
  Color bc = Colors.black54;
  List<Offset> points = List<Offset>();
  GlobalKey<ScaffoldState> _skey = GlobalKey<ScaffoldState>();
  int cchanged = change[1];
  int _revision = 0;

  static var change = [1, 2, 0];

  @override
  Widget build(BuildContext context) {
    MyPainter _painter =
        MyPainter(color: color.indexOf(_pencolor), canvasp: points, changed: cchanged, revision: _revision);
    _painter.addListener(() {
      print('hello');
    });
    return new Scaffold(
      resizeToAvoidBottomPadding: true,
      key: _skey,
      appBar: AppBar(
        backgroundColor: bc,
        elevation: 0.0,
        title: Text(
          'Draw',
          style: Theme.of(context).textTheme.display1,
        ),
        centerTitle: true,
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.content_paste),
            onPressed: !ispen
                ? null
                : () {
                    _skey.currentState.showSnackBar(
                      SnackBar(
                        backgroundColor: Colors.transparent,
                        content: Center(
                          heightFactor: 1.0,
                          child: Text(
                            'Choose Canvas Color',
                            textScaleFactor: 0.7,
                            style: Theme.of(context).textTheme.display3,
                          ),
                        ),
                      ),
                    );
                    setState(() {
                      ispen = false;
                    });
                  },
          ),
          IconButton(
            icon: Icon(Icons.edit),
            onPressed: ispen
                ? null
                : () {
                    _skey.currentState.showSnackBar(
                      SnackBar(
                        content: Center(
                            heightFactor: 1.0,
                            child: Text('Choose Pen Color',
                                textScaleFactor: 0.7, style: Theme.of(context).textTheme.display3)),
                        backgroundColor: Colors.transparent,
                      ),
                    );
                    setState(() {
                      ispen = true;
                    });
                  },
          )
        ],
      ),
      drawer: Drawer(
        child: ListView(
          children: <Widget>[
            ListTile(
              title: Text('Create Canvas'),
              leading: Icon(Icons.add),
              onTap: () {
                //TODO
              },
            ),
            ListTile(
              title: Text('Connect to Canvas'),
              leading: Icon(Icons.compare_arrows),
              onTap: () {
                //TODO
              },
            )
          ],
        ),
      ),
      body: Container(
        color: bc,
        child: Column(
          children: <Widget>[
            Expanded(
              child: Padding(
                padding: const EdgeInsets.only(left: 8.0, right: 8.0, top: 10.0),
                child: ClipRRect(
                  child: Container(
                    color: _canvasclr,
                    child: GestureDetector(
                      onPanStart: (DragStartDetails d) {
                        setState(() {
                          points.add(Offset(d.globalPosition.dx, d.globalPosition.dy - 100));
                          cchanged = change[2];
                          _revision++;
                        });
                        print('${d.globalPosition},$points');
                      },
                      onPanUpdate: (DragUpdateDetails d) {
                        print('${d.globalPosition}');
                        setState(() {
                          points.add(Offset(d.globalPosition.dx, d.globalPosition.dy - 100));
                          cchanged = change[0];
                          _revision++;
                        });
                      },
                      child: CustomPaint(
                        isComplex: true,
                        willChange: false,
                        child: Container(),
                        painter: _painter,
                      ),
                    ),
                  ),
                  borderRadius: BorderRadius.circular(25.0),
                ),
              ),
            ),
            Container(
              height: 75.0,
              child: ListView.builder(
                scrollDirection: Axis.horizontal,
                shrinkWrap: true,
                itemCount: color.length,
                itemBuilder: (BuildContext context, int index) {
                  return InkWell(
                    splashColor: Colors.white,
                    onTap: () {
                      setState(() {
                        ispen ? (_pencolor = color[index]) : (_canvasclr = color[index]);
                      });
                    },
                    child: Padding(
                      padding: const EdgeInsets.all(12.0),
                      child: CircleAvatar(
                        backgroundColor: color[index],
                      ),
                    ),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class MyPainter extends CustomPainter {
  final int color;
  final List<Offset> canvasp;
  final int revision;
  Paint p = Paint();
  List<Paint> _paint = [
    Paint()
      ..strokeCap = StrokeCap.round
      ..strokeJoin = StrokeJoin.round
      ..strokeWidth = 2.0
      ..color = Colors.white,
    Paint()
      ..strokeCap = StrokeCap.round
      ..strokeJoin = StrokeJoin.round
      ..strokeWidth = 2.0
      ..color = Colors.black,
    Paint()
      ..strokeCap = StrokeCap.round
      ..strokeJoin = StrokeJoin.round
      ..strokeWidth = 2.0
      ..color = Colors.pink,
    Paint()
      ..strokeCap = StrokeCap.round
      ..strokeJoin = StrokeJoin.round
      ..strokeWidth = 2.0
      ..color = Colors.blue,
    Paint()
      ..strokeCap = StrokeCap.round
      ..strokeJoin = StrokeJoin.round
      ..strokeWidth = 2.0
      ..color = Colors.red,
    Paint()
      ..strokeCap = StrokeCap.round
      ..strokeJoin = StrokeJoin.round
      ..strokeWidth = 2.0
      ..color = Colors.yellow,
    Paint()
      ..strokeCap = StrokeCap.round
      ..strokeJoin = StrokeJoin.round
      ..strokeWidth = 2.0
      ..color = Colors.orange,
    Paint()
      ..strokeCap = StrokeCap.round
      ..strokeJoin = StrokeJoin.round
      ..strokeWidth = 2.0
      ..color = Colors.green,
    Paint()
      ..strokeCap = StrokeCap.round
      ..strokeJoin = StrokeJoin.round
      ..strokeWidth = 2.0
      ..color = Colors.cyan,
    Paint()
      ..strokeCap = StrokeCap.round
      ..strokeJoin = StrokeJoin.round
      ..strokeWidth = 2.0
      ..color = Colors.purple,
    Paint()
      ..strokeCap = StrokeCap.round
      ..strokeJoin = StrokeJoin.round
      ..strokeWidth = 2.0
      ..color = Colors.brown,
    Paint()
      ..strokeCap = StrokeCap.round
      ..strokeJoin = StrokeJoin.round
      ..strokeWidth = 2.0
      ..color = Colors.indigo,
    Paint()
      ..strokeCap = StrokeCap.round
      ..strokeJoin = StrokeJoin.round
      ..strokeWidth = 2.0
      ..color = Colors.teal,
    Paint()
      ..strokeCap = StrokeCap.round
      ..strokeJoin = StrokeJoin.round
      ..strokeWidth = 2.0
      ..color = Colors.grey,
  ];

  final int changed;

  MyPainter({this.color, this.canvasp, this.changed, this.revision});

  @override
  void paint(Canvas canvas, Size size) {
    print('painting .......     $canvasp');
    for (int i = 0; i < canvasp.length; i++) {
      canvas.drawCircle(canvasp[i], 10.0, _paint[color]);
    }
  }

  @override
  bool shouldRepaint(MyPainter oldDelegate) {
    return oldDelegate.revision != revision;
  }
}

我添加了修订参数并做了一些其他的小修复。您的代码仍然需要进行大量重构,但这至少可以使其正常工作。请记住我的其他评论 =)。

此外 - 看看 this question & answer,因为它执行类似的操作,如果您最终想这样做,可以帮助保存生成的绘图!