【发布时间】:2025-12-17 14:45:01
【问题描述】:
我有一个基本的有状态应用程序,带有一个 GoogleMap 基础,它在 FloatingActionButton 按下时打开一个 BottomSheet。这用作设置选项卡以更改/过滤一些列表,然后由地图使用。我的 Provider 已设置,可以从 GoogleMap dart 文件和 BottomSheet dart 文件中读取/保存值。
我的主要问题是如何在不在小部件树中时为Provider.of() 提供上下文。例如,GoogleMap 在完成加载后运行onMapCreated: _onMapCreated,。从该函数中,我想从 Provider.of() 中提取一个字符串值,它告诉我要使用哪个列表(然后填充标记)。
我正在尝试做的事情:
- onMapCreated() 从 Provider 拉取值(稍后在 DB sqflite 查询中使用)
- bottomsheet 需要以某种方式回调和
updateMarkers(),以提供正确的上下文
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
GoogleMapController mapController;
void _onMapCreated(GoogleMapController controller) {
mapController = controller;
print(Provider.of<MyAppStateContainer>(context, listen:false).getSomeValue); <---- Doesn't work
...
}
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider<MyAppStateContainer>(
create: (contextooo) => MyAppStateContainer(),
child: MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('My Map'),
backgroundColor: Colors.green[700],
),
//Put in a stack widget so can layer other widgets on top of map widget
body: Stack(
children: <Widget>[
//Builder so we can get a CTX made, and then Provider.of() finds the Provider
Builder(
builder: (context) => GoogleMap(
mapType: Provider.of<MyAppStateContainer>(context).getMapType, <--- Works fine
markers: _markers,
onMapCreated: _onMapCreated,
...
}
提供者:
class MyAppStateContainer extends ChangeNotifier {
MyAppStateContainer();
MapType _mapType = MapType.terrain;
String _someValue;
MapType get getMapType => _mapType;
String get getSomeValue => _someValue;
}
我已经尝试了各种回传BuildContext context 的组合,但遗憾的是我永远都会收到关于 Widget Tree 的错误:
Unhandled Exception: Error: Could not find the correct Provider<MyAppStateContainer> above this MyApp Widget
【问题讨论】:
标签: google-maps flutter android-context flutter-provider