[英]Riverpod - Problem when combining providers
I am trying to combine providers using Riverpod state management.我正在尝试结合使用 Riverpod state 管理的提供商。 In this scenario, I am creating a view model which contains a function that retrieves a future from that view model class. When I try to load the country data from the VM, the following error is displayed:
在这种情况下,我正在创建一个视图 model,其中包含一个 function,它从该视图 model class 中检索未来。当我尝试从 VM 加载国家/地区数据时,显示以下错误:
"'package:flutter_hooks/src/framework.dart': Failed assertion: line 489 pos 7: ':_debugIsInitHook'. Cannot listen to inherited widgets inside HookState.initState. Use HookState.build instead". “'package:flutter_hooks/src/framework.dart':断言失败:第 489 行 pos 7:':_debugIsInitHook'。无法收听 HookState.initState 内的继承小部件。改用 HookState.build”。
TestScreen code:测试屏幕代码:
var viewModel =
Provider<TestViewModel>((ref) => TestViewModel(ref.read));
var countryProvider = FutureProvider<Country>((ref) {
var vm = ref.watch(viewModel);
return vm.getCountryData();
});
class TestScreen extends HookWidget {
@override
Widget build(BuildContext context) {
var country = useProvider(countryProvider);
return Scaffold(
appBar: AppBar(title: 'Test'),
body: country.when(
loading: () => Container(),
error: (err, stack) => Center(child: Text(err.toString())),
data: (country) => Center(child: Text("Success")),
),
);
}
}
TestViewModel code:测试视图模型代码:
class TestViewModel {
final Reader read;
SessionRepository _session;
Destination get dest => _session.destination;
TestViewModel (this.read) : _session = read(sessionProvider);
// A function that returns a Future
Future<Country> getCountryData() => Country.getData(dest.countryName);
}
Maybe you could try implementing it like this也许你可以尝试像这样实现它
class Home extends StatelessWidget{
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: 'Test'),
body: TestScreen();
);
}
}
class TestScreen extends HookWidget {
@override
Widget build(BuildContext context) {
return useProvider(countryProvider).when(
loading: () => Container(),
error: (err, stack) => Center(child: Text(err.toString())),
data: (country) => Center(child: Text("Success")),
);
}
}
This way the Hook can rebuild the widget without displaying the error of trying to listening to changes in the initState这样 Hook 就可以重建 widget 而不会显示尝试监听 initState 变化的错误
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.