This is my first Flutter project, and I'm learning as I go. I originally had all 10,000 lines of code in my main.dart, and surprisingly I was not running into lag when switching tabs. I've since broken it up into files based on screens, classes, and functions, and I'm lag when switching tabs, but only occasionally—it seems random.
At first, I had ValueNotifiers in a globals.dart file. I thought that might be the issue, so I implemented a provider in some places (haven't done it everywhere yet because I don't think it is fixing the issue).
I have a list page that displays tiles. Here is some code:
class ListPage extends StatefulWidget {
const ListPage({Key? key}) : super(key: key);
@override
_ListState createState() => _ListState();
}
class _ListState extends State<ListPage> {
@override
Widget build(BuildContext context) {
context.watch<ListProvider>().getIndivWorkouts();
var listProvider = Provider.of<ListProvider>(context);
return Scaffold(
body: ListView(
children: <Widget>[
for (int index = listProvider.indivWorkouts.length - 1;
index >= 0; index--)
Column(children: <Widget>[// just builds tile]
...
And the provider:
class ListProvider with ChangeNotifier {
List _indivWorkouts = <IndivWorkout>[];
List get indivWorkouts => _indivWorkouts.toList();
getIndivWorkouts() {
final box = Hive.box<IndivWorkout>('indivWorkoutsBox');
_indivWorkouts = box.values.toList();
}
addIndivWorkout(IndivWorkout workout) {
var indivWorkoutsBox = Hive.box<IndivWorkout>('indivWorkoutsBox');
indivWorkoutsBox.add(workout);
notifyListeners();
}
}
addIndivWorkout is called from another page.
I tried to screen record the issue, but it appeared perfectly normal in the final recording, so I had to film with another device. Notice the delay from hitting the tab to the page loading.
https://i.sstatic.net/8NPeQ.jpg
The delay seems more frequent on the release than the debug build, strangely. Additionally, even when I am visibly seeing a large delay, the DevTools performance graph appears normal. I really don't want to go back to one huge main.dart file, so any help is appreciated!!
I would check out the Consumer class:
https://pub.dev/documentation/provider/latest/provider/Consumer-class.html
https://docs.flutter.dev/development/data-and-backend/state-mgmt/simple
A little example of how you could have your code.
I believe that this may help with the lagging
@override
Widget build(BuildContext context) {
return Scaffold(
body: Consumer<ListProvider>(
builder: (context, listProvider, child) {
return ListView(
children: <Widget>[
for (int index = listProvider.indivWorkouts.length - 1;
index >= 0; index--)
Column(children: <Widget>[// just builds tile]
},
);
}
Make sure to take note of the second link and put your consumer as far down in the widget tree as possible. Because "You don’t want to rebuild large portions of the UI just because some detail somewhere changed."