showToast method
Future<bool?>
showToast({
- required String msg,
- Duration toastDuration = const Duration(seconds: 1),
- DencendToastGravity? gravity,
- ToastStyle? style,
override
显示 Toast 消息
将 Flutter 中的参数转换为原生平台能理解的格式, 然后通过方法通道调用原生平台的 showToast 方法
参数说明:
msg - 要显示的消息文本
toastLength - Toast 显示时长(仅Android有效)
toastDuration - Toast显示时长,使用Duration类型,适用于所有平台
gravity - Toast 显示位置
style - Toast 样式配置,包含字体、颜色等样式参数
返回 Future<bool?> 表示操作是否成功
Implementation
@override
Future<bool?> showToast({
required String msg,
Duration toastDuration = const Duration(seconds: 1),
DencendToastGravity? gravity,
ToastStyle? style,
}) async {
try {
// 将Duration转换为秒
final int toastDurationSeconds = toastDuration.inSeconds;
// 将位置枚举转换为原生平台能识别的字符串
String gravityDencendToast = "bottom";
if (gravity == DencendToastGravity.top) {
gravityDencendToast = "top";
} else if (gravity == DencendToastGravity.center) {
gravityDencendToast = "center";
} else {
gravityDencendToast = "bottom";
}
// 构建参数映射表
// 注意:颜色需要转换为整数(透明度+RGB值)才能传递给原生平台
final Map<String, dynamic> params = <String, dynamic>{
'msg': msg,
'toastDuration': toastDurationSeconds,
'gravity': gravityDencendToast,
'bgcolor': style?.backgroundColor?.toARGB32(),
'iosBgcolor': style?.backgroundColor?.toARGB32(),
'textcolor': style?.textColor?.toARGB32(),
'iosTextcolor': style?.textColor?.toARGB32(),
'fontSize': style?.fontSize,
'fontAsset': style?.fontAsset,
'borderRadius': style?.borderRadius,
'webBgColor': style?.webBgColor ?? "linear-gradient(to right, #00b09b, #96c93d)",
'iconAsset': style?.iconAsset,
'iconSize': style?.iconSize,
'iconColor': style?.iconColor?.toARGB32(),
'iconPosition': style?.iconPosition?.name,
'iconSpacing': style?.iconSpacing,
};
// 调用原生平台的 'showToast' 方法,传递所有参数
// 原生平台会根据传入的参数显示相应的 Toast
final bool? result = await channel.invokeMethod('showToast', params);
return result;
} on PlatformException catch (e) {
// 捕获平台异常,在调试模式下打印错误信息
if (kDebugMode) {
print('MethodChannelDencendToast.showToast failed: ${e.message}');
}
return false;
}
}