Flutter:如何使小部件与Google Map保持不变?

AQR*_*QRC 10 google-maps dart flutter

我正在使用Google Maps for Flutter小部件。在我的应用程序中,地图是通过BottomNavigationBar的选项卡之一显示的。

而且我有以下问题:

  1. 用户在地图的标签上
  2. 用户更改选项卡(通过点击另一选项卡)
  3. [问题]当用户返回地图的选项卡时,地图将重绘。

我想保持地图在用户离开“地图”选项卡时的状态,以便他以后再返回时可以继续使用它。

试着:

  • 使用PageStorage-没有成功。
  • 制作类似Map的状态的Singletone-失败。
  • 使用AutomaticKeepAliveClientMixin(在此处看到),它看起来很有希望,但仍然没有成功。

(我承认我做错了什么)

上次尝试的代码:

class MapScreen extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => MapScreenState();
}

class MapScreenState extends State<MapScreen> with AutomaticKeepAliveClientMixin {
  GoogleMapController mapController;

  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
        appBar: AppBar(
          title: const Text("Map"),
        ),
        body: GoogleMap(
          onMapCreated: _onMapCreated,
        )
    );
  }

  void _onMapCreated(GoogleMapController controller) {
      mapController = controller;
      updateKeepAlive();
  }
}
Run Code Online (Sandbox Code Playgroud)

因此,我只需要一种方法来保持MapScreen处于活动状态且保持不变,或者以某种方式存储其状态并在用户返回MapScreen时将其还原。或者其他可以解决问题的方法。

Aar*_*onJ 6

使用索引堆栈

例如:

Class _ExamplePageState extends State<ExamplePage> {
  int _bottomNavIndex = 0;

  final List<Widget> _children = [
    WidgetOne(),
    WidgetTwo(),
    GoogleMap(),
  ]

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: IndexedStack(
        index: _bottomNavIndex,
        children: _children,
      ),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _bottomNavIndex,
        onTap: (index) {
          if (_bottomNavIndex == index) return;
          setState(() {
            _bottomNavIndex = index;
          });
        }
        items: [ ... ]
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)


die*_*per 3

Widget总是在从一个页面更改到另一个页面后重建,因此,尝试这个,使用变量并重GoogleMap用(如果它与 null 不同)。

    GoogleMap _map;

     @override
    Widget build(BuildContext context) {
      if (_map == null){
        _map =  GoogleMap(
            onMapCreated: _onMapCreated,
          );
      }
      return Scaffold(
          appBar: AppBar(
            title: const Text("Map"),
          ),
          body:_map,
      );
    }
Run Code Online (Sandbox Code Playgroud)

  • 我是。甚至让 State&lt;GoogleMap&gt; 使用它,但它没有帮助。现在,我将按照 Ian 的建议存储相机位置和所有其他数据。如果我找到或提出解决方案,我会将其发布在这里 (2认同)