全局Toast

原生Android中有一个Toast类型的通知对象,可以悬浮显示一些信息,类似下图的效果:

 

 

 Flutter中同样可以实现类似的效果:

需要在pubspec.yaml中引入如下组件:

 

fluttertoast: ^4.0.1

 

 由于使用较为频繁,可以将其写成一个静态的全局工具类,在需要的地方直接进行调用显示Toast:

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
 
class ToastUtil{
  static ToastUtil instance;
 
  static getInstance(){
    if(instance == null){
      instance = new ToastUtil();
    }
    return instance;
  }
 
  static showToast(String msg) async{
    Fluttertoast.showToast(
      msg: msg,
      toastLength: Toast.LENGTH_SHORT,
      gravity: ToastGravity.TOP,
      timeInSecForIosWeb: 1,
      backgroundColor: Colors.black26,
      textColor: Colors.white,
      fontSize: 16.0,
    );
  }
}

 由于我的显示位置比较固定,因此只提供了一个静态的showToast方法,这个方法会在顶部显示一个偏黑色背景、文字颜色为白色的Toast,如果有别的位置,只需仿照上述showToast()方法,改变其中的gravity参数即可。

实现代码:

if (connectivityResult != ConnectivityResult.none) {
    var httpUtil = new HttpUtil();
    var server = 'http://www.aac.com:8001/api';
    try {
      server = server + "data=" + barCode;
      var data = httpUtil.get(server);
      if (data != null && data['status'] == 'success') {
        isSuccess = true;
      }
    } catch (e) {
      ToastUtil.showToast("出现异常:" + e.toString());
    }
} else {
    ToastUtil.showToast("无网络连接,已准备将数据保存至本地,请在连接网络后重新发送");
}

 效果图:

 

 

 



posted @ 2020-10-15 15:47  猎喵Rachel  阅读(338)  评论(0)    收藏  举报