Last active
May 20, 2021 11:10
-
-
Save guidezpl/a338a69afea04f746015861cd55782db to your computer and use it in GitHub Desktop.
ListView.builder with pre-created items
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/cupertino.dart'; | |
import 'package:flutter/material.dart'; | |
void main() => runApp(App()); | |
class App extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
home: Material( | |
child: PerformanceMediumDemo(), | |
), | |
); | |
} | |
} | |
class _ListItem extends StatefulWidget { | |
final int index; | |
_ListItem({required this.index}) { | |
print('creating list item $index'); | |
} | |
@override | |
_ListItemState createState() { | |
// print('creating list item state $index'); | |
return _ListItemState(); | |
} | |
} | |
class _ListItemState extends State<_ListItem> { | |
@override | |
Widget build(BuildContext context) { | |
print('building list item ${widget.index}'); | |
return Container(height: 500, child: Center(child: Text(widget.index.toString()))); | |
} | |
} | |
class PerformanceMediumDemo extends StatefulWidget { | |
@override | |
_PerformanceMediumDemoState createState() => _PerformanceMediumDemoState(); | |
} | |
class _PerformanceMediumDemoState extends State<PerformanceMediumDemo> { | |
final listItems = [ | |
_ListItem(index: 0), | |
_ListItem(index: 1), | |
_ListItem(index: 2), | |
_ListItem(index: 3), | |
_ListItem(index: 4), | |
_ListItem(index: 5), | |
_ListItem(index: 6), | |
_ListItem(index: 7), | |
]; | |
@override | |
Widget build(BuildContext context) { | |
// This offers no benefit, it is actually more efficient to use the ListView constructor instead. | |
return ListView.builder( | |
itemBuilder: (context, index) { | |
return listItems[index]; | |
}, | |
itemCount: 8, | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment