Creare toast in Flutter con fluttertoast
fluttertoast è un package per Flutter specializzato nella creazione di toast.
E' compatibile con Linux, iOS e Web.
Per installarlo:
flutter pub add fluttertoast
Qui sotto un esempio:
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Test',
debugShowCheckedModeBanner: false,
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
late FToast fToast;
Widget toast = Container(
padding: const EdgeInsets.symmetric(
horizontal: 24.0,
vertical: 12.0,
),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(25.0),
color: Colors.greenAccent,
),
child: const Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.check),
SizedBox(
width: 12.0,
),
Text("This is a Custom Toast"),
],
),
);
@override
void initState() {
super.initState();
fToast = FToast();
}
void showColoredToast() {
Fluttertoast.showToast(
msg: "Toast",
toastLength: Toast.LENGTH_LONG,
backgroundColor: Colors.red,
gravity: ToastGravity.TOP,
textColor: Colors.white,
);
}
void showCustomToast() {
fToast.showToast(
child: toast,
gravity: ToastGravity.BOTTOM,
toastDuration: const Duration(seconds: 2),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Toast"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () {
showColoredToast();
},
child: const Text("Flutter Toast"),
),
const SizedBox(
height: 24.0,
),
ElevatedButton(
onPressed: () {
showCustomToast();
},
child: const Text("Custom Flutter Toast"),
),
],
),
),
);
}
}
Enjoy!
dart flutter fluttertoast
Commentami!