flutter 自定义 Toast

工具类

import 'package:flutter/material.dart';

class Toast {
  static const Duration lengthShort = Duration(milliseconds: 1000);
  static const Duration lengthLong = Duration(milliseconds: 3000);

  String _text; //显示的文本
  BuildContext _context; //上下文
  Duration _duration; //持续的时长
  TextStyle? _textStyle; //文本样式
  Color _backgroundColor; //背景颜色
  double _radiusSize; //圆角大小
  EdgeInsetsGeometry? _padding; //内边距大小
  double _top; //顶部距离 百分比

  Toast._(this._text, this._context, this._duration, this._textStyle,
      this._backgroundColor, this._radiusSize, this._padding, this._top);

  factory Toast.makeText(
    BuildContext context,
    String text, {
    Duration duration = lengthShort,
    TextStyle? textStyle,
    Color backgroundColor = Colors.black,
    double radiusSize = 4,
    EdgeInsetsGeometry? padding,
    double top = 0.8,
  }) {
    return Toast._(text, context, duration, textStyle, backgroundColor,
        radiusSize, padding, top);
  }

  OverlayEntry _buildBody() {
    return OverlayEntry(builder: (context) {
      Size size = MediaQuery.of(context).size;
      return Positioned(
          top: size.height * _top,
          child: Material(
            color: Colors.transparent,
            child: Container(
              width: size.width * 0.8,
              alignment: Alignment.center,
              margin: EdgeInsets.only(left: size.width * 0.1),
              child: _buildToastView(),
            ),
          ));
    });
  }

  Widget _buildToastView() {
    return Container(
      padding:
          _padding ?? const EdgeInsets.symmetric(vertical: 2, horizontal: 4),
      decoration: BoxDecoration(
        color: _backgroundColor,
        borderRadius: BorderRadius.all(Radius.circular(_radiusSize)),
      ),
      child: Text(_text,
          style:
              _textStyle ?? const TextStyle(fontSize: 12, color: Colors.white)),
    );
  }

  show() {
    OverlayEntry entry = _buildBody();
    Overlay.of(_context)?.insert(entry);
    Future.delayed(_duration, () {
      entry.remove();
    });
  }
}

调用方式

Toast.makeText(context,"加载成功").show();
Toast.makeText(context,"加载成功",duration: Toast.lengthLong).show();

展示结果

不知道啥情况图片违规了就不放了。。。。

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值