Flutter Hooks Riverpod not updating widget despite provider being refreshed

Issue

I’ve been studying flutter for a couple of months and I am now experimenting with Hooks and Riverpod which would be very important so some results can be cached by the provider and reused and only really re-fetched when there’s an update.

But I hit a point here with an issue where I can’t wrap my head around the provider update to reflect in the Widget. Full example can be checked out from here -> https://github.com/codespair/riverpod_update_issue I’ve added some debug printing and I can see the provider is properly refreshed but the changes don’t reflect on the widget.

The example has a working sample provider:

// create simple FutureProvider with respective future call next
final futureListProvider =
    FutureProvider.family<List<String>, int>((ref, value) => _getList(value));

// in a real case there would be an await call inside this function to network or local db or file system, etc...
Future<List<String>> _getList(int value) async {
  List<String> result = [...validValues];
  if (value == -1) {
    // do nothing just return original result...
  } else {
    result = []..add(result[value]);
  }
  debugPrint('Provider refreshed, result => $result');
  return result;
}

a drop down list when changed refreshes the provider:

             Container(
                  alignment: Alignment.center,
                  padding: EdgeInsets.fromLTRB(5, 2, 5, 1),
                  child: DropdownButton<String>(
                    key: UniqueKey(),
                    value: dropDownValue.value.toString(),
                    icon: Icon(Icons.arrow_drop_down),
                    iconSize: 24,
                    elevation: 16,
                    underline: Container(
                      height: 1,
                      color: Theme.of(context).primaryColor,
                    ),
                    onChanged: (String? newValue) {
                      dropDownValue.value = newValue!;
                      context
                          .refresh(futureListProvider(intFromString(newValue)));
                    },
                    items: validValues
                        .map<DropdownMenuItem<String>>((String value) {
                      return DropdownMenuItem<String>(
                        value: value,
                        child: Text(
                          value,
                          style: Theme.of(context).primaryTextTheme.subtitle1,
                        ),
                      );
                    }).toList(),
                  ),
                ),

And a simple list which uses the provider elements to render which despite the provider being properly refreshed as you can see in the debugPrinting it never updates:

Container(
          key: UniqueKey(),
          height: 200,
          child: stringListProvider.when(
            data: (stringList) {
              debugPrint('List from Provider.when $stringList');
              return MyListWidget(stringList);
              // return _buildList(stringList);
            },
            loading: () => CircularProgressIndicator(),
            error: (_, __) => Text('OOOPsss error'),
          ),
        ),
      ]),


class MyListWidget extends HookWidget {
  final GlobalKey<ScaffoldState> _widgetKey = GlobalKey<ScaffoldState>();
  final List<String> stringList;

  MyListWidget(this.stringList);

  @override
  Widget build(BuildContext context) {
    debugPrint('stringList in MyListWidget.build $stringList');
    return ListView.builder(
      key: _widgetKey,
      itemCount: stringList.length,
      itemBuilder: (BuildContext context, int index) {
        return Card(
          key: UniqueKey(),
          child: Padding(
              padding: EdgeInsets.all(10), child: Text(stringList[index])),
        );
      },
    );
  }

As I am evaluating approaches to develop some applications I am getting inclined to adopt a more straightforward approach to handle such cases so I am also open to evaluate simpler, more straightforward approaches but I really like some of the features like the useMemoized, useState from hooks_riverpod.

Solution

One thing I wanted to note before we get started is you can still use useMemoized, useState, etc. without hooks_riverpod, with flutter_hooks.

As far as your problem, you are misusing family. When you pass a new value into family, you are actually creating another provider. That’s why your list prints correctly, because it is, but the correct result is stuck in a ProviderFamily you aren’t reading.

The simpler approach is to create a StateProvider that you use to store the currently selected value and watch that provider from your FutureProvider. It will update the list automatically without having to refresh.

final selectedItemProvider = StateProvider<int>((_) => -1);

final futureListProvider = FutureProvider<List<String>>((ref) async {
  final selected = ref.watch(selectedItemProvider).state;
  return _getList(selected);
});

DropdownButton<String>(
  ...
  onChanged: (String? newValue) {
    dropDownValue.value = newValue!;
    context.read(selectedItemProvider).state = intFromString(newValue);
  },
}

Answered By – Alex Hartford

Answer Checked By – Robin (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *