Snackbar widget in Flutter
Creating a custom Snackbar in Flutter involves creating a custom widget that mimics the appearance and behavior of the built-in Snackbar. Here's a step-by-step guide on how to create a simple custom Snackbar:
1. **Create the Custom Snackbar Widget**:
Start by creating a new Dart file for your custom Snackbar widget. For this example, let's call it `custom_snackbar.dart`.
2. **Import Required Packages**:
Import the necessary packages and widgets for creating your custom Snackbar:
```dart
import 'package:flutter/material.dart';
```
3. **Define the CustomSnackbar Class**:
Define a class that extends `StatelessWidget`. This class will represent your custom Snackbar:
```dart
class CustomSnackbar extends StatelessWidget {
final String message;
CustomSnackbar({required this.message});
@override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(16),
color: Colors.grey[900],
child: Row(
children: [
Icon(Icons.info, color: Colors.white),
SizedBox(width: 16),
Text(
message,
style: TextStyle(color: Colors.white),
),
],
),
);
}
}
```
In this example, the `CustomSnackbar` widget consists of a container with a padding, an icon, and a text message.
4. **Using the Custom Snackbar**:
To use your custom Snackbar in your app, you can follow these steps:
- First, import your custom Snackbar widget at the top of your Dart file:
```dart
import 'custom_snackbar.dart';
```
- Then, within your app's widget tree, call your custom Snackbar widget when needed. You can use a `ScaffoldMessengerState` to show the custom Snackbar:
```dart
final GlobalKey<ScaffoldMessengerState> _scaffoldKey = GlobalKey<ScaffoldMessengerState>();
// ...
ScaffoldMessenger(
key: _scaffoldKey,
child: YourWidgetTree(), // Your main widget tree
),
// ...
ElevatedButton(
onPressed: () {
_scaffoldKey.currentState?.showSnackBar(
SnackBar(
content: CustomSnackbar(message: 'Custom Snackbar Message'),
),
);
},
child: Text('Show Custom Snackbar'),
),
```
This example demonstrates how to trigger the custom Snackbar when a button is pressed. Replace `'Custom Snackbar Message'` with the message you want to display.
Remember, this is a simple example to get you started with creating a custom Snackbar. You can further customize the appearance and behavior of the Snackbar to match your app's design and requirements.
Comments
Post a Comment