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

时间:2019-01-13 23:59:52

标签: google-maps dart flutter

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

我有以下问题:

  1. 用户在地图的标签上
  2. “用户更改”标签(通过点击另一个)
  3. [问题],当用户返回“地图”标签页时,地图会重绘。

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

试图:

  • 使用PageStorage-失败。
  • 做出类似Map的状态的单调-没有成功。
  • 使用AutomaticKeepAliveClientMixin(saw here),它看起来很有希望,但仍然没有成功。

(我承认我做错了什么事

上次尝试的代码:

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时将其还原。或其他可以解决问题的东西。

4 个答案:

答案 0 :(得分:5)

使用IndexedStack

例如:

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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

答案 3 :(得分:0)

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

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

请参阅this线程。