In my app, I have a ListView that I would like to populate with Firebase data. I successfully did it, but now, I would like to separate my ListView in another dart file
main.dart
class _MyHomePageState extends State<MyHomePage> {
int currentPageIndex = 0;
late List<QueryDocumentSnapshot<Map<String, dynamic>>> list;
@override
void initState() {
print('INIT');
FirebaseFirestore.instance
.collection('bands').get().then(
(querySnapshot) => {
setState(() {
list = querySnapshot.docs;
}),
},
);
super.initState();
}
and then I am calling my custom View as part of Bottom Navigation:
@override
Widget build(BuildContext context) {
return ...
appBar: AppBar(
...
),
bottomNavigationBar: NavigationBar(
.....
),
body:
<Widget>[
ArtistList(list),
and in a separate dart file
class ArtistList extends StatefulWidget {
ArtistList(this.list);
final List<QueryDocumentSnapshot<Map<String, dynamic>>> list;
@override
State<ArtistList> createState() => _ArtistListPageState(list);
}
class _ArtistListPageState extends State<ArtistList> {
_ArtistListPageState(this.list);
final List<QueryDocumentSnapshot<Map<String, dynamic>>> list;
@override
Widget build(BuildContext context) {
return ListView.builder(
itemBuilder: (BuildContext context, int index) {
var data=list[index];
return Text(data['name'])
....
This is working, but it's not really optimised.
Do I have to define my list as a parameter of all my widgets? I see a lot of redundancy there.
Remove
_ArtistListPageState(this.list);
final List<QueryDocumentSnapshot<Map<String, dynamic>>> list;
Use
var data = widget.list[index];
The page state has access to all parameters in the stateful widget through the widget
variable
Also when defining a list that might take some time before it is populated, I recommend setting it to an empty list rather than using late
In your HomePage
, do this instead
List<QueryDocumentSnapshot<Map<String, dynamic>>> list = [];