Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: How to load Future data from firebase to GridView?

Hi everybody (the ones that loves Flutter),

It is very simple (but I don't know how).

I have dynamic menu options in a Firebase database. I need to show it to final user in a GridView.

I have a Future list (let's say Future>) that returns a list from Firebase data:

static Future<List<Menu>> list() async {
    List<Menu> _list = new List();
    await drMenues.onValue.listen((event) {
      Menu _menu = new Menu();
      _menu.desdeData(event.snapshot);
      _list.add(_menu);
    });
    return _list;
  }

Now, I need to fill my GridView with these menu options.

final datosMenues = list();
...
new GridView.count(
  crossAxisCount: (orientation == Orientation.portrait) ? 3 : 4,
  childAspectRatio: (orientation == Orientation.portrait) ? 1.0 : 1.3,
      children: datosMenues.then
...

I need a little help to finish it. I know I need a "then" because is a Future list.

Please any advice?

like image 389
abnerh69 Avatar asked Dec 13 '17 02:12

abnerh69


1 Answers

Here is a complete example if you need a little more help.

This is how my data is organized in Firebase:

this is how my data is organized in Firebase

return StreamBuilder(
    stream: FirebaseDatabase.instance
        .reference()
        .child("Communities")
        .onValue,
    builder: (BuildContext context, AsyncSnapshot<Event> snapshot) {
      if (snapshot.hasData) {
        Map<dynamic, dynamic> map = snapshot.data.snapshot.value;
        map.forEach((dynamic, v) => print(v["pic"]));

        return GridView.builder(
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 3),
          itemCount: map.values.toList().length,
          padding: EdgeInsets.all(2.0),
          itemBuilder: (BuildContext context, int index) {
            return Container(
              child: Image.network(
                map.values.toList()[index]["pic"],
                fit: BoxFit.cover,
              ),
              padding: EdgeInsets.all(2.0),
            );
          },
        );
      } else {
        return CircularProgressIndicator();
      }
    });

void initState() {
  final FirebaseDatabase database = FirebaseDatabase(app: widget.app);
  database.setPersistenceEnabled(true);
  database.setPersistenceCacheSizeBytes(10000000);
  super.initState();
}
like image 132
Daniel Avatar answered Sep 28 '22 02:09

Daniel