UnicornsOnLSD
UnicornsOnLSD

Reputation: 773

How should I access a Riverpod provider from a different file?

I'm used to provider's Provider.of() call to get a provider from elsewhere in the widget tree, but every Riverpod resource I've found relies on having access to the provider variable already (by having both widgets in the same file). For a provider that only reaches through two widgets, passing this variable is simple enough, but I don't see this being feasible for accessing providers that are created high up in the widget tree. Is there a proper way to get a provider?

Upvotes: 5

Views: 2536

Answers (1)

Alex Hartford
Alex Hartford

Reputation: 5970

You can simply import the file that the provider is defined in. Riverpod providers are created in global scope, therefore accessible anywhere.

For example:

// hello_provider.dart
import 'package:flutter_riverpod/flutter_riverpod.dart';

final helloWorld = Provider<String>((_) => 'Hello World');
// widget.dart
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:my_app/hello_provider.dart'

class MyWidget extends ConsumerWidget {
  @override
  Widget build(BuildContext context, ScopedReader watch) {
    return Text(watch(helloWorld));
  }
}

Upvotes: 10

Related Questions