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

Sus*_*lle 0 android repaint flutter flutter-layout

这是我的应用程序的 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;
  }
}
Run Code Online (Sandbox Code Playgroud)

此实现显示了我正在尝试构建以在画布上绘制的应用程序。

但是,当我触摸屏幕时,我无法绘制它。相反,它仅在我更改墨水瓶中的颜色时重新绘制 - 而不是在写入时或在 GestureDetector 中接收到事件时。

以更改我现有代码的形式提供答案将不胜感激。

rmt*_*zie 5

我将首先说请不要亲自接受我在这个答案中所说的任何内容 - 我知道be niceStackOverflow 一直在尝试实施的努力。但我还要说:你需要考虑清理你的代码。这不是人身攻击,只是想帮助您提高程序员水平的人的一些话。

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

另外几个提示是:

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

  • 如果您打算使用像您的 静态变量static var change = [1, 2, 0],您可能最好使用枚举 - 特别是没有文档注释,这对其他人查看您的代码(即我 =D)没有任何意义。使用枚举将使您的代码更具可读性。另外,请考虑以不同的cchanged方式命名 -除了你自己之外对任何人都没有意义(如果你离开几周,甚至可能对你也没有意义)。

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

  • 这是第二段的重复,但重要的是要重复……将您的类分解为更多有状态或无状态小部件……或者至少将您的构建功能分解为多个功能。这将使事情变得不那么复杂,更容易理解,并且性能更高。原因的一个例子是,每次您在画布上绘制一个点时,您可能会同时重新绘制标题栏、底部栏以及您在屏幕上看到的所有其他内容,因为它们都在一个小部件中!您的 statefulwidget 应该只构建有状态的视觉部分!

  • 使用时setState,实际设置setState函数内的状态。现在,如果您不这样做,事情就会起作用……但是从语义上讲,您在做什么并不那么清楚,并且如果 flutter 开发人员对 setState 的工作方式进行更改,将来很容易中断。

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

我猜这只是一个为了好玩而放在一起的快速应用程序,并且您正在学习 flutter 和/或编码。但是从专业的开发人员和临时招聘经理那里得到它-多花几分钟确保您的代码可读且易于理解,从长远来看将节省您的时间,并且即使在一次性项目编写干净的代码也会帮助您养成好习惯,帮助你成为更好的程序员. 另外 - 当我检查可能的招聘时,如果我在他们的一个公共 github 存储库中看到非常混乱的代码,这是不给他们面试的另一个原因。我知道并非您在 github 上所做的一切都是为公众准备的,但是代码清洁是一项易于开发的技能,不需要那么长时间,并且对您作为一名程序员说了很多!

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

现在讨论您的实际问题 - 这一切都归结为以下声明:

@override
bool shouldRepaint(MyPainter oldDelegate) {
  return oldDelegate.canvasp.length != canvasp.length;
}
Run Code Online (Sandbox Code Playgroud)

在 dart(以及许多其他编程语言,但不是全部)中,将列表与 != 或 == 进行比较只会执行我所说的“浅比较”;也就是说,它只检查列表是否是同一个列表。因为每次检测到手势时都会向同一个列表添加一个新点,但不会重新创建该列表,所以后续语句始终返回 false,因此您的画布永远不会重新绘制。

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

我建议使用一个计数器,用于在每次更改列表时进行跟踪。我在下面的一些代码中进行了更改 - 我称之为_revision. 每次添加到列表时,也要增加_revision并将其传递到画布。在您的画布中,您只需检查修订版是否相同。我建议创建一个方法来为你做递增,并确保 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;
  }
}
Run Code Online (Sandbox Code Playgroud)

我添加了修订参数并做了一些其他的小修复。您的代码仍然需要大量重构,但这至少应该使它起作用。请记住我的其他评论=)。

另外 - 看看这个问题和答案,因为它做了类似的事情,如果这是你最终想要做的事情,它可以帮助保存生成的绘图!