loading...

Como criar um Toast no Flutter

alexandrefreire profile image Alexandre Freire ・1 min read

Você pode acessar o pai ScaffoldState usando Scaffold.of(context)

Então faça algo como

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

Para mais detalhes consulte:
https://material.io/design/components/snackbars.html#usage

Exemplo:

Alt Text

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),
      ),
    );
  }
}

Posted on by:

alexandrefreire profile

Alexandre Freire

@alexandrefreire

CST em Análise e Desenvolvimento de Sistemas

Discussion

markdown guide