Below is a minimal app that demonstrates my concern. If you run it you'll see that the build method of every visible item runs even when the data for only one item has changed.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyList extends StatelessWidget {
final List<int> items;
MyList(this.items);
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
print("item $index built");
return ListTile(
title: Text('${items[index]}'),
);
});
}
}
class MyApp extends StatefulWidget {
MyApp({Key? key}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
List<int> items = List<int>.generate(10000, (i) => i);
void _incrementItem2() {
setState(() {
this.items[1]++;
});
}
@override
Widget build(BuildContext context) {
final title = 'Long List';
return MaterialApp(
title: title,
home: Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Column(
children: <Widget>[
MyButton(_incrementItem2),
Expanded(child: MyList(this.items))
],
),
),
);
}
}
class MyButton extends StatelessWidget {
final Function incrementItem2;
void handlePress() {
incrementItem2();
}
MyButton(this.incrementItem2);
@override
Widget build(BuildContext context) {
return TextButton(
style: ButtonStyle(
foregroundColor: MaterialStateProperty.all<Color>(Colors.blue),
),
onPressed: handlePress,
child: Text('increment item 2'),
);
}
}
In React / React Native, I would use shouldComponentUpdate or UseMemo to prevent unnecessary renders. I'd like to do the same in Flutter.
Here is a link to a closed issue on the Flutter github on the same topic: (I'll be commenting there with a link to this question) https://github.com/flutter/flutter/issues/19421
What are the best practices for avoiding useless "rerenders" or calls to the build method in Flutter, or are these extra builds not a serious concern given structural differences between Flutter and React?
This is more or less similar this question asked on stack overflow a few years ago: How to Prevent rerender of a widget based on custom logic in flutter?
An upvoted answer given is to use ListView.builder. While that can prevent some if not most useless renders, it doesn't prevent all useless renders, as shown in my example.
Thanks in advance for your knowledge and insight.


