Flutter官方插件市场上已经有了很多成熟的Toast组件,如 fluttertoast 等等。
使用了一年多的Flutter框架,一时兴起,自己封装了一个简单的Toast组件。
注:本人觉得,自动关闭的时候,不宜使用 "Navigator.pop(context);" 或者 "Navigator.of(context).pop();" ,可以改用 "Navigator.of(context).removeRoute(this);" 。
包含测试的完整代码如下:
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('HomePage'),
),
body: Container(
color: const Color(0xfff3f3f3),
alignment: Alignment.center,
child: GestureDetector(
onTap: () {
MyToast(msg: 'Hello world!').show(context);
},
child: Container(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
border: Border.all(color: Colors.black38, width: 1.0),
borderRadius: BorderRadius.circular(12.0),
),
child: const Text(
'显示Toast',
style: TextStyle(color: Colors.black38, fontSize: 16, height: 1),
textAlign: TextAlign.center,
),
),
),
),
);
}
}
class MyToast extends PopupRoute {
MyToast({
this.msg = 'This is a Toast',
this.margin,
}) : super(settings: const RouteSettings(name: 'MyToast'));
void show(
BuildContext context, {
Duration duration = const Duration(seconds: 2),
}) {
Navigator.push(context, this);
//Navigator.of(context).push(this);
Future.delayed(duration, () {
//Navigator.pop(context);
//Navigator.of(context).pop();
Navigator.of(context).removeRoute(this);
});
}
final String msg;
final EdgeInsets? margin;
@override
Color? get barrierColor => Colors.transparent;
@override
bool get barrierDismissible => false;
@override
String? get barrierLabel => runtimeType.toString();
@override
Duration get transitionDuration => const Duration(milliseconds: 300);
@override
Widget buildPage(BuildContext context, Animation<double> animation,
Animation<double> secondaryAnimation) {
return Center(
child: DefaultTextStyle(
style: Theme.of(context).textTheme.bodyMedium!,
child: _buildUI(),
),
);
}
Widget _buildUI() {
return Container(
width: 280,
height: 60,
margin: margin,
alignment: Alignment.center,
decoration: const ShapeDecoration(
color: Colors.black,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(6.0))),
),
padding: const EdgeInsets.all(10),
child: Text(
msg,
style: const TextStyle(fontSize: 14.0, color: Colors.white),
),
);
}
}
特别鸣谢下列链接的作者:
(0) Flutter入门:如何只关闭自身页面 。