[英]Flutter: how to keep widget with Google Map unchanged?
我正在使用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 时恢复它。 或者其他可以解决问题的东西。
使用索引堆栈
例如:
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.