Search code examples
androidflutterdartflutter-layoutflutter-gridview

Add and remove columns childs inside Gridview


I write the code to add and remove columns inside Gridview at first load screen everything looks fine but when I remove any column on click the cross button inside the column it breaks the layout and does not remove any column whenever i click to remove column it shows error

Error: SliverGeometry is not valid: The "maxPaintExtent" is less than the "paintExtent".

Error Image: Error of layout during click/remove item

Here is my code :-

import 'package:flutter/material.dart';
import 'package:mindmatch/utils/widget_functions.dart';
import 'package:mindmatch/custom/BorderIcon.dart';
import 'package:mindmatch/screens/Relation.dart';
import 'package:flutter_svg/flutter_svg.dart';

void main() {
  runApp(new MaterialApp(
  home: new Photos(),
));
}

class Photos extends StatefulWidget {
 var usrid;

 Photos({Key? key, @required this.usrid}) : super(key: key);

 @override
 _Photos createState() => _Photos();
}

class _Photos extends State<Photos>{

 int counter = 0;
 //List<Widget> _list = new List<Widget>();
 List<Widget> _list = <Widget> [];


 @override
 void initState() {

  for(int i =0;  i < 4; i++){
        Widget child = _newItem(i);
        _list.add(child);
  }
 }

 void on_Clicked() {
  Widget child = _newItem(counter);
  setState(() => _list.add(child));
}

Widget _newItem(int i) {
 Key key = new Key('item_${i}');
 Column child = Column(
    key: key,
    children: [
      Stack(
          children:  [
            Card(
              elevation: 0,
              shape: RoundedRectangleBorder(
                side: BorderSide(
                  color: Color(0xffa1a1a1),
                ),
                borderRadius: BorderRadius.all(Radius.circular(12)),
              ),
              child: SizedBox(
                //width: 300,
                height: 100,
                child: Center(child:
                Icon(
                  Icons.image,
                  color: Color(0xffcccccc),
                  size: 60,
                ),

                ),
              ),
            ),
            Positioned(
              top: 9,
              right: 9,
              child: InkWell(
                onTap: () => _removeItem(key),
                child: SvgPicture.asset(
                  width: 20,
                  'assets/images/close.svg',
                  height: 20,
                ),
              ),
            )
          ]
      ),
    ]
);
counter++;
return child;
}

void _removeItem(Key key){
 for(int i = 0; i < _list.length; i++){
  Widget child = _list.elementAt(i);
  if(child.key == key){
    setState(() => _list.removeAt(i));
    print('Removing ${key.toString()}');
  }
 }
}


@override
Widget build(BuildContext context) {

 return new Scaffold(
  appBar: new AppBar(
    title: new Text('Photos'),
    backgroundColor: Colors.deepPurpleAccent,
  ),

  floatingActionButton: new FloatingActionButton(onPressed: on_Clicked, child: new 
  Icon(Icons.add),),

  body: new Container(
      padding: new EdgeInsets.all(32.0),
      child: Column(
        children: [
          Expanded(
              child: GridView(
                //padding: const EdgeInsets.all(8.0),
                gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 3,
                  crossAxisSpacing: 10.0,
                  mainAxisSpacing: 15,
                  //childAspectRatio: 2/1,
                ),
                children: _list,
              )
          )
        ],
      ),
  ),
);
}


}

And here is my output:- Output image of code where clearly see add and remove functionality

Please help out how I did this task and how I add and remove columns inside Gridview anyone, please help me.

And this is what I need to do:- this is actual layout i want to create So please help me


Solution

  • You should not operate the widget directly but data instead. What you should store in the list is the data (image URL or some string, which can be a very complex data structure) you want to present in the view and make the view respond to the changes happening on the object list with flutter's setState function.

    try this:

    import 'package:flutter/material.dart';
    
    void main() {
      runApp(new MaterialApp(
        home: new Photos(),
      ));
    }
    
    class Photos extends StatefulWidget {
      var usrid;
    
      Photos({Key? key, @required this.usrid}) : super(key: key);
    
      @override
      _Photos createState() => _Photos();
    }
    
    class _Photos extends State<Photos> {
      int counter = 0;
      //List<Widget> _list = new List<Widget>();
      List<String> _list = <String>[];
    
      @override
      void initState() {
        for (int i = 0; i < 4; i++) {
          _list.add("your data -obj");
        }
      }
    
      void on_Clicked() {
        setState(() => _list.add("your data -obj"));
      }
    
      Widget _newItem(int i) {
        Key key = new Key('item_${i}');
        Column child = Column(key: key, children: [
          Stack(children: [
            Card(
              elevation: 0,
              shape: RoundedRectangleBorder(
                side: BorderSide(
                  color: Color(0xffa1a1a1),
                ),
                borderRadius: BorderRadius.all(Radius.circular(12)),
              ),
              child: SizedBox(
                //width: 300,
                height: 80,
                child: Center(
                  child: Icon(
                    Icons.image,
                    color: Color(0xffcccccc),
                    size: 60,
                  ),
                ),
              ),
            ),
            Positioned(
              top: 9,
              right: 9,
              child: InkWell(onTap: () => _removeItem(i), child: Text('close')),
            )
          ]),
        ]);
        counter++;
        return child;
      }
    
      void _removeItem(int i) {
        print("====remove $i");
    
        print('===Removing $i');
        setState(() => _list.removeAt(i));
      }
    
      @override
      Widget build(BuildContext context) {
        return new Scaffold(
          appBar: new AppBar(
            title: new Text('Photos'),
            backgroundColor: Colors.deepPurpleAccent,
          ),
          floatingActionButton: new FloatingActionButton(
            onPressed: on_Clicked,
            child: new Icon(Icons.add),
          ),
          body: new Container(
            padding: new EdgeInsets.all(32.0),
            child: Column(
              children: [
                Expanded(
                    child: GridView(
                        //padding: const EdgeInsets.all(8.0),
                        gridDelegate:
                            const SliverGridDelegateWithFixedCrossAxisCount(
                          crossAxisCount: 3,
                          crossAxisSpacing: 10.0,
                          mainAxisSpacing: 15,
                          //childAspectRatio: 2/1,
                        ),
                        children: List.generate(_list.length, (index) {
                          //generating tiles with people from list
                          return _newItem(index);
                        })))
              ],
            ),
          ),
        );
      }
    }