【问题标题】:Flutter GoogleMap Provider Context problemFlutter GoogleMap Provider Context问题
【发布时间】: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&lt;MyAppStateContainer&gt; above this MyApp Widget

【问题讨论】:

    标签: google-maps flutter android-context flutter-provider


    【解决方案1】:

    问题是在_onMapCreated 中,您尝试使用MyApp 的上下文访问Provider,它比Provider 本身在小部件的层次结构中更高。

    将您的home 小部件(脚手架及其下方的所有内容)转换为单独的StatefulWidget,一切都应该开始工作,因为您将使用新小部件的上下文,它位于小部件层次结构的较低位置比Provider

    【讨论】:

    • 这回答了我的问题,Provider.of() 现在提取了正确的值。然而,它引入了一个新问题——也许是一个新问题,但仍然与国家有关。现在,当我更改值并调用 mainAppState.setState() - mainAppState 一个使用 this 传递的参数时,showBottomSheet UI 不会刷新
    • 好的,我解决了这个问题。非常感谢您的回答。问题解决了