How to create Toast in Flutter?

aziza picture aziza · Aug 29, 2017 · Viewed 105.2k times · Source

Can I create something similar to Toasts in Flutter? Just a tiny notification window that is not directly in the face of the user and does not lock or fade the view behind it?

Answer

Rémi Rousselet picture Rémi Rousselet · Aug 29, 2017

You can access the parent ScaffoldState using Scaffold.of(context)

Then do something like

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

Snackbars are the official "Toast" from material design. See https://material.io/design/components/snackbars.html#usage

Here is a fully working example:

enter image description here

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: const Home(),
    );
  }
}

class Home extends StatelessWidget {
  const Home({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Snack bar'),
      ),

      /// We use [Builder] here to use a [context] that is a descendant of [Scaffold]
      /// or else [Scaffold.of] will return null
      body: Builder(
        builder: (context) => Center(
              child: RaisedButton(
                child: const Text('Show toast'),
                onPressed: () => _showToast(context),
              ),
            ),
      ),
    );
  }

  void _showToast(BuildContext context) {
    final scaffold = Scaffold.of(context);
    scaffold.showSnackBar(
      SnackBar(
        content: const Text('Added to favorite'),
        action: SnackBarAction(
            label: 'UNDO', onPressed: scaffold.hideCurrentSnackBar),
      ),
    );
  }
}