[英]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.