Skip to content

Instantly share code, notes, and snippets.

@wilinz
Last active March 13, 2024 13:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wilinz/ee0435d9f332003ac31cef650a75cbd1 to your computer and use it in GitHub Desktop.
Save wilinz/ee0435d9f332003ac31cef650a75cbd1 to your computer and use it in GitHub Desktop.
fluttertoast 封装
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:xxx/generated/locales.g.dart';
import 'package:xxx/ui/route.dart';
final FToast fToast = FToast();
bool _isInit = false;
void toast(dynamic message) {
if (!initFToast()) return;
final toast = ToastWidget(
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Text(message.toString()),
],
));
fToast.showToast(
child: toast,
gravity: ToastGravity.BOTTOM,
toastDuration: Duration(seconds: 2),
);
}
bool initFToast() {
if (!_isInit) {
final context = AppRoute.navigatorKey.currentContext;
if (context == null) {
return false;
}
fToast.init(context);
_isInit = true;
}
return true;
}
void toastSuccess({dynamic message}) {
if (!initFToast()) return;
message ??= LocaleKeys.successful.tr;
final toast = ToastWidget(
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.check, color: Colors.green),
SizedBox(width: 12.0),
Text(message.toString()),
],
));
fToast.showToast(
child: toast,
gravity: ToastGravity.BOTTOM,
toastDuration: Duration(seconds: 2),
);
}
void toastFailure({dynamic message, error}) {
if (!initFToast()) return;
message ??= LocaleKeys.failed.tr;
final toast = ToastWidget(
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.clear, color: Colors.red),
SizedBox(width: 12.0),
Text(message.toString()),
if (error != null) Text(": " + error.toString())
],
));
fToast.showToast(
child: toast,
gravity: ToastGravity.BOTTOM,
toastDuration: Duration(seconds: 2),
);
}
class ToastWidget extends StatelessWidget {
final Widget child;
const ToastWidget({
super.key,
required this.child,
});
@override
Widget build(BuildContext context) {
return Material(
borderRadius: BorderRadius.all(Radius.circular(8)),
elevation: 2,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 12.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(25.0),
color: Colors.white,
),
child: child,
),
);
}
}
class AppRoute {
static final GlobalKey<NavigatorState> navigatorKey =
GlobalKey<NavigatorState>();
}
Future<void> main() async {
runApp(GetMaterialApp(
builder: FToastBuilder(),
navigatorKey: AppRoute.navigatorKey,
));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment