[Solved] Flutter How to put all the Widgets into a List<Widget>?

Question

Asked by Alfred on November 05, 2021 (source).

class _MyHomePageState extends State<MyHomePage> {
  List<int> _counters = [];
  List<Text> t = [];
  void _incrementCounter() {
    setState(() {
      for (var i = 0; i < _counters.length; i++) {
        _counters[i]++;
      }
    });
  }

  @override
  void initState() {
    super.initState();
    for (var i = 0; i < 20; i++) {
      _counters.add(i);
      t.add(Text('${_counters[i]}'));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: t,
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

I want to isolate the widget List<Widget> t = [];, but it doesn't work. Because I want to change the a part of the UI when the date changed. It's similar to VUE. Any suggestion?Thanks!

Answer

Question answered by Jahidul I (source).

you also need to call your List<Widget> in setState for rebuilding your widget

  int _counter = 2;
  List<Widget> t = [];
  void _incrementCounter() {
    setState(() {
      print("working $_counter");
      _counter++;
      t.add(Text('$_counter'));
    });
  }
FLUTTER
SHARE: