Home > database >  How to Make Widget Flutter Fast?
How to Make Widget Flutter Fast?

Time:11-22

I'm trying to make my own photo codecs, I made a 512 * 512 image,

I'm just trying to build with one color and arrange in a Container in Column and Row My Code:

 SizedBox(
          height: 512,
          width: 512,
          child: Column(
            children: List.generate(512, (index) {
              return Row(
                children: List.generate(512, (index) {
                  return Container(
                    height: 1,
                    width: 1,
                    color: Colors.blue,
                  );
                }),
              );
            }),
          ),
        ),

I tried this code, it is very slow,

So how to build flutter widget fast?

CodePudding user response:

You have to use CustomPainter class to draw your own custom widget

CodePudding user response:

As said by powerman23rus said, you should use a CustomPainter, here's an example of implementation based on the code you've provided:

class ImageWidget extends StatelessWidget {
  final Color color;
  final Size size;

  const ImageWidget({
    super.key,
    this.color = Colors.blue,
    this.size = const Size(512, 512),
  });

  @override
  Widget build(BuildContext context) {
    return CustomPaint(
      painter: ImagePainter(color: color),
      size: size,
    );
  }
}

class ImagePainter extends CustomPainter {
  final Color color;

  ImagePainter({required this.color});

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()..color = color;
    canvas.drawRect(Offset.zero & size, paint);
  }

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

You can try the full example on DartPad to check by yourself the performance.

  • Related