我想将go_router
(https://pub.dev/packages/go_router#redirection)与Riverpod
一起使用。
我有一个Provider
和一个StreamProvider
,我想把它们组合成一个Listenable
,这样它就可以用作GoRouter
的refreshListenable
参数。
我想我需要将Provider
和StreamProvider
组合成某种Provider
(如何?)。
从Provider
创建Listenable
最简单的方法是什么?
编辑:我明白这"否定"了Riverpod的意义,但应用程序已经与Riverpod一起设置好了,我只是想添加go_router。
有一个更简单的方法,ChangeNotifier可以与Riverpod一起使用。在Riverpod的Github回购上有一个Github问题。https://github.com/rrousselGit/river_pod/issues/884
回答蒂姆些微Gihtub(他的下面的代码和注释):
您可以使用ChangeNotifier与flutter_riverpod。
final myNotifierProvider = ChangeNotifierProvider<MyNotifier>((ref) => MyNotifier());
class MyNotifier with ChangeNotifier {
void refresh(){
notifyListeners();
}
}
然后你必须观察你试图传递Listenable的提供者。
// 1.0.0-dev riverpod
refreshListenable: ref.watch(myNotifierProvider)
// 0.14.0
refreshListenable: watch(myNotifierProvider) // using a Consumer / ConsumerWidget
在其他地方使用
// 1.0.0-dev riverpod
ref.read(myNotifierProvider.notifier).refresh();
// 0.14.0
context.read(myNotifierProvider.notifier).refresh();
我是这样解决的:
class AListenable extends ValueNotifier {
AListenable(value) : super(value);
void changeValue(newValue) {
value = newValue;
}
}
final aListenableInstance = AListenable(false);
final myProvider = Provider((ref) {
final my2ndProviderValue = ref.watch(my2ndProvider);
if (my2ndProviderValue is AsyncError || my2ndProviderValue is AsyncLoading) {
aListenableInstance.changeValue(false);
return false;
}
aListenableInstance.changeValue(true);
return true;
});
final _router = GoRouter(
refreshListenable: aListenableInstance,...);
如果你想集中使用riverpod,你可以直接使用它来导航,而不需要go_router。这里有一个有趣的问题:river_pod问题1122