JoJo的个人博客

记录精彩的程序人生

目录
Flutter Toast组件实现
/  

Flutter Toast组件实现

Overlay

首先介绍下Overlay组件,通过overlay组件可以实现一个UI上面的浮层

通过Overlay.of获取OverlayState对象,调用OverlayState.insert添加OverlayEntry,当不需要时候,通过OverlayEntry.remove移除OverlayEntry

附上toast组件代码

import 'package:flutter/material.dart';

import '../main.dart';

var toast = new Toast();

///toast组件
class Toast {
  Toast._internal();

  static Toast _singleton = new Toast._internal();

  factory Toast() => _singleton;

  void show(String message, {int duration}) {
    OverlayEntry entry = OverlayEntry(builder: (context) {
      return Container(
        color: Colors.transparent,
        margin: EdgeInsets.only(
          top: MediaQuery.of(context).size.height * 0.7,
        ),
        alignment: Alignment.center,
        child: Center(
          child: Material(
            child: Container(
              padding: EdgeInsets.all(8),
              margin: EdgeInsets.fromLTRB(20, 0, 20, 0),
              decoration: BoxDecoration(
                  color: Colors.black54,
                  borderRadius: BorderRadius.circular(4)),
              child: Text(
                message,
                style: TextStyle(color: Colors.white, fontSize: 14),
              ),
            ),
          ),
        ),
      );
    });

    Overlay.of(MyApp.context).insert(entry);
    Future.delayed(Duration(seconds: duration ?? 2)).then((value) {
      entry.remove();
    });
  }
}


标题:Flutter Toast组件实现
作者:SunnySky
地址:https://www.tianyang.pub/articles/2020/07/02/1593676823718.html

评论