I'm trying to use an Inherited Widget to share the same service across all the screens.
This is the code of my Inherited Widget:
class GlobalValues extends InheritedWidget {
final AudioProvider audioProvider;
GlobalValues({Key key, Widget child, this.audioProvider}) : super(key: key, child: child);
static AudioProvider of(BuildContext context){
return (context.dependOnInheritedWidgetOfExactType<GlobalValues>()).audioProvider;
}
@override
bool updateShouldNotify(InheritedWidget oldWidget) {
return false;
}
}
Therefore, I initialize it in the Home Screen:
@override
Widget build(BuildContext context) {
double width = MediaQuery.of(context).size.width;
return GlobalValues(
audioProvider: AudioProvider(),
child: StreamBuilder<MapEntry<Position, List<MuseumCard>>>(...)
);
}
and finally I would like to access it from a subsequent screen:
@override
Widget build(BuildContext context) {
super.build(context);
AudioProvider audioProvider = GlobalValues.of(context);
Return Scaffold(...);
}
But when the last screen is built I got this error message:
The getter 'audioProvider' was called on null. Receiver: null Tried calling: audioProvider
I'm noticing that if I initialize the widget in the main.dart then the error doesn't show up and everything works correctly:
@override
Widget build(BuildContext context) {
return GlobalValues(
audioProvider: AudioProvider(),
child: MaterialApp(...),);
}
But I would like to make it available only in a certain part of widget subtree, but don't know why it doesn't work.
Could it be due to routing between the screens? Or what other reason?
Thank you