Skip to content

[Flutter] How to Create SnackBar Message Component

We often use the SnackBar message component in Flutter Apps to display the remind messages.

After all, it is difficult to use the print() function to interact with user, and it is also difficult for making a new widget for message displaying.

In Flutter, it is actually very easy to display SnackBar messages, just use the following component:

ScaffoldMessenger.of(context).showSnackBar(SnackBar(
      content: Text("Sending Message"),
    )
);


The following is the complete sample code.


Sample Code

import 'package:flutter/material.dart';

void main() => runApp(SnackBarDemo());

class SnackBarDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: SnackBarPage(),
      ),
    );
  }
}

class SnackBarPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: ElevatedButton(
        child: Text("Show Toast"),
        onPressed: () {
          final scaffold = ScaffoldMessenger.of(context);
          final snackBar = SnackBar(
            content: Text("This is a Toast Component"),
            action: SnackBarAction(
              label: 'CANCEL',
              onPressed: () {
                scaffold.removeCurrentSnackBar();
              },
            ),
          );

          // Show
          scaffold.showSnackBar(snackBar);
        },
      ),
    );
  }
}


Output:

As you can see, if we click the Show Toast button, A SnackBar will show on the bottom of the screen.

The above is a simple introduction to SnackBar message component in Flutter. Hope we have fun in the development.


References


Read More

Tags:

Leave a Reply