'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?
Solution 1:[1]
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));
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ajit Kumar |