IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 移动开发 -> Flutter toast弹窗实现 -> 正文阅读

[移动开发]Flutter toast弹窗实现

一.Flutter toast库配置,可参考fluttertoast配置引用

1.在pubspec.yaml中配置fluttertoast库,通过Pub get 获取fluttertoast的版本,通过Pub upgrade更新,eg:

 # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  provider: ^5.0.0
  fluttertoast: ^8.0.8

2.在需要显示toast的dart文件中,import?fluttertoast.dart,eg:

import 'package:fluttertoast/fluttertoast.dart';

3.fluttertoast.dart源码查看

/// Summons the platform's showToast which will display the message
  ///
  /// Wraps the platform's native Toast for android.
  /// Wraps the Plugin https://github.com/scalessec/Toast for iOS
  /// Wraps the https://github.com/apvarun/toastify-js for Web
  ///
  /// Parameter [msg] is required and all remaining are optional
  static Future<bool?> showToast({
    required String msg,
    Toast? toastLength,
    int timeInSecForIosWeb = 1,
    double? fontSize,
    ToastGravity? gravity,
    Color? backgroundColor,
    Color? textColor,
    bool webShowClose = false,
    webBgColor: "linear-gradient(to right, #00b09b, #96c93d)",
    webPosition: "right",
  }) async {
    String toast = "short";
    if (toastLength == Toast.LENGTH_LONG) {
      toast = "long";
    }

    String gravityToast = "bottom";
    if (gravity == ToastGravity.TOP) {
      gravityToast = "top";
    } else if (gravity == ToastGravity.CENTER) {
      gravityToast = "center";
    } else {
      gravityToast = "bottom";
    }

//lines from 78 to 97 have been changed in order to solve issue #328
    if (backgroundColor == null) {
      backgroundColor = Colors.black;
    }
    if (textColor == null) {
      textColor = Colors.white;
    }
    final Map<String, dynamic> params = <String, dynamic>{
      'msg': msg,
      'length': toast,
      'time': timeInSecForIosWeb,
      'gravity': gravityToast,
      'bgcolor': backgroundColor != null ? backgroundColor.value : null,
      'iosBgcolor': backgroundColor != null ? backgroundColor.value : null,
      'textcolor': textColor != null ? textColor.value : null,
      'iosTextcolor': textColor != null ? textColor.value : null,
      'fontSize': fontSize,
      'webShowClose': webShowClose,
      'webBgColor': webBgColor,
      'webPosition': webPosition
    };

    bool? res = await _channel.invokeMethod('showToast', params);
    return res;
  }
}

1).默认值设置,eg:

propertydescriptiondefault
msgString (Not Null)(required)required
toastLengthToast.LENGTH_SHORT or Toast.LENGTH_LONG (optional)Toast.LENGTH_SHORT
gravityToastGravity.TOP (or) ToastGravity.CENTER (or) ToastGravity.BOTTOM (Web Only supports top, bottom)ToastGravity.BOTTOM
timeInSecForIosWebint (for ios & web)1 (sec)
backgroundColorColors.rednull
textcolorColors.whitenull
fontSize16.0 (float)null
webShowClosefalse (bool)false
webBgColorString (hex Color)linear-gradient(to right, #00b09b, #96c93d)
webPositionString (left,?center?or?right)right

4.在需要显示toast的dart文件中调用showToast()方法,eg:

Fluttertoast.showToast(
            msg: "Dividend cannot be zero",
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.CENTER,
            timeInSecForIosWeb: 1,
            backgroundColor: Colors.white,
            textColor: Colors.black,
            fontSize: 18.0
        );

5.取消toast,可调用?cancel(),eg:

Fluttertoast.cancel()

二.自定义fluttertoast

1.定义FToast字段,eg:

FToast fToast;

2.初始化定义的FToast,eg:

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    fToast=FToast();
    fToast.init(context);
  }

3.定义FToast显示的方法,包括内容,布局,和显示时长,eg:

_showToast() {
    Widget toast = Container(
      padding: const EdgeInsets.symmetric(horizontal: 5.0, vertical: 5.0),
      alignment: Alignment.center,
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: const [
          SizedBox(
            width: 50.0,
          ),
          Text(
            "Dividend cannot be zero",
            textAlign: TextAlign.center,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              color: Colors.black,
              backgroundColor: Colors.white,
              fontSize: 18,
            ),
          )
        ],
      ),
    );


    fToast.showToast(
      child: toast,
      gravity: ToastGravity.BOTTOM,
      toastDuration: const Duration(seconds: 1),
    );

    // Custom Toast Position
    fToast.showToast(
        child: toast,
        toastDuration: const Duration(seconds: 3),
        positionedToastBuilder: (context, child) {
          return Positioned(
            child: child,
            top: 15.0,
            left: 15.0,
          );
        });
  }

4.调用,可在需要显示toast的地方直接调用_showToast()方法即可,eg:计算器简单实现中添加被除数不能为零的toast

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';

