1

When the user clicks the FAB, i want it to create a new Card widget wrapped in a GestureDetector. I have created a list of type widget and also created a function with a setState to add to the list and display it in a SliverGrid. but when i click the FAB, it doesnt seem to be adding.

Could i get a small guide on how to add a Card using an FAB. (or adding any type of widget in a SliverGrid).

the list : List<Widget> cardList = <Widget>[];

function for adding items to the list :

void addItems() async{
  setState(() {
    cardList.insert(0, GestureDetector(
      onTap: () async {
        await Navigator.push( context, MaterialPageRoute(
          builder: (context) => TodoList(), // this just navigates to another screen ; not important in this question
        )
        );
      },
      child: Card(

          child:Center(child: whitefontstylemont(text: "project 1", size:20,)) //this is just a custom TextStyle
      ),
    ));
  });
}

the floating action button which adds a new Card to the list :

floatingActionButton:  FloatingActionButton( // this is inside a Scaffold
  onPressed: ()async {
    setState(() {
addItems();
    });
  },
  heroTag: "btn2",
  child: Icon(Icons.add, color: Color(whitecolor),), backgroundColor: Color(redcolor),),

the SliverGrid where i want a new card to be displayed :

SliverGrid(
  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
    crossAxisCount: 2
  ),
  delegate: new SliverChildBuilderDelegate((context, index) {
      return cardList[index];
    },
    childCount: cardList.length // this is where i want a new Card to be displayed
  )
),
Dmitry Garazhny
  • 344
  • 3
  • 12
  • First thing I would do is to not save Widgets in your State. In your case you can simply save the current number of cards in the screen, so just put an `int cardCount` in your State. Then build your cards in the SliverGrid – Martyns Sep 10 '19 at 07:27
  • Hey @Martyns! Sorry i am a bit new to flutter (and app development); could you just clarify on how i can use an ```int cardCount``` in the ```setState```? and how do i map it to the list ```cardList```? –  Sep 10 '19 at 08:13
  • 1
    Flutter needs to rebuild the widgets everytime you call setState. If you just save the Widget objects in a list in the State, those will not get rebuilt. When you press a button you can do `setState(() { cardCount += 1; })` Then, in the build method you can use a for loop to generate the list of Card widgets using that cardCount int – Martyns Sep 10 '19 at 08:34
  • I was able to generate a new ```Card``` using your ```setState``` method but it does seem to save the created cards when i reopen or hot restart the app. Could you please suggest me a method on how to save it when the app reopens? –  Sep 10 '19 at 09:59
  • You need to look at some persistent storage alternatives (Shared preferences, sqflite...) – Martyns Sep 10 '19 at 10:24

0 Answers0