flutter自定义弹窗_app加弹窗

flutter自定义弹窗_app加弹窗一.Fluttertoast库配置,可参考fluttertoast配置引用1.在pubspec.yaml中配置fluttertoast库,通过Pubget获取fluttertoast的版本,通过Pubupgrade更新,eg:#ThefollowingaddstheCupertinoIconsfonttoyourapplication.#UsewiththeCupertinoIconsclassforiOSstyleicons.cuper

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE稳定放心使用

一.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:

property description default
msg String (Not Null)(required) required
toastLength Toast.LENGTH_SHORT or Toast.LENGTH_LONG (optional) Toast.LENGTH_SHORT
gravity ToastGravity.TOP (or) ToastGravity.CENTER (or) ToastGravity.BOTTOM (Web Only supports top, bottom) ToastGravity.BOTTOM
timeInSecForIosWeb int (for ios & web) 1 (sec)
backgroundColor Colors.red null
textcolor Colors.white null
fontSize 16.0 (float) null
webShowClose false (bool) false
webBgColor String (hex Color) linear-gradient(to right, #00b09b, #96c93d)
webPosition String (leftcenter 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,
                ),
              ],
            )
          ],
        ),
      ),
    );
  }
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/189910.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月6日 上午11:22
下一篇 2026年3月6日 下午12:01


相关推荐

  • Java学习之Request篇

    Java学习之Request篇0x00前言在b/s架构里面,请求和响应是必不可少的。访问网页时,会发出一个request请求,服务器接收到请求后,根据设定代码,给我们响应对应的内容。0x01

    2021年12月12日
    45
  • 动态迁移_动作迁移

    动态迁移_动作迁移概念在虚拟化环境中的迁移,又分为动态迁移,静态迁移,也有人称之为冷迁移和热迁移,或者离线迁移在线迁移;静态迁移和动态迁移的区别就是静态迁移明显有一段时间客户机的服务不可用,而动态迁移则没有明显的服务暂停时间,静态迁移有两种1,是关闭客户机将其硬板镜像复制到另一台宿主机系统,然后回复启动起来,这种迁移不保留工作负载,2是,两台客户机公用一个存储系统,关闭一台客户机,防止其内存到另一台宿主机,这样做的

    2025年7月26日
    4
  • 全栈JavaScript之路(十八)HTML5 自己定义数据属性「建议收藏」

    全栈JavaScript之路(十八)HTML5 自己定义数据属性

    2022年1月19日
    39
  • TCP拥塞控制算法的演进

    TCP拥塞控制算法的演进TCP拥塞控制算法的演进TCP协议仅定义框架,也就是发送端和接收端需要遵循的“规则”。TCP协议的实现经过多年的改进,有了多个不同的版本。比较重要的有Tahoe、Reno、NewReno、SACK、Vegas等,有些已经成为了影响广泛的RFC文档,有些则成为了Unix/Linux操作系统的标准选项。以下简要介绍各个实现版本的主要区别和联系。1 早期的TCP实现最早的

    2022年6月24日
    24
  • 一步一步写算法(之 A*算法)

    一步一步写算法(之 A*算法)

    2021年12月4日
    45
  • 史上最详细图解快速排序的方法_快速排序的基本步骤

    史上最详细图解快速排序的方法_快速排序的基本步骤0.前言找了好多贴在都没有找到舒心的一次能看懂的文章,决定把学明白每一步全部图解出来。推荐一个博主的文章也很不错:https://blog.csdn.net/weixin_42109012/article/details/916450511.图解开始![在这里插入图片描述](https://img-blog.csdnimg.cn/e6bbdfbe97e44bbd99f99cf456c998ed.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5

    2025年11月12日
    5

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号