Flutter:CustomPainter 绘画方法被调用多次而不是只调用一次

Flutter: CustomPainter paint method gets called several times instead of only once

我有一个简单的应用程序,它通过 CustomPainter 在 canvas 上绘制一个红色或绿色圆圈,具体取决于 AppBar 中按下的按钮:


class ColorCircle 扩展 CustomPainter 并负责绘制彩色圆圈:

class ColorCircle extends CustomPainter {
  MaterialColor myColor;

  ColorCircle({@required this.myColor});
  
  @override
  void paint(Canvas canvas, Size size) {
    debugPrint('ColorCircle.paint, ${DateTime.now()}');
    final paint = Paint()..color = myColor;
    canvas.drawCircle(Offset(size.width / 2, size.height / 2), 100, paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => false;
}

不同颜色的绘制效果很好,但是当我单击(仅一次!)或将鼠标悬停在其中一个按钮上时,paint 方法被调用了几次:


更多实施细节: 我使用 StatefulWidget 来存储 actualColor。在构建方法中 actualColor 被传递给 ColorCircle 构造函数:

class _MyHomePageState extends State<MyHomePage> {
  MaterialColor actualColor = Colors.red;
    
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        actions: <Widget>[
          OutlinedButton(
            onPressed: () => setState(() => actualColor = Colors.red),
            child: Text('RedCircle'),
          ),
          OutlinedButton(
            onPressed: () => setState(() => actualColor = Colors.green),
            child: Text('GreenCircle'),
          ),
        ],
      ),
      body: Center(
        child: CustomPaint(
          size: Size(300, 300),
          painter: ColorCircle(myColor: actualColor),
        ),
      ),
    );
  }
}  

可以在此处找到带有 运行 示例的完整源代码:CustonPainter Demo


那么为什么 paint 被调用多次而不是只调用一次? (你如何实现它以便 paint 只被调用一次?)。

一个糟糕的解决方案可能是在悬停小部件周围添加一个 RepaintBoundary

class _MyHomePageState extends State<MyHomePage> {
  MaterialColor actualColor = Colors.red;

  @override
  Widget build(BuildContext context) {
    print('Rebuilding with $actualColor');
    return Scaffold(
      appBar: AppBar(
        title: Text('CustomPainter Demo'),
        actions: <Widget>[
          RepaintBoundary(
            child: OutlinedButton(
                style: ButtonStyle(
                    foregroundColor: MaterialStateProperty.all(Colors.black)),
                onPressed: () {
                  setState(() => actualColor = Colors.red);
                },
                child: Text('RedCircle')),
          ),
          RepaintBoundary(
            child: OutlinedButton(
                style: ButtonStyle(
                    foregroundColor: MaterialStateProperty.all(Colors.black)),
                onPressed: () {
                  setState(() => actualColor = Colors.green);
                },
                child: Text('GreenCircle')),
          ),
        ],
      ),
      body: Center(
        child: CustomPaint(
          size: Size(300, 300),
          painter: ColorCircle(myColor: actualColor),
        ),
      ),
    );
  }
}

然后,正确定义 ColorCircleshouldRepaint 方法(当前返回 false):

@override
bool shouldRepaint(CustomPainter oldDelegate) {
  return (oldDelegate as ColorCircle).myColor != myColor;
}

这似乎是一个非常糟糕的解决方案。我很想知道更好、更可持续的答案。

包含 RepaintBoundary 解决方法的完整源代码

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'CustomPainter Demo',
      home: MyHomePage(),
    );
  }
}

class ColorCirle extends CustomPainter {
  MaterialColor myColor;

  ColorCirle({@required this.myColor});
  @override
  void paint(Canvas canvas, Size size) {
    debugPrint('ColorCircle.paint, ${DateTime.now()}');
    final paint = Paint()..color = myColor;
    canvas.drawCircle(Offset(size.width / 2, size.height / 2), 100, paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return (oldDelegate as ColorCirle).myColor != myColor;
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  MaterialColor actualColor = Colors.red;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('CustomPainter Demo'),
        actions: <Widget>[
          RepaintBoundary(
            child: OutlinedButton(
                style: ButtonStyle(
                    foregroundColor: MaterialStateProperty.all(Colors.black)),
                onPressed: () {
                  setState(() => actualColor = Colors.red);
                },
                child: Text('RedCircle')),
          ),
          RepaintBoundary(
            child: OutlinedButton(
                style: ButtonStyle(
                    foregroundColor: MaterialStateProperty.all(Colors.black)),
                onPressed: () {
                  setState(() => actualColor = Colors.green);
                },
                child: Text('GreenCircle')),
          ),
        ],
      ),
      body: Center(
        child: CustomPaint(
          size: Size(300, 300),
          painter: ColorCirle(myColor: actualColor),
        ),
      ),
    );
  }
}

您需要做两件事:

  1. RepaintBoundary

    扭曲 CustomPaint
    Center(
     child: RepaintBoundary(
       child: CustomPaint(
         size: Size(300, 300),
         painter: ColorCircle(myColor: actualColor),
       ),
     ),
    
  2. return shouldRepaint 方法为真

    bool shouldRepaint(CustomPainter oldDelegate) {
      return true;
    }