// ignore: camel_case_types
class calculatePage extends StatefulWidget {

  const calculatePage({Key? key}) : super(key: key);

  @override
  State createState() => calculatePageState();

}

// ignore: camel_case_types
class calculatePageState extends State<calculatePage> {
  var num1 = 0, num2 = 0, sum = 0;
  late FToast fToast;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    fToast=FToast();
    fToast.init(context);
  }

  final TextEditingController text1 = TextEditingController(text: "0");
  final TextEditingController text2 = TextEditingController(text: "0");

  void doAddition() {
    setState(() {
      print("doAddition---begin");
      num1 = int.parse(text1.text);
      num2 = int.parse(text2.text);
      sum = num1 + num2;
    });
  }

  void doSub() {
    setState(() {
      // ignore: avoid_print
      print("doSub---begin");
      num1 = int.parse(text1.text);
      num2 = int.parse(text2.text);
      sum = num1 - num2;
    });
  }

  void doMul() {
    setState(() {
      print("doSub---begin");
      num1 = int.parse(text1.text);
      num2 = int.parse(text2.text);
      sum = num1 * num2;
    });
  }

  void doDiv() {
    setState(() {
      // ignore: avoid_print
      print("doSub---begin");
      num1 = int.parse(text1.text);
      num2 = int.parse(text2.text);
      if(num2==0){
        /*Fluttertoast.showToast(
            msg: "Dividend cannot be zero",
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.CENTER,
            timeInSecForIosWeb: 1,
            backgroundColor: Colors.white,
            textColor: Colors.black,
            fontSize: 18.0
        );*/
        _showToast();
      }else{
        sum = num1 ~/ num2;
      }
    });
  }

  void doClear() {
    setState(() {
      print("doSub---begin");
      text1.text = "0";
      text2.text = "0";
      sum=0;
    });
  }

  _showToast() {
    Widget toast = Container(
      padding: const EdgeInsets.symmetric(horizontal: 5.0, vertical: 5.0),
      alignment: Alignment.center,
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: const [
          SizedBox(
            width: 50.0,
          ),
          Text(
            "Dividend cannot be zero",
            textAlign: TextAlign.center,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              color: Colors.black,
              backgroundColor: Colors.white,
              fontSize: 18,
            ),
          )
        ],
      ),
    );


    fToast.showToast(
      child: toast,
      gravity: ToastGravity.BOTTOM,
      toastDuration: const Duration(seconds: 1),
    );

    // Custom Toast Position
    fToast.showToast(
        child: toast,
        toastDuration: const Duration(seconds: 3),
        positionedToastBuilder: (context, child) {
          return Positioned(
            child: child,
            top: 15.0,
            left: 15.0,
          );
        });
  }

  @override
  Widget build(BuildContext context) {
    print("build---begin");
    return Scaffold(
      appBar: AppBar(
        title: const Text("calculatePage"),
      ),
      body: Container(
        padding: const EdgeInsets.all(45.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            TextField(
              keyboardType: TextInputType.number,
              decoration: const InputDecoration(hintText: "Please Enter Number one"),
              controller: text1,
            ),
            TextField(
              keyboardType: TextInputType.number,
              decoration: const InputDecoration(hintText: "Please Enter Number two"),
              controller: text2,
            ),

            const Padding(
              padding: EdgeInsets.only(top: 18.0),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text(
                  "Calculate Output : $sum",
                  style: const TextStyle(
                      fontSize: 16.0,
                      fontWeight: FontWeight.bold,
                      color: Colors.orange),
                ),
              ],
            ),
            const Padding(
              padding: EdgeInsets.only(top: 18.0),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                MaterialButton(
                  child: const Text("+"),
                  color: Colors.greenAccent,
                  onPressed: doAddition,
                ),
                MaterialButton(
                  child: const Text("-"),
                  color: Colors.greenAccent,
                  onPressed: doSub,
                ),
              ],
            ),
            const Padding(
              padding: EdgeInsets.only(top: 18.0),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                MaterialButton(
                  child: const Text("*"),
                  color: Colors.greenAccent,
                  onPressed: doMul,
                ),
                MaterialButton(
                  child: const Text("/"),
                  color: Colors.greenAccent,
                  onPressed: doDiv,
                ),
              ],
            ),
            const Padding(
              padding: EdgeInsets.only(top: 18.0),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                MaterialButton(
                  child: const Text("Clear"),
                  color: Colors.red,
                  onPressed: doClear,
                ),
              ],
            )
          ],
        ),
      ),
    );
  }
}

  移动开发 最新文章
Vue3装载axios和element-ui
android adb cmd
【xcode】Xcode常用快捷键与技巧
Android开发中的线程池使用
Java 和 Android 的 Base64
Android 测试文字编码格式
微信小程序支付
安卓权限记录
知乎之自动养号
【Android Jetpack】DataStore
上一篇文章      下一篇文章      查看所有文章
加:2021-12-28 23:02:56  更:2021-12-28 23:04:50 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/24 9:47:05-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码