简体   繁体   中英

Riverpod - Problem when combining providers

I am trying to combine providers using Riverpod state management. 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:

"'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".

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM