Show snackbar from scaffold inside onPressed callback on Floating Action Button

前端 未结 3 1110
星月不相逢
星月不相逢 2021-02-13 14:05

I am trying to call

Scaffold.of(context).showSnackBar(SnackBar(
  content: Text(\"Snack text\"),
));

inside onPressed of fl

相关标签:
3条回答
  • 2021-02-13 14:16

    UPDATE: The second solution is better than this solution.

    You should put the floatingActionButton widget in a Builder Widget. The following code should work:

    @override
      Widget build(BuildContext context) {
        return new Scaffold(
          floatingActionButton: new Builder(builder: (BuildContext context) {
            return new FloatingActionButton(onPressed: () {
              Scaffold
                  .of(context)
                  .showSnackBar(new SnackBar(content: new Text('Hello!')));
            });
          }),
          body: new Container(
            padding: new EdgeInsets.all(32.0),
            child: new Column(
              children: <Widget>[
                new MySwitch(
                  value: _switchValue,
                  onChanged: (bool value) {
                    if (value != _switchValue) {
                      setState(() {
                        _switchValue = value;
                      });
                    }
                  },
                )
              ],
            ),
          ),
        );
    
    0 讨论(0)
  • 2021-02-13 14:22

    Add a Globalkey of the Scaffold state and use that to display snack bar as below,

    GlobalKey<ScaffoldState> scaffoldState;
    
    Scaffold {
    key: scaffoldState,
    ....
    
    
    scaffoldState.currentState.showSnackBar(new SnackBar(content: new Text('Hello!')));
    
    0 讨论(0)
  • 2021-02-13 14:39

    This is even simpler. Tried it. Create the FloatingActionButton as a separate Stateless Widget. Call this Stateless Widget from the Scaffold.

    class Abc extends StatelessWidget
    {
       Widget build(BuildContext context)
       {
          return Scaffold(
             appBar:AppBar(title:Text("Long List View")),
             body:SomeOtherWidget(),
             floatingActionButton:MyFAB()  
          );
       }
    }
    
    class MyFAB extends StatelessWidget
    {
        Widget build(BuildContext context)
        {
           return FloatingActionButton(
                onPressed:(){
                    showSnackBarHandler(context);
                },
                child:Icon(Icons.add),
                tooltip:"Press to Add More"
           );
        }
    }
    
    void showSnackBarHandler(BuildContext context){
    
    var snackBar = SnackBar(
        content:Text("Hello")
    );
    
    Scaffold.of(context).showSnackBar(snackBar);
    
    }
    
    0 讨论(0)
提交回复
热议问题