我正在使用Google Maps for Flutter小部件。 在我的应用程序地图中,是通过BottomNavigationBar的一个标签显示的。
我有以下问题:
我想保持地图在用户离开“地图”选项卡时的状态,以便他以后可以继续使用它。
试图:
(我承认我做错了什么事
上次尝试的代码:
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时将其还原。或其他可以解决问题的东西。
答案 0 :(得分:5)
例如:
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线程。