我正在使用底部导航栏。在某个事件触发器上,我需要在当前屏幕上显示一些警报。
这就是我实现底部导航栏的方式。我有四个标签。在这里,当第4个选项卡的图标_isHomeDetected为true且用户单击该图标(即在索引3上)时,我需要更改该图标,无论用户位于哪个选项卡中,我都必须显示一条警报消息。我该如何做?
class LandingScreen extends StatefulWidget {
static Widget bottomNavigationBar;
..
}
class _LandingScreenState extends State<LandingScreen> {
...
StreamSubscription<String> _subscription;
bool _isHomeDetected = false;
@override
void initState() {
...
_subscription = server.messages.listen(onData, onError: onError);
}
onData(message) {
setState(() {
_isHomeDetected = json.decode(message)["isHomeBeacon"];
});
}
...
@override
Widget build(BuildContext context) {
LandingScreen.bottomNavigationBar = new BottomNavigationBar(
....
);
return new Scaffold(
body: _currentPage,
bottomNavigationBar: LandingScreen.bottomNavigationBar,
);
}
_navigateToScreens(int currentIndex) {
List screens = [
..
];
setState((){
if (!_isHomeDetected || currentIndex != 3){
_currentPage = screens[currentIndex];
} else {
Utils.showCupertinoAlert(
context: context, content: "You wanna log out???");
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
声明一个全局密钥
final globalNavigatorKey = GlobalKey<NavigatorState>();
void main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(MyApp());
}
Run Code Online (Sandbox Code Playgroud)
然后将此全局密钥分配给您的MaterialApp
return MaterialApp(
title: 'Flutter Demo',
navigatorKey: globalNavigatorKey,
theme: ThemeData(primarySwatch: Colors.blue,),
home: MyHomePage(),
);
Run Code Online (Sandbox Code Playgroud)
然后无论你想在哪里调用 example :-
const snackBar = SnackBar(content: Text('Yay! A SnackBar!'));
ScaffoldMessenger.of(globalNavigatorKey.currentContext).showSnackBar(snackBar);
Run Code Online (Sandbox Code Playgroud)
小智 3
在任何有状态小部件的构建方法中,您将能够获取构建上下文。如果您做不到这一点,下面来自 flutter 团队的示例使用GlobalKey<ScaffoldState>to hace 访问来显示 SnackBar 警报。
| 归档时间: |
|
| 查看次数: |
7355 次 |
| 最近记录: |