raman raman
raman raman

Reputation: 1811

How can I create staggered grid view like this in flutter

enter image description here If you need more info then please comment.Thank you

How can I create flutter staggered grid view like this with headerTile + image in each grid tile + centered texts

Upvotes: 0

Views: 2058

Answers (1)

Ravinder Kumar
Ravinder Kumar

Reputation: 7990

First, create a child and parent model class, ParentModel contains a header text as well list of its children,

class ParentModel {
  String title;
  List<ChildModel> list;
  ParentModel(this.title, this.list);
}

class ChildModel {
  String text;
  ChildModel(this.text);
}

Then create a ListView, this list will contain title as well as a grid of its children.

class ComplexList extends StatefulWidget {
  @override
  _ComplexListState createState() => _ComplexListState();
}

class _ComplexListState extends State<ComplexList> {
  List<ParentModel> parentList = List();

  @override
  void initState() {
    super.initState();
// this list is just to add dummy data, replace this with your list from api
    List<ChildModel> childList = List();
    childList.add(ChildModel('Child1'));
    childList.add(ChildModel('Child2'));
    childList.add(ChildModel('Child3'));
    childList.add(ChildModel('Child4'));
    List<ChildModel> childList1 = List();
    childList1.add(ChildModel('Child5'));
    childList1.add(ChildModel('Child6'));
    childList1.add(ChildModel('Child7'));
    childList1.add(ChildModel('Child8'));
    parentList.add(ParentModel('Title1', childList));
    parentList.add(ParentModel('Title2', childList1));
  }

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
        itemCount: parentList.length,
        itemBuilder: (context, index) {
          ParentModel parentModel = parentList[index];
          return Column(
            children: <Widget>[Text('${parentModel.title}',style: TextStyle(fontSize: 16),),
              GridView.count(
                shrinkWrap: true,
                // Create a grid with 2 columns. If you change the scrollDirection to
                // horizontal, this produces 2 rows.
                crossAxisCount: 2,
                // Generate 100 widgets that display their index in the List.
                children: List.generate(parentModel.list.length, (index) {
                  ChildModel childModel = parentModel.list[index];
                  return Card(

                    child: Center(
                      child: Text(
                        'Item ${childModel.text}',
                        style: Theme
                            .of(context)
                            .textTheme
                            .headline,
                      ),
                    ),
                  );
                }),
              ),
            ],
          );
        });
  }
}

The output of this code,

enter image description here

Upvotes: 2

Related Questions