How to render 18267 tiny Container widgets in Flutter without hurting performance?

Viewed 32

I want to render 18267 tiny "Container" widgets in a Gridview.builder in Flutter to show the entire span of an average human life for an app I'm building. But when I do that, the app on all 3 platforms (web, mobile and desktop) slows down immensely to the point that it takes several seconds just to scroll down a bit. Also, the app takes quite a bit of time to even start when I try to render only 1/3rd of the Container widget.

Here's how the screen looks like with 5000 container widgets.

enter image description here

And here's what the code is right now.

Widget build(BuildContext context) {
    totalDays = (deathDate.difference(birthDate).inHours / 24).round();
    // totalDays = 15000;
    print(totalDays);
    // int count = 5;
    totalDays = 5000;
    Size size = MediaQuery.of(context).size;

    return Scaffold(
      appBar: AppBar(
        title: Text("347 Days - 68 Hours - 67000 Seconds left"),
        centerTitle: true,
      ),
      body: SafeArea(
        child: SizedBox(
          height: size.height,
          width: size.width,
          child: GridView.builder(
            itemCount: totalDays,
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 180,
                childAspectRatio: 1 / 2,
                mainAxisSpacing: 5,
                crossAxisSpacing: 5),
            itemBuilder: (ctx, count) {
              return Container(
                width: 15,
                height: 15,
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(5),
                ),
              );
            },
          ),
        ),
      ),
    );
  }
}

Is there any way I can render that many widgets efficiently without hurting performance?

Thanks.

1 Answers

These tiny squares do not need to be Container widgets. Consider using a CustomPaint to draw rectangles instead (similar to html canvas if you are familiar with that). The Flutter team made a short video tutorial on this.

After using CustomPaint, if you still run into performance issues (especially when scrolling, like have mentioned in the question), consider wraping the CustomPaint widget with a RepaintBoundary widget.

Related