fluttertoast
is a library that allows you to create Toast popups easily across iOS, Android and Web.
Video
Would you prefer to watch a video instead of reading this article? Here you go:
Project Setup
To get started, we'll go ahead and create a new Flutter project:
# New Flutter project
$ flutter create fl_toast
# Open in editor
$ cd fl_toast && code .
Dependencies
Next up, we'll need to add the fluttertoast
dependency to our pubspec.yaml
:
dependencies:
flutter:
sdk: flutter
fluttertoast: ^4.0.1
Showing a Toast
Here's a typical example of the Fluttertoast
call that we'll be using:
Fluttertoast.showToast(
msg: _messageTextEditingController.text,
timeInSecForIosWeb: 10,
toastLength: Toast.LENGTH_LONG,
webShowClose: true,
)
We'll be using a text box and button which displays a toast with the message a user has typed. Our newly created HomePage
that does exactly that:
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
TextEditingController _messageTextEditingController;
GlobalKey<FormState> _formKey;
@override
void initState() {
super.initState();
_formKey = GlobalKey<FormState>();
_messageTextEditingController = TextEditingController();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Flutter Toast"),
),
body: Padding(
padding: const EdgeInsets.all(12.0),
child: Form(
key: _formKey,
child: Column(children: [
TextFormField(
controller: _messageTextEditingController,
),
FlatButton(
onPressed: () => Fluttertoast.showToast(
msg: _messageTextEditingController.text,
timeInSecForIosWeb: 10,
toastLength: Toast.LENGTH_LONG,
webShowClose: true,
),
child: Text("Show Toast"),
)
]),
),
),
);
}
@override
void dispose() {
_messageTextEditingController.dispose();
super.dispose();
}
}
We'll also need to update the home
within our main.dart
:
import 'package:fl_toast/presentation/pages/home_page.dart';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Toastie',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
brightness: Brightness.dark,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: HomePage(),
);
}
}
We can configure our toasts even further with various other options as seen here: https://pub.dev/documentation/fluttertoast/latest/
Summary
Next time you're looking for a library to display toasts inside of your Flutter apps, give fluttertoast
a try!
Code for this article: https://github.com/PaulHalliday/fl_toast
Top comments (0)