Saltar al contenido

¿Cómo crear Toast en Flutter?

Después de tanto luchar pudimos encontrar la contestación de esta interrogante que algunos de nuestros usuarios de esta web han tenido. Si tienes algún detalle que aportar no dejes de aportar tu comentario.

Solución:

Puedes acceder al padre ScaffoldState utilizando Scaffold.of(context)

Entonces haz algo como

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

Los snacks son el “brindis” oficial de material design. Ver https://material.io/design/components/snackbars.html#usage

Aquí hay un ejemplo completamente funcional:

ingrese la descripción de la imagen aquí

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

Utilice este complemento

Fluttertoast.showToast(
        msg: "This is Toast messaget",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIos: 1
    );

ingrese la descripción de la imagen aquí

SnackBar es definitivamente la clase correcta para usar, como lo señaló Darky.

snackbar

Una cosa complicada sobre showSnackBar está llegando a la ScaffoldState, si estas tratando de llamar showSnackBar dentro del método de construcción donde construyes tu Scaffold.

Es posible que vea un error como este, que incluye un texto que explica cómo resolver el problema.

══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════
The following assertion was thrown while handling a gesture:
Scaffold.of() called with a context that does not contain a Scaffold.
No Scaffold ancestor could be found starting from the context that was passed to Scaffold.of(). This
usually happens when the context provided is from the same StatefulWidget as that whose build
function actually creates the Scaffold widget being sought.
There are several ways to avoid this problem. The simplest is to use a Builder to get a context that
is "under" the Scaffold. For an example of this, please see the documentation for Scaffold.of():
  https://docs.flutter.io/flutter/material/Scaffold/of.html
A more efficient solution is to split your build function into several widgets. This introduces a
new context from which you can obtain the Scaffold. In this solution, you would have an outer widget
that creates the Scaffold populated by instances of your new inner widgets, and then in these inner
widgets you would use Scaffold.of().
A less elegant but more expedient solution is assign a GlobalKey to the Scaffold, then use the
key.currentState property to obtain the ScaffoldState rather than using the Scaffold.of() function.
The context used was:
  MyHomePage
When the exception was thrown, this was the stack:
#0      Scaffold.of (package:flutter/src/material/scaffold.dart:444:5)
#1      MyHomePage.build. (/Users/jackson/Library/Developer/CoreSimulator/Devices/7072C907-DBAD-44FE-8F40-0257442C51D9/data/Containers/Data/Application/77FEC1A4-1453-442C-8208-96E0323DEFB2/tmp/so_scratch2Tkq9Jb/so_scratch2/lib/main.dart:23:24)
#2      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:323:14)
#3      _InkResponseState.build. (package:flutter/src/material/ink_well.dart:375:30)
#4      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:102:24)
#5      TapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:149:9)
#6      TapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:119:7)
#7      GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:156:27)
#8      BindingBase&SchedulerBinding&GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:147:20)
#9      BindingBase&SchedulerBinding&GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:121:22)
#10     BindingBase&SchedulerBinding&GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:101:7)
#11     BindingBase&SchedulerBinding&GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:64:7)
#12     BindingBase&SchedulerBinding&GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:48:7)
#13     _invoke1 (file:///b/build/slave/Mac_Engine/build/src/flutter/lib/ui/hooks.dart:100)
#14     _dispatchPointerDataPacket (file:///b/build/slave/Mac_Engine/build/src/flutter/lib/ui/hooks.dart:58)
Handler: onTap
Recognizer:
  TapGestureRecognizer#69dbc(debugOwner: GestureDetector, state: ready)
════════════════════════════════════════════════════════════════════════════════════════════════════

Puede pasar un GlobalKey para usted Scaffold constructor:

class MyHomePage extends StatelessWidget 
  @override
  Widget build(BuildContext context) 
    final key = new GlobalKey();
    return new Scaffold(
      key: key,
      floatingActionButton: new Builder(
        builder: (BuildContext context) 
          return new FloatingActionButton(
            onPressed: () 
              key.currentState.showSnackBar(new SnackBar(
                content: new Text("Sending Message"),
              ));
            ,
            tooltip: 'Increment',
            child: new Icon(Icons.add),
          );
        
      ),
    );
  

O puedes usar un Builder para crear un BuildContext que es un hijo del Scaffold.

class MyHomePage extends StatelessWidget 
  @override
  Widget build(BuildContext context) 
    return new Scaffold(
      floatingActionButton: new Builder(
        builder: (BuildContext context) 
          return new FloatingActionButton(
            onPressed: () 
              Scaffold.of(context).showSnackBar(new SnackBar(
                content: new Text("Sending Message"),
              ));
            ,
            tooltip: 'Increment',
            child: new Icon(Icons.add),
          );
        
      ),
    );
  

Finalmente, puede dividir su widget en varias clases, que es el mejor enfoque a largo plazo.

Si crees que te ha resultado de utilidad nuestro artículo, sería de mucha ayuda si lo compartes con otros entusiastas de la programación así nos ayudas a difundir esta información.

¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *