How to show SnackBar in Flutter

后端 未结 3 1100
不思量自难忘°
不思量自难忘° 2021-01-25 08:23

I want to show a SnackBar Widget when the bottom tab is clicked. I am trying to show it as:

Scaffold.of(context).showSnackBar(new SnackBar(
                cont         


        
相关标签:
3条回答
  • 2021-01-25 09:00

    You do have a scaffold, but not above the context of MyHomePage. Your Scaffold is a child of MyHomePage, while doing Scaffold.of(context) is trying to access the closest parent Scaffold. And since you have none, it crash.

    You should probably wrap your BottomNavigationBar into a new class. And use that widget's context to do Scaffold.of(context).

    0 讨论(0)
  • 2021-01-25 09:22

    Change your _handleBottomNavigationBarTap method to take a BuildContext argument.

    void _handleBottomNavigationBarTap(int newValue, BuildContext context) {
      ...
    }
    

    Then change your bottomNavigationBar argument as follows:

    bottomNavigationBar: new Builder(
      builder: (BuildContext context) {
        return new BottomNavigationBar(
          labels: bottomBarLabels,
          onTap: (index) => _handleBottomNavigationBarTap(index, context),
        );
      }
    ),
    

    This ensures that you call to Scaffold.of(context) will be able to find a ScaffoldState that is an ancestor of the context.

    0 讨论(0)
  • 2021-01-25 09:24

    Unfortunately I am not able to upgrade my Flutter version at the moment, However, from what I understand, you are trying to show a SnackBar only when Live Icon is pressed.

    So you may want to make the Live Icon into an IconButton instead and use its onPressed property on its own instead of using the onTap property of the BottomNavigationBar, then wrap the IconButton within a Builder, something similar to the following:

    new BottomNavigationBar(
              labels: [
                new DestinationLabel(title: new Text("Live"),
                  icon: new Builder(builder: (BuildContext context) {
                    return new IconButton(icon: new Icon(Icons.live_tv),
                        onPressed: () {
                          Scaffold.of(context).showSnackBar(
                              new SnackBar(content: new Text("Live Clicked")));
                        });
                  }),
                ),
                new DestinationLabel(icon: new Icon(Icons.date_range),
                    title: new Text("Matches"),)
    
    
              ],
            )
    

    I am not sure if this is the best practice, our Flutter gurus here always suggest to compose the more complex widgets from multiple classes.

    0 讨论(0)
提交回复
热议问题