Flutter SnackBars

Displaying SnackBars In Flutter App :

In some situations,  to briefly inform our users when certain actions take place. For example, when a user swipes away a message in a list, then we  want to inform them the message has been deleted. We might even want to give them an option to undo the action!

 

Using SnackBar In Flutter App:

  • Create a Scaffold
  • Display a SnackBar
  • Provide an additional action

Creating a Scaffold:

While  creating the apps that follow the Material Design guidelines, we’ll want to give our apps a consistent visual structure. In this case, we’ll need to display the SnackBar at the bottom of the app screen, without overlapping other important Widgets, such as the FloatingActionButton!

The Scaffold Widget from the material library creates this visual structure for us and ensures important Widgets that don’t overlap!

Scaffold(
appBar: AppBar(
title: Text('SnackBar Demo'),
),
body: SnackBarPage(), // You'll fill this in below!
);

Displaying a SnackBarin Flutter App:

 

With the Scaffold in place, you can display a SnackBar! First, you need to create a SnackBar, then display it using the Scaffold.

final snackBar = SnackBar(content: Text('Yay! A SnackBar!'));

// Find the Scaffold in the Widget tree and use it to show a SnackBar
Scaffold.of(context).showSnackBar(snackBar);

Provide an additional action to Flutter App:

 

In some situations, you might want to provide an additional action to the user when the SnackBar is displayed. For example, if  accidentally deleted a message, then we could provide an action to undo that change.

To achieve this, we can provide an additional action to the SnackBar Widget. using below code.

 

final snackBar = SnackBar(
content: Text('Yay! A SnackBar!'),
action: SnackBarAction(
label: 'Undo',
onPressed: () {
// Some code to undo the change!
},
),
);

Below is the Complete code for Flutter SnackBar App:

import 'package:flutter/material.dart';

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

class SnackBarDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'SnackBar Demo',
home: Scaffold(
appBar: AppBar(
title: Text('SnackBar Demo'),
),
body: SnackBarPage(),
),
);
}
}

class SnackBarPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: RaisedButton(
onPressed: () {
final snackBar = SnackBar(
content: Text('Yay! A SnackBar!'),
action: SnackBarAction(
label: 'Undo',
onPressed: () {
// Some code to undo the change!
},
),
);

// Find the Scaffold in the Widget tree and use it to show a SnackBar!
Scaffold.of(context).showSnackBar(snackBar);
},
child: Text('Show SnackBar'),
),
);
}
}

Congratulations You Have Learned Using Snackbar In Flutter App..!

 

If it is useful share it with your Friends..!!!

Leave a Reply

Categories