Riverpod with Hooks doesn't rebuild ListView

Viewed 611

I've implemented a simple ListView using hooks_riverpod. There's a button that adds a new item(Other Store) to the ListView, but when I click it the ListView doesn't change. I know the item is being added to the list because I checked the value of storeList by printing it. Any ideas why the ListView.separated doesn't rebuild when the list changes?

Packages:
flutter_hooks: 0.17.0
hooks_riverpod: 0.14.0
state_notifier: 0.7.0

class StoreListController extends StateNotifier<List<String>> {
  StoreListController() : super(['First Store']);
  void add() => state.add('Other Store');
}
final storeListProvider =
    StateNotifierProvider<StoreListController, List<String>>(
  (_) => StoreListController(),
);

class HomePage extends HookWidget {
  @override
  Widget build(BuildContext context) {
    final storeList = useProvider(storeListProvider);
    return Scaffold(
      appBar: AppBar(
        title: Text('ListView Sample'),
      ),
      body: ListView.separated(
        itemBuilder: (context, index) => ListTile(
          title: Text(storeList[index]),
        ),
        itemCount: storeList.length,
        separatorBuilder: (context, index) => const Divider(),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => context.read(storeListProvider.notifier).add(),
        child: Icon(Icons.add),
      ),
    );
  }
}

1 Answers

The issue is how you are modifying your state in your StateNotifier.

For the state to update, you have to actually replace the state object.

Change your add function to the following:

void add() => state = [...state, 'Other Store'];

Here's an example from the developer of Riverpod that demonstrates array modifications as the state of a StateNotifier.

Related