1

我正在尝试使用 Riverpod 状态管理来组合提供者。在这种情况下,我正在创建一个视图模型,其中包含一个从该视图模型类中检索未来的函数。当我尝试从 VM 加载国家数据时,显示以下错误:

“'package:flutter_hooks/src/framework.dart':断言失败:第 489 行 pos 7:'!_debugIsInitHook':无法监听 HookState.initState 中继承的小部件。请改用 HookState.build”。

测试屏幕代码:

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")),
      ),
    );
  }
}

测试视图模型代码:

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);
}
4

1 回答 1

0

也许你可以尝试像这样实现它

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")),
    );
  }
}

这样,Hook 可以重建小部件,而不会显示尝试侦听 initState 更改的错误

于 2020-11-15T17:24:45.063 回答