繁体   English   中英

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

[英]Flutter: how to keep widget with Google Map unchanged?

我正在使用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();
  }
}

所以,我只需要一种方法来保持 MapScreen 处于活动状态并保持不变,或者以某种方式存储其状态并在用户返回 MapScreen 时恢复它。 或者其他可以解决问题的东西。

使用索引堆栈

例如:

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: [ ... ]
      ),
    );
  }
}

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,
      );
    }

我只是遇到了同样的问题,mixin 解决了它。 我认为您刚刚错过了在声明末尾输入 mixin 的类型。

class MapScreenState extends State<MapScreen> with AutomaticKeepAliveClientMixin<MapScreenState>

如果有的话,请参阅线程。

请注意,Google Maps小部件的版本为0.2,处于开发人员预览状态。 某些行为可能会随着时间而改变。 请勿在生产中使用此功能。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM