Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current context in Flutter?

Tags:

flutter

dart

I am using a bottom navigation bar. On a certain Event trigger I need to show some alert on the current screen.

This is how I have implemented the bottom navigation bar. I have four tabs. Here, I need to change the icon of the 4th tab when _isHomeDetected is true and when the user clicks on the icon, i.e on index 3 I have to show an alert message irrespective of which tab the user is in. How do I do this?

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???");
      }
    });
  }
}
like image 337
Chaythanya Nair Avatar asked May 09 '18 05:05

Chaythanya Nair


People also ask

How do you define context in flutter?

– Context is a link to the location of a widget in the tree structure of widgets. – Context can belong to only one widget. – If a widget has child widgets, then the context of the parent widget becomes the parent context for the contexts of direct child elements.

What is of () in flutter?

In the Flutter SDK the . of methods are a kind of service locator function that take the framework BuildContext as an argument and return an internal API related to the named class but created by widgets higher up the widget tree.


1 Answers

Within the build method of any stateful widget you'll be able to get the build context. If you can't do this, the below sample from flutter team uses a GlobalKey<ScaffoldState> to hace access to show snackBar alert.

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

like image 52
Ron Geo Avatar answered Oct 08 '22 08:10

Ron Geo