在Flutter中绘制应用程序。

时间:2018-07-04 12:52:32

标签: android flutter repaint 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;
  }
}

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

但是,当我触摸屏幕时,无法绘制它。取而代之的是,它仅在我更改墨水池中的颜色时才重新绘制,而不是在书写时或在GestureDetector中接收到事件时才重新绘制。

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

1 个答案:

答案 0 :(得分:2)

我将通过在此开头开头说:请不要接受我在此答案中所说的任何内容-我知道StackOverflow一直在努力实现be nice。但我也要这样说:您需要来研究清理代码。这不是个人攻击,只是想帮助您提高程序员水平的人的一些话。

您绝对应该将逻辑分解为较小的块-一般规则是,如果您的构建函数垂直占用的空间超过一页,则可能做得太多。这对您作为程序员来说都是如此,对于应用程序的性能也是如此,因为flutter使用受大型构建函数影响的基于状态的机制进行重建。

另外两个提示是:

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

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

  • 画家和小部件中的“颜色”列表是一个等待发生的编码错误。只要您不循环执行,Build Paint对象就很便宜-只需在build函数中实例化一个新对象,而不是保留一个列表,然后直接传递颜色!或至少要制作一个名为enum的Palette之类的东西,并使用它来做出决策而不是列表-至少这样,如果您使用开关,dart分析器将有助于确保您迎合每个客户可能的选项。

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

  • 使用setState时,实际上在setState函数中设置状态。 现在,如果您不这样做,一切都会奏效……但是语义上并不清楚您在做什么,而且如果开发者改变了方式,将来很容易中断setState起作用。

  • 因为您在小吃店中使用Center,所以它们正在扩展以显示整个屏幕。我相当确定这是您不想要的,因此添加heightFactor = 1.0使其不会垂直扩展。我将由您决定是否要继续使用此可视化机制来更改要更改的颜色-我个人认为这并不好,因为它会覆盖您实际用于选择颜色的区域。

我想这只是一个有趣的快速应用程序,您正在学习抖动和/或编码。但是请从专业的开发人员和临时招聘经理那里获取经验-花额外的几分钟时间来确保您的代码可读性强并且易于理解从长远来看将节省您的时间,并且即使在废弃项目上也可以使用干净的代码,这将有助于您养成良好的习惯,从而帮助您成为更好的程序员。另外-当我检查一个可能的聘用人员时,如果我在他们的公共github仓库之一中看到真正凌乱的代码,那就是不接受他们采访的另一个原因。我不知道您在github上进行的所有操作都是面向公众的,但是代码清洁度是一项易于开发的技能,不需要花费那么长的时间,并且会以程序员的身份谈论您很多!

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

现在来看您的实际问题-一切都归结为以下陈述:

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

在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;
  }
}

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

还-看一下this question & answer,因为它做了类似的事情,并且如果您最终想做的话,可以帮助保存生成的图形!