Riverpod - Problem when combining providers

Viewed 1657

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

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

Related