[英]I want keep this Stopwatch screen running while switching through screens
我有這款Flutter iOS風格的秒表,我希望在切換屏幕時保持秒表運行。
我已經嘗試過在Stopwatch的initState函數中放置一些setState,但這沒有用。
我認為回到秒表屏幕時,它不會重建小部件。
//我的構建器位於home_screen.dart文件中
@override
Widget build(BuildContext context) {
return CupertinoTabScaffold(
controller: controller,
tabBar: CupertinoTabBar(
items: [
BottomNavigationBarItem(
icon: Icon(
Ionicons.getIconData('ios-globe'),
),
title: Text('World Clock'),
),
BottomNavigationBarItem(
icon: Icon(
Ionicons.getIconData('ios-alarm'),
),
title: Text('Alarm'),
),
BottomNavigationBarItem(
icon: Icon(
Ionicons.getIconData('ios-bed'),
),
title: Text('Bedtime'),
),
BottomNavigationBarItem(
icon: Icon(
Ionicons.getIconData('ios-stopwatch'),
),
title: Text('Stopwatch'),
),
BottomNavigationBarItem(
icon: Icon(
Ionicons.getIconData('ios-timer'),
),
title: Text('Timer'),
),
],
),
tabBuilder: (context, i) {
if(i == 3){
final Dependencies dependencies = new Dependencies();
return StopWatch(dependencies: dependencies,);
}else{
return CupertinoTabView(
builder: (context){
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
middle: Text(chooseMiddle(i)),
),
child: Center(
child: Text('Screen $i'),
),
);
},
);
}
},
);
}
每當您在選項卡之間切換時,都會導致重建屏幕,並因此在選項卡生成器中創建StopWatch小部件的新對象。 您將必須使用PageStorageBucket和PageStorageKeys來維護頁面。
這樣的事情應該有所幫助
class HomeScreen extends StatefulWidget{
@override
State<StatefulWidget> createState() {
return HomeWidget();
}
}
class HomeWidget extends State<HomeScreen>{
final List<Widget> pages = [
DashboardScreen(
key: PageStorageKey('Dashboard'),
),
CarsScreen(
key: PageStorageKey('Cars'),
),
MapScreen(
key: PageStorageKey('Find'),
),
ProfileScreen(
key: PageStorageKey('Profile'),
),
SettingScreen(
key: PageStorageKey('Settings'),
)
];
final PageStorageBucket bucket = PageStorageBucket();
int _selectedIndex = 0;
Widget _bottomNavigationBar(int selectedIndex) => BottomNavigationBar(
type: BottomNavigationBarType.fixed,
onTap: (int index) => setState(() => _selectedIndex = index),
currentIndex: selectedIndex,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(CupertinoIcons.home), title: Text('Home')),
BottomNavigationBarItem(
icon: Icon(CupertinoIcons.car), title: Text('My Cars')),
BottomNavigationBarItem(
icon: Icon(CupertinoIcons.search), title: Text('Find')),
BottomNavigationBarItem(
icon: Icon(CupertinoIcons.profile_circled), title: Text('Profile')),
BottomNavigationBarItem(
icon: Icon(CupertinoIcons.settings), title: Text('Settings')),
],
);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Smart Park'),
),
body: PageStorage(
child: pages[_selectedIndex],
bucket: bucket,
),
bottomNavigationBar: _bottomNavigationBar(_selectedIndex),
);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.