I have read the other questions and while they do have similar titles to this one, they don't cover my issue. Please read below.

I'm using Android Studio. I have a simple stateful app with a GridView. Its children are in a list "geza". When I press the button a Text('Hello') is added to the list.

This is done inside the setState() method. The newly added widget will not appear in the grid.

If I do a hot-redeploy from Android studio, then after the redeploy the widget will show up. So it looks like the widget is added to the list, but the Grid is not updated.

What am I doing wrong?

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key}) : super(key: key);

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

class _MyHomePageState extends State<MyHomePage> {

  var geza = <Widget>[ Text('AAA') ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('My Test'),
      ),
      body: Center(
        child: GridView.count(crossAxisCount: 2,
          children: this.geza
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            this.geza.add(Text('Hello'));
          });
        },
        child: Icon(Icons.add),
      ),
    );
  }
}


Solution 1: enzo

I think Flutter treats list of widgets specially, as you can see in this similar case. This solution uses ListView.builder: in your case, you can use a GridView.builder, but you can also use strings instead of widgets inside your geza list to avoid any further problems:

class _MyHomePageState extends State<MyHomePage> {
  // Use a list of strings
  final List<String> geza = ['AAA'];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('My Test'),
      ),
      body: Center(
        child: GridView.count(
          crossAxisCount: 2,
          // Convert to a list of widgets here
          children: this.geza.map((v) => Text(v)).toList(),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          // Add a string to the list
          setState(() => this.geza.add('Hello'));
        },
        child: Icon(Icons.add),
      ),
    );
  }
}


Solution 2: Tirth Patel

You could use spread operator (...) to solve this issue.

GridView.count(
  crossAxisCount: 2,
  children: [
    ...geza
  ],
),