Home > Back-end >  Flutter How to put all the Widgets into a List<Widget>?
Flutter How to put all the Widgets into a List<Widget>?

Time:11-05

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!

CodePudding user response:

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'));
    });
  }
  • Related