Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter GridView.builder how to update

I am trying to build an Flutter App with a GriView of cards and I want to add a new Card every time I hit the floatingActionButton. But how to update my view? I know the items are added to my list, but the GridView doesn't show the change.

  List<Widget> cardsList = [];

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: AppBar(
        title: Text('Team Kitty'),
      ),
      body: GridView.builder(
          itemCount: cardsList.length,
          gridDelegate:
              SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3),
          itemBuilder: (BuildContext context, int index) {
            return Container(child: cardsList[index]);
          }),
      floatingActionButton: new FloatingActionButton(
        onPressed: addCard(),
        tooltip: 'Add Card',
        child: new Icon(Icons.add),
      ),
    );
  }
  addCard() {
    setState(() {
      cardsList.add(_RobotCard());
    });
  }
}

I find it hard to find good Grid documentation, maybe someone has a hint?

Thx Guys

like image 851
FuzzyTemper Avatar asked Apr 08 '26 23:04

FuzzyTemper


1 Answers

You invoke addCard method while your widget is built instead of passing method's reference as onPressed parameter:

floatingActionButton: new FloatingActionButton(
  onPressed: addCard, // pass method reference here
  tooltip: 'Add Card',
  child: new Icon(Icons.add),
)
like image 198
tomwyr Avatar answered Apr 11 '26 12:04

tomwyr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!