Search code examples
flutterflutter-providerfirebase-remote-configriverpod

Riverpod Alternative To SetUpLocator


I want to call my Remote Config Instance on Flutter App StartUp I have set up Riverpod as follows

class ConfigService {
  // Will Initialise here
  final RemoteConfig _remoteConfig;
  ConfigService(this._remoteConfig);

  Future<void> initialise() async {
  ...// Will fetchAndActivate
}

final remoteConfigProvider = Provider<RemoteConfig>((ref) {
  return RemoteConfig.instance;
});

final configProvider = Provider<ConfigService>((ref) {
  final _config = ref.read(remoteConfigProvider);
  return ConfigService(_config);
});

I would want to call it in the main after

...
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
... here

But this can't be done because one needs a Reader and the ProviderScope is below this level

How do I call this provider in my main ?


Solution

  • The short answer is you can't. What you should do is call the Provider within the ProviderScope.

    Future<void> main() async {
      WidgetsFlutterBinding.ensureInitialized();
      await Firebase.initializeApp();
      runApp(
        ProviderScope(
          child: MyApp(),
        ),
      );
    }
    
    class MyApp extends ConsumerWidget {
      const MyApp({Key? key}) : super(key: key);
    
      @override
      Widget build(BuildContext context, ScopedReader watch) {
        final config = watch(configProvider);
        return Container();
      }
    }