如何在Flutter中获取当前上下文?

Cha*_*air 6 dart flutter

我正在使用底部导航栏。在某个事件触发器上,我需要在当前屏幕上显示一些警报。

这就是我实现底部导航栏的方式。我有四个标签。在这里,当第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)

Ily*_*ath 5

声明一个全局密钥

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 警报。

https://github.com/flutter/flutter/blob/master/examples/flutter_gallery/lib/demo/cupertino/cupertino_alert_demo.dart

  • 实际上是 State 类中的任何地方。`State` 有一个 `context` 成员/getter (7认同)
  • 由于链接现在已损坏,有人有这个例子吗? (3认同)