I am trying to share the current location of an user within the app in other routes.
My widget tree is quite extensive to keep passing the value down, so I would like to get it easier and updated in a interval of 1 minute in the widgets below.
I've tried Provider and Inherited widget but my value is null and I'm getting the error:
The following NoSuchMethodError was thrown building:
The getter 'currentPosition' was called on null.
Receiver: null
Tried calling: currentPosition
My initial class
class _HomeScreenState extends State<HomeScreen> {
Placemark _currentPlaceMark;
Position _currentPosition =
Position(longitude: -23.708422, latitude: -46.5568553);
initState() {
super.initState();
//Get the current location of user
_determinePosition();
}
@override
Widget build(BuildContext context) {
return CurrentPositionInherited(
child: MaterialApp(
debugShowCheckedModeBanner: false,
title: mainTitleApp,
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: Scaffold(
drawer: CustomDrawer(),
appBar: AppBar(
title: Text(mainTitleApp),
),
body: BodyCategoriesList()),
),
currentPosition: _currentPosition,
);
}
The method I call at Init to determine the current position
void _determinePosition() async {
var pos = await Geolocator.getCurrentPosition();
setState(() {
_currentPosition = pos;
});
placemarkFromCoordinates(pos.latitude, pos.longitude)
.then((value) => setState(() {
_currentPlaceMark = value.first;
}));
}
My Inherited Widget
class CurrentPositionInherited extends InheritedWidget {
const CurrentPositionInherited({
Key key,
@required this.currentPosition,
@required Widget child,
}) : assert(child != null),
super(key: key, child: child);
final Position currentPosition;
static CurrentPositionInherited of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType()
as CurrentPositionInherited;
}
@override
bool updateShouldNotify(CurrentPositionInherited old) =>
currentPosition != old.currentPosition;
}
inside the BodyCategoriesList() It has 2 layers of widgets that led to other routes (because I call the MaterialPageRoute to build other pages) and then I try to call the location property using this approach:
Widget _buildSubtitle(RatingModel rating, BuildContext context) {
print(CurrentPositionInherited.of(context)
.currentPosition
.latitude
.toString());
}
I just want to share my current location updated in this deep widget but I couldn't achieve that and I am trying for hours!