Flutter之如何自定义Toast

654 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路

安卓里有Toast (显示提示的一种机制 没有焦点 一段时间之后会自动消失) 而如何在Flutter里面去调用安卓的Toast呢

可以使用oktoast依赖来实现

首先先在pubspec.yaml下载依赖:

dependencies:
  flutter:
    sdk: flutter
    
  oktoast: ^3.1.1

代码如下:

import 'package:flutter/material.dart';
import 'package:oktoast/oktoast.dart';

const DEFAULT_TOAST_DURATION = Duration(seconds: 2);
const DEFAULT_TOAST_COLOR = Color(0xFF424242);

class ToastHelper {
  ToastHelper._internal();

  ///全局初始化Toast配置, child为MaterialApp
  static init(Widget child) {
    return OKToast(
      ///字体大小
      textStyle: TextStyle(fontSize: 16, color: Colors.white),
      backgroundColor: DEFAULT_TOAST_COLOR,
      radius: 10,
      dismissOtherOnShow: true,
      textPadding: EdgeInsets.fromLTRB(20, 10, 20, 10),
      child: child,
      duration: DEFAULT_TOAST_DURATION,
    );
  }

  static void toast(String msg,
      {Duration duration = DEFAULT_TOAST_DURATION,
        Color color = DEFAULT_TOAST_COLOR}) {
    showToast(msg, duration: duration, backgroundColor: color);
  }

  static void waring(String msg, {Duration duration = DEFAULT_TOAST_DURATION}) {
    showToast(msg, duration: duration, backgroundColor: Colors.yellow);
  }

  static void error(String msg, {Duration duration = DEFAULT_TOAST_DURATION}) {
    showToast(msg, duration: duration, backgroundColor: Colors.red);
  }

  static void success(String msg,
      {Duration duration = DEFAULT_TOAST_DURATION}) {
    showToast(msg, duration: duration, backgroundColor: Colors.lightGreen);
  }
}

首先我们先定义一个常量 Toast的显示时间(const DEFAULT_TOAST_DURATION = Duration(seconds: 2))这里我们让它默认显示2秒 和 Toast的默认显示颜色(显示灰色)

然后开始全局初始化Toast配置, child为MaterialApp

然后设置属性 字体大小 边框 和是是否允许其它toast显示

///字体大小 textStyle: TextStyle(fontSize: 16, color: Colors.white), backgroundColor: DEFAULT_TOAST_COLOR, radius: 10, dismissOtherOnShow: true, textPadding: EdgeInsets.fromLTRB(20, 10, 20, 10), child: child, duration: DEFAULT_TOAST_DURATION,

然后开始写Toast显示方法

我们可以根据不同的场景来设置不同的Toast颜色

首先是常规的Toast:

static void toast(String msg,
    {Duration duration = DEFAULT_TOAST_DURATION,
      Color color = DEFAULT_TOAST_COLOR}) {
  showToast(msg, duration: duration, backgroundColor: color);
}

然后是警告的Toast

static void waring(String msg, {Duration duration = DEFAULT_TOAST_DURATION}) {
  showToast(msg, duration: duration, backgroundColor: Colors.yellow);
}

等等等等

主要是背景颜色的区别

其它最重要的是showToast这个方法

这个方法有一个必选参数 就是你要提示的信息 是字符串形式

其它的都为可选参数

ToastFuture showToast(
  String msg, {
  BuildContext? context,
  Duration? duration,
  ToastPosition? position,
  TextStyle? textStyle,
  EdgeInsetsGeometry? textPadding,
  Color? backgroundColor,
  double? radius,
  VoidCallback? onDismiss,
  TextDirection? textDirection,
  bool? dismissOtherToast,
  TextAlign? textAlign,
  OKToastAnimationBuilder? animationBuilder,
  Duration? animationDuration,
  Curve? animationCurve,
  BoxConstraints? constraints,
  EdgeInsetsGeometry? margin = const EdgeInsets.all(50),
})