Creating a Custom SnackBar

This example demonstrates how to create and display a custom SnackBar with actions.

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Custom SnackBar',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: SnackBarExample(),
    );
  }
}

class SnackBarExample extends StatelessWidget {
  void _showSnackBar(BuildContext context) {
    final snackBar = SnackBar(
      content: Text('This is a custom SnackBar!'),
      action: SnackBarAction(
        label: 'Undo',
        onPressed: () {
          // Undo action
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('Action undone!')),
          );
        },
      ),
      duration: Duration(seconds: 3),
    );

    ScaffoldMessenger.of(context).showSnackBar(snackBar);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Custom SnackBar')),
      body: Center(
        child: ElevatedButton(
          onPressed: () => _showSnackBar(context),
          child: Text('Show SnackBar'),
        ),
      ),
    );
  }
}

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *