Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 263 Vote(s) - 3.44 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to create Toast in Flutter

#1
Can I create something similar to [Toasts][1] in Flutter?

[![enter image description here][2]][2]

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.


[1]:

[To see links please register here]

[2]:
Reply

#2
fluttertoast: ^3.1.3

import 'package:fluttertoast/fluttertoast.dart';

Fluttertoast.showToast(
msg: "This is Center Short Toast",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIos: 1,
backgroundColor: Colors.red,
textColor: Colors.white,
fontSize: 16.0
);



Reply

#3
**UPDATE:** `Scaffold.of(context).showSnackBar` is deprecated in Flutter 2.0.0 (stable)

You can access the parent `ScaffoldMessengerState` using `ScaffoldMessenger.of(context)`.

Then do something like

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

Snackbars are the official "Toast" from material design. See *[Snackbars][1]*.

Here is a fully working example:

[![Enter image description here][2]][2]

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: 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'),
),
body: Center(
child: RaisedButton(
onPressed: () => _showToast(context),
child: const Text('Show toast'),
),
),
);
}

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

[1]:

[To see links please register here]

[2]:



Reply

#4
`SnackBar` is definitely the right class to use, as pointed out by Darky.

[![Snackbar][1]][1]

One tricky thing about `showSnackBar` is getting to the `ScaffoldState`, if you're trying to call `showSnackBar` within the build method where you construct your `Scaffold`.

You might see an error like this, which includes some text explaining how to solve the problem.

```lang-none
══╡ 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():

[To see links please register here]

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.<anonymous closure> (/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.<anonymous closure> (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)
════════════════════════════════════════════════════════════════════════════════════════════════════
```

You can either pass a `GlobalKey` to your `Scaffold` constructor:

class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
final key = new GlobalKey<ScaffoldState>();
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),
);
}
),
);
}
}

Or you can use a `Builder` to create a `BuildContext` that is a child of the 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),
);
}
),
);
}
}

Finally, you could split your widget into multiple classes, which is the best long-term approach.

[1]:



Reply

#5
Use

[To see links please register here]

for toast. This library is pretty easy to use and perfectly works for iOS and Android.

Syntax for showing Toast:

Toast.show("Toast plugin app", duration: Toast.LENGTH_SHORT, gravity: Toast.BOTTOM);




Reply

#6
Step 1:
---------

Dependencies:

flutter_just_toast: ^1.0.1

----------

Step 2:
----------

import 'package:flutter_just_toast/flutter_just_toast.dart';

----------


Step 3:
----------

Toast.show(
message: "Your toast message",
duration: Delay.SHORT,
textColor: Colors.black);

----------

Reply

#7
I would like to provide an alternative solution to use package [flushbar][1].

As the package said: Use this package if you need more customization when notifying your user. For Android developers, it is made to substitute toasts and snackbars.

Another suggestion to use flushbar is *https://stackoverflow.com/questions/51260227/how-can-i-show-a-snackbar-after-navigator-popcontext-in-flutter*

You can also set flushbarPosition to TOP or BOTTOM:

[![Enter image description here][2]][2]

Flushbar(
title: "Hey Ninja",
message: "Lorem Ipsum is simply dummy text of the printing and typesetting industry",
flushbarPosition: FlushbarPosition.TOP,
flushbarStyle: FlushbarStyle.FLOATING,
reverseAnimationCurve: Curves.decelerate,
forwardAnimationCurve: Curves.elasticOut,
backgroundColor: Colors.red,
boxShadows: [BoxShadow(color: Colors.blue[800], offset: Offset(0.0, 2.0), blurRadius: 3.0)],
backgroundGradient: LinearGradient(colors: [Colors.blueGrey, Colors.black]),
isDismissible: false,
duration: Duration(seconds: 4),
icon: Icon(
Icons.check,
color: Colors.greenAccent,
),
mainButton: FlatButton(
onPressed: () {},
child: Text(
"CLAP",
style: TextStyle(color: Colors.amber),
),
),
showProgressIndicator: true,
progressIndicatorBackgroundColor: Colors.blueGrey,
titleText: Text(
"Hello Hero",
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 20.0, color: Colors.yellow[600], fontFamily: "ShadowsIntoLightTwo"),
),
messageText: Text(
"You killed that giant monster in the city. Congratulations!",
style: TextStyle(fontSize: 18.0, color: Colors.green, fontFamily: "ShadowsIntoLightTwo"),
),
)..show(context);

[1]:

[To see links please register here]

[2]:




Reply

#8
You can use something like FlutterToast.

Import the library:

fluttertoast: ^2.1.4

Use it like below:

Fluttertoast.showToast(
msg: "Hello, World!",
textColor: Colors.white,
toastLength: Toast.LENGTH_SHORT,
timeInSecForIos: 1,
gravity: ToastGravity.BOTTOM,
backgroundColor: Colors.indigo,
);

That's it...
Reply

#9
Use this dependency:

toast: ^0.1.3

Then import the dependency of toast in the page:

import 'package:toast/toast.dart';

Then on *onTap()* of the widget:

Toast.show("Toast plugin app", context, duration:Toast.LENGTH_SHORT, gravity: Toast.BOTTOM);

Reply

#10
For the ones that are looking for a `Toast` what can survive the route changes, the `SnackBar` might not be the best option.

Have a look at [`Overlay`][1] instead.

[1]:

[To see links please register here]

Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through