How to insert children into Grid View from model List

In this example, we are going to show you how to make a model class, and make a list of model data and populate them into Grid View. This is a simple example to understand the method to insert data into Grid View. You can make a list from JSON string as well using Model class. We have commented the code to convert JSON string to model data.

See the example below to learn how to insert children inside Grid View from a list of model data. Please read the comments in the code for better understandings.

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

//apply this class to home: attribute of MaterialApp()
class MyGridView extends StatefulWidget{
  @override
  _MyGridViewState createState(){
    return _MyGridViewState();
  } 
}

class _MyGridViewState extends State<MyGridView> {
  List<PeopleOne> peoplelist; //list array variable for peoples

  @override
  void initState() {

    peoplelist = [ 
        PeopleOne(id:"1", name:"Poonam", address:"Kathmandu, Nepal"),
        PeopleOne(id:"2", name:"Krishna", address:"Lumbini, Nepal"),
        PeopleOne(id:"3", name:"Anil", address:"Chaumala, Nepal"),
        PeopleOne(id:"4", name:"Arjun", address:"Kailali, Nepal"),
        PeopleOne(id:"5", name:"Karan", address:"Dhangadhu, Nepal"),
        PeopleOne(id:"6", name:"Saroj", address:"Pokhara, Nepal"),
    ];  //list of peoples using PeopleOne model class, you can convert from JSON too

    //OR to convert from JSON

   /*
    peoplelist = List<PeopleOne>.from(
      jsonstring.map((dataone){
          return PeopleOne.fromJSON(dataone); 
          //return of factory of PeopleOne
      })
    ); 
   */

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
      return Scaffold( 
        appBar: AppBar(
          title:Text("GridView People List"),
          backgroundColor: Colors.redAccent
        ),

        body:GridView.count( //use GridView.count for independent to silver layout
            crossAxisCount: 2, //
            //scrollDirection: Axis.horizontal, //set this for horizontal scroll direction
            shrinkWrap: true,
            children: peoplelist.map((people){ //user peoplelist.map to loop over the list
                return Card( 
                  elevation: 10, //shadow elevation for card
                  margin: EdgeInsets.all(8),
                  child:Container(
                      color: Colors.orange[100],
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center, //main axix alignemnt to center
                        children: <Widget>[
                         Text(people.name, style: TextStyle(fontSize:20)),
                         Text(people.address, style: TextStyle(fontSize:13)),

                         Container( 
                           margin: EdgeInsets.only(top:20),
                           child:RaisedButton.icon(
                              onPressed: (){ 
                                  print('Clicked on view details: ' + people.id);
                                  //add more action for this button
                                  //Navigator.push() to show details in new page
                              }, 
                              icon: Icon(Icons.person), 
                              label: Text("View Details"),
                              color: Colors.redAccent,
                              colorBrightness: Brightness.dark,
                               //color brightness is dark becaause its background is dark color
                            )
                         ),

                         Container( 
                           margin: EdgeInsets.only(top:0),
                           child:RaisedButton.icon(
                              onPressed: (){ 
                                  print('Clicked on send email: ' + people.id);
                                  //add more action for this button
                                  //Navigator.push() to show details in new page
                              }, 
                              icon: Icon(Icons.mail), 
                              label: Text("Send Email"),
                              color: Colors.blueAccent,
                              colorBrightness: Brightness.dark,
                               //color brightness is dark becaause its background is dark color
                            )
                         )
                      ],) 
                    )
                );
            }).toList(), //don't forget to to add .toList() at last of map
          )
      );
  }
}

//model class for people information
class PeopleOne{
   String id, name, address;
   PeopleOne({this.id, this.name, this.address});
   //constructure for class

   /* factory to convert json string to model data
   factory PeopleOne.fromJSON(Map<String, dynamic> json){
     return PeopleOne(
       id: json["id"],
       name: json["name"],
       address: json["address"]
     );
   } */ 
}

Output:

In this way, you can create your Grid View with the list of data models.

No any Comments on this Article


Please Wait...