Flutter: Creating GridView From Firebase Realtime DB items

Viewed 1916

Currently, in my app's homescreen I have a firebase_animated_list widget which creates a listView. However, I want to show these items in a GridView because it'll look much better.

Here's my code snippet.

body: Column(
          children: <Widget>[
            Flexible(
              child: FirebaseAnimatedList(
                query: firebaseRef,
                itemBuilder: (BuildContext context, DataSnapshot snapshot,
                    Animation<double> animation, int index) {
                  return InkWell(
                    child: ListTile(
                      contentPadding: EdgeInsets.all(7),
                      title: Text(mynode[index].key),
                      leading: CircleAvatar(
                        radius: 30,
                        child: FittedBox(
                          child: Text(mynode[index].id),
                        ),
                      ),
                      trailing: Icon(Icons.play_arrow),
                      onTap: () => Navigator.of(context).push(
                        MaterialPageRoute(
                          builder: (context) => DemoDb(
                            id: othernode[index].id,
                          ),
                        ),
                      ),
                    ),
                  );
                },
              ),
            ),
          ],
        ),

This perfectly creates a list of items but how should I change it to a GridView? I tried using GridView.count in place of ListTile widget. but because it was nested inside the firebase_animated_list , Each grid is layed out inside this animated list.

Is there any plugins or libraries that can help me in this? perhaps a code snippet Or if someone can suggest me any better approach to achieve this, it would mean world to me.

Thank You.

1 Answers

try Using StreamBuilder to load the items in a map and then use a Gridview and then you can populate the Gridview with your data.

have a look at the following Example:

Here we have a model of the data that we're trying to pull from firebase.

class Product {

  String key;
  String cardid;
  String cardname;
  String cardimage;
  int cardprice;
  String carddiscription;
 

  Product(this.key,this.cardid,this.cardname,this.cardimage,this.cardprice,this.carddiscription);

  
}

and here is how to implement a GridView inside a StreamBuilder and populate it with the data:

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


              products.clear();

             map.forEach((dynamic, v) =>
                 products.add( new Product(v["key"],v["cardid"] , v["cardname"],v["cardimage"] ,v["cardprice"], v["carddiscription"]))
             );

              return GridView.builder(
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 2),
                itemCount: products.length,
                padding: EdgeInsets.all(2.0),
                itemBuilder: (BuildContext context, int index) {
                  return     GestureDetector(
                    onTap: (){

                    },
                    child: Padding(
                      padding: EdgeInsets.all(5),
                      child: Container(

                        width: (screenWidth(context)/2)-15,
                        height: 150,
                        decoration: BoxDecoration(

                          shape: BoxShape.rectangle,
                          borderRadius: BorderRadius.all(Radius.circular(15.0)),
                          image: DecorationImage(
                            image: NetworkImage(products[index].cardimage),
                            fit: BoxFit.cover,
                          ),
                        ),
                        child:  Padding(
                          padding: EdgeInsets.all(0),
                          child: Container(

                            decoration: BoxDecoration(
                              shape: BoxShape.rectangle,
                              borderRadius: BorderRadius.all(Radius.circular(15.0)),
                              gradient: new LinearGradient(
                                  colors: [
                                    Colors.black,
                                    const Color(0x19000000),
                                  ],
                                  begin: const FractionalOffset(0.0, 1.0),
                                  end: const FractionalOffset(0.0, 0.0),
                                  stops: [0.0, 1.0],
                                  tileMode: TileMode.clamp),
                            ),
                            child: Padding(
                              padding: EdgeInsets.all(10),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                mainAxisAlignment: MainAxisAlignment.end,
                                children: [
                                  Text(
                                    products[index].cardname,
                                    style: TextStyle(fontSize: 20, fontWeight: FontWeight.w500,color: Colors.white),
                                  ),
                                  Text('Rs. ${products[index].cardprice}'
                                    ,
                                    style: TextStyle(fontSize: 20, fontWeight: FontWeight.w200,color: Colors.white),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ), /* add child content here */
                      ),
                    ),
                  );

},
              );
            } else {
              return CircularProgressIndicator();
            }
          }),

Output

Related