Search code examples
flutterfloating-action-buttonsnackbarscaffold

How to pass context of Scaffold to some function in flutter?


I want to show Snackbar using the floating action button but I am not able to pass the context of scaffold as parameter to call the local function in onPressed argument.

Is there any way to show the scaffold using floating action button?

void main() {
BuildContext context;
  runApp(
    MaterialApp(
      title: "Exploring UI Widgets",
      home: Scaffold(
        appBar: AppBar(
          title: Text("My App")
        ),
     floatingActionButton: FloatingActionButton(
       child: Icon(Icons.add),
       onPressed: (){
       //  showSnackBar(/*Here*/);
       },
       tooltip: "Floating Button",
     ),
      )
    )
  );
}

void showSnackBar(BuildContext context){
  var snackbar = SnackBar(
      content: Text("You just tapped Floating Button & This is Snakbar"),
      action: SnackBarAction(
        label: "Button",
        onPressed: (){
          //Blank Anonymous/ Lambda Function
        }
      )

  );
ScaffoldMessenger.of(context).showSnackBar(snackbar);

} 

Solution

  • Directly using ScaffoldMessenger inside MaterialApp will show context issue. Separate the home part.

    void main() {
      runApp(const MyApp());
    }
    
    class MyApp extends StatelessWidget {
      const MyApp({Key? key}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
            title: 'List Demo',
            theme: ThemeData(
              primarySwatch: Colors.blue,
            ),
            home: HomePage());
      }
    }
    
    
    class HomePage extends StatelessWidget {
      const HomePage({Key? key}) : super(key: key);
    
      showMySnackBar(BuildContext context) {
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("data")));
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(title: Text("My App")),
          floatingActionButton: FloatingActionButton(
            child: Icon(Icons.add),
            onPressed: () {
              showMySnackBar(context);
            },
            tooltip: "Floating Button",
          ),
        );
      }
    }