Home > OS >  Flutter - Update items in a ListView
Flutter - Update items in a ListView

Time:10-24

I'm trying to change the order of widgets in a ListView as follows:

Widgets List

List<Widget> widgets = [const Text("Widget 1"), const Text("Widget 2")];

ListView

  ListView(children: widgets),

  Text("$widgets")

Function

() {
    widgets.shuffle();
    setState(() {
      widgets = widgets;
    });
  }
  

This way the order of widgets is changed in the TEXT but not in the list as I intended. Any idea?

CodePudding user response:

First solution: Add Key to List ListView like this:

ListView(
   key: UniqueKey(),// <--- add this
   children: widgets,
),

also in your Function you don't need to pass widgets again:

() {
    widgets.shuffle();
    setState(() {});
  }

Second solution: you can use SingleChildScrollView and Column like this:

Padding(
  padding: const EdgeInsets.all(20.0),
  child: SizedBox(
    height: 50,
    width: 100,
    child: SingleChildScrollView(
      child: Column(
        children: widgets,
      ),
    ),
  ),
),
  • Related