简体   繁体   中英

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

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM