Show snackbar from scaffold inside onPressed callback on Floating Action Button

前端 未结 3 1117
星月不相逢
星月不相逢 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: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);
    
    }
    

提交回复
热议问题