Riverpod - 合并供应商时出现问题

Riverpod - Problem when combining providers

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

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

TestViewModel 代码:

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

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

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可以重建widget而不显示试图监听initState变化的错误