Home > Software engineering >  How to useState of List<int> in Flutter hooks?
How to useState of List<int> in Flutter hooks?

Time:10-10

I have very simple case of using flutter hooks:

class PositionedTiles extends HookWidget {
  @override
  Widget build(BuildContext context) {
    final counterList = useState<List<int>>([1,2,3,4,5]);
    return Scaffold(
        body: Text("Counter: ${counterList.value}"),
        floatingActionButton: FloatingActionButton(
              onPressed: () => counterList.value.removeAt(0),
              child: const Icon(Icons.sentiment_very_satisfied)),
        );
    );
  }

So, after click floatingActionButton the printed list (counterList) doesn't change. I conclude that rebuild is not invoked.

Why hook doesn't see that the list has been changed?

How to signal that the list (counterList) has been changed after onPressed invoked in order to rebuild?

CodePudding user response:

To update the state you need to reassign the list.

onPressed: () {
  counterList.value = [...counterList.value..removeAt(0)];
  log("${counterList.value}");
},
  • Related