【发布时间】:2020-05-04 22:13:08
【问题描述】:
您好,有什么方法可以使用 WidgetBindingObservers 来检测用户何时退出或进入 Flutter 中的选项卡,然后在重新进入后刷新选项卡?
我正在以这种方式使用它(参考代码),但它不起作用,所以我需要一些指导。非常感谢。
我想要的输出类似于 Facebook 的应用程序,特别是 NewsFeed 选项卡。当您退出该标签长时间或长时间观看新闻源中的视频时,该标签将自动刷新
我的 main.dart 代码是这样的:
class MyApp extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return MyAppState();
}
}
class MyAppState extends State<MyApp> with WidgetsBindingObserver {
var lastloaded;
bool isInactive;
int _selectedPage = 0;
final _pageOptions = [
HomePage(),
CategoriesPage(),
Deals(),
ProfileAccount(),
CartPage(),
];
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
super.didChangeAppLifecycleState(state);
switch(state){
case AppLifecycleState.paused:
print("p");
break;
case AppLifecycleState.resumed:
print("r");
break;
case AppLifecycleState.inactive:
print("I");
break;
case AppLifecycleState.detached:
print("D");
break;
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Sync Shop',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
body: IndexedStack(
index: _selectedPage,
children: _pageOptions,
),
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
currentIndex: _selectedPage,
onTap: (int index) {
setState((){
_selectedPage = index;
});
},
items: [
BottomNavigationBarItem(icon: Image.asset("assets/home.png",
height: 25,
width: 25,
),
title: Text("Home",),
activeIcon:
Image.asset("assets/home-active.png",
height: 25,
width: 25,
)
),
BottomNavigationBarItem(icon: Image.asset("assets/categories.png",
height: 22,
width: 22,
),
title: Text("Categories",),
activeIcon:
Image.asset("assets/categories-active.png",
height: 22,
width: 22,
),
),
BottomNavigationBarItem(icon: Image.asset("assets/deals.png",
height: 25,
width: 25,
),
title: Text("Deals",),
activeIcon:
Image.asset("assets/deals-active.png",
height: 25,
width: 25,
)
),
BottomNavigationBarItem(icon: Image.asset("assets/profile.png",
height: 25,
width: 25,
), title: Text("Profile",),
activeIcon:
Image.asset("assets/profile-active.png",
height: 25,
width: 25,
)
),
BottomNavigationBarItem(icon: Image.asset("assets/cart.png",
height: 25,
width: 25,
), title: Text("Cart"),
activeIcon:
Image.asset("assets/cart-active.png",
height: 25,
width: 25,
),
),
],
unselectedLabelStyle: TextStyle(color: Colors.grey[600], fontSize: 11),
selectedItemColor: Color(0xFFEF5021),
selectedLabelStyle: TextStyle(fontWeight: FontWeight.bold, fontSize: 12),
),
),
);
}
}
【问题讨论】:
-
您的页面是否在单独的文件 (.dart) 中?
-
@Naveen Avidi 是的
标签: android flutter flutter-layout flutter-web