Flutter EasyLoading - 让全局Toast/Loading更简单

flutter_easyloading: 一个简单易用的Flutter插件,包含23种loading动画效果、进度条展现、Toast展现。纯Flutter端实现,支持iOS、Android。git

开源地址github.com/huangjianke…github

前言

FlutterGoogle在2017年推出的一套开源跨平台UI框架,能够快速地在iOSAndroidWeb平台上构建高质量的原生用户界面。Flutter发布至今,不可谓不说是大受追捧,吸引了大批App原生开发者、Web开发者前赴后继的投入其怀抱,也正因为Flutter是跨平台领域的新星,总的来讲,其生态目前还不是十分完善,我相信对于习惯了原生开发的同窗们来讲,找轮子确定没有了那种章手就莱的感受。好比说这篇文章即将讲到的,如何在Flutter应用内简单、方便的展现Toast或者Loading框呢?canvas

探索

起初,我也在pub上找到了几个比较优秀的插件:缓存

  • FlutterToast: 这个插件应该是不少刚入坑Flutter的同窗们都使用过的,它依赖于原生,但对于UI层级的问题,最好在Flutter端解决,这样便于后期维护,也能够减小兼容性问题;
  • flutter_oktoast: 纯Flutter端实现,调用方便。但缺乏loading、进度条展现,仍可自定义实现;

试用事后,发现这些插件都或多或少不能知足咱们的产品需求,因而便结合本身产品的需求来造了这么个轮子,也但愿能够帮到有须要的同窗们。效果预览:markdown

flutter_easyloading

实现

showDialog 实现

先看看初期咱们实现弹窗的方式showDialog,部分源码以下:app

Future<T> showDialog<T>({
  @required BuildContext context,
  bool barrierDismissible = true,
  @Deprecated(
    'Instead of using the "child" argument, return the child from a closure '
    'provided to the "builder" argument. This will ensure that the BuildContext '
    'is appropriate for widgets built in the dialog. '
    'This feature was deprecated after v0.2.3.'
  )
  Widget child,
  WidgetBuilder builder,
  bool useRootNavigator = true,
})
复制代码

这里有个必传参数context,想必接触过Flutter开发一段时间的同窗,都会对BuildContext有所了解。简单来讲BuildContext就是构建Widget中的应用上下文,是Flutter的重要组成部分。BuildContext只出如今两个地方:框架

  • StatelessWidget.build方法中:建立StatelessWidgetbuild方法
  • State对象中:建立StatefulWidgetState对象的build方法中,另外一个是State的成员变量

有关BuildContext更深刻的探讨不在此文的探讨范围内,若是使用showDialog实现弹窗操做,那么咱们所考虑的问题即是,如何方便快捷的在任意地方去获取BuildContext,从而实现弹窗。若是有同窗恰巧也用了showDialog这种方式的话,我相信,你也会发现,在任意地方获取BuildContext并非那么简单,并且会产生不少没必要要的代码量。less

那么,咱们就只能使用这种体验极其不友好的方法么?ide

固然不是的,请继续看。函数

Flutter EasyLoading 介绍

Flutter EasyLoading是一个简单易用的Flutter插件,包含23loading动画效果、进度条展现、Toast展现。纯Flutter端实现,兼容性好,支持iOSAndroid。先简单看下如何使用Flutter EasyLoading

安装

将如下代码添加到您项目中的 pubspec.yaml 文件:

dependencies:
 flutter_easyloading: ^1.1.0 // 请使用最新版
复制代码

导入

import 'package:flutter_easyloading/flutter_easyloading.dart';
复制代码

如何使用

首先, 使用 FlutterEasyLoading 组件包裹您的App组件:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    /// 子组件一般为 [MaterialApp] 或者 [CupertinoApp].
    /// 这样作是为了确保 loading 组件能覆盖在其余组件之上.
    return FlutterEasyLoading(
      child: MaterialApp(
        title: 'Flutter EasyLoading',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: MyHomePage(title: 'Flutter EasyLoading'),
      ),
    );
  }
}
复制代码

而后, 请尽情使用吧:

EasyLoading.show(status: 'loading...'); 

EasyLoading.showProgress(0.3, status: 'downloading...');

EasyLoading.showSuccess('Great Success!');

EasyLoading.showError('Failed with Error');

EasyLoading.showInfo('Useful Information.');

EasyLoading.dismiss();
复制代码

自定义样式

首先,咱们看下Flutter EasyLoading目前支持的自定义属性:

/// loading的样式, 默认[EasyLoadingStyle.dark].
EasyLoadingStyle loadingStyle;

/// loading的指示器类型, 默认[EasyLoadingIndicatorType.fadingCircle].
EasyLoadingIndicatorType indicatorType;

/// loading的遮罩类型, 默认[EasyLoadingMaskType.none].
EasyLoadingMaskType maskType;

/// 文本的对齐方式 , 默认[TextAlign.center].
TextAlign textAlign;

/// loading内容区域的内边距.
EdgeInsets contentPadding;

/// 文本的内边距.
EdgeInsets textPadding;

/// 指示器的大小, 默认40.0.
double indicatorSize;

/// loading的圆角大小, 默认5.0.
double radius;

/// 文本大小, 默认15.0.
double fontSize;

/// 进度条指示器的宽度, 默认2.0.
double progressWidth;

/// [showSuccess] [showError] [showInfo]的展现时间, 默认2000ms.
Duration displayDuration;

/// 文本的颜色, 仅对[EasyLoadingStyle.custom]有效.
Color textColor;

/// 指示器的颜色, 仅对[EasyLoadingStyle.custom]有效.
Color indicatorColor;

/// 进度条指示器的颜色, 仅对[EasyLoadingStyle.custom]有效.
Color progressColor;

/// loading的背景色, 仅对[EasyLoadingStyle.custom]有效.
Color backgroundColor;

/// 遮罩的背景色, 仅对[EasyLoadingMaskType.custom]有效.
Color maskColor;

/// 当loading展现的时候,是否容许用户操做.
bool userInteractions;

/// 展现成功状态的自定义组件
Widget successWidget;

/// 展现失败状态的自定义组件
Widget errorWidget;

/// 展现信息状态的自定义组件
Widget infoWidget;
复制代码

由于 EasyLoading 是一个全局单例, 因此咱们能够在任意一个地方自定义它的样式:

EasyLoading.instance
  ..displayDuration = const Duration(milliseconds: 2000)
  ..indicatorType = EasyLoadingIndicatorType.fadingCircle
  ..loadingStyle = EasyLoadingStyle.dark
  ..indicatorSize = 45.0
  ..radius = 10.0
  ..backgroundColor = Colors.green
  ..indicatorColor = Colors.yellow
  ..textColor = Colors.yellow
  ..maskColor = Colors.blue.withOpacity(0.5);
复制代码

更多的指示器动画类型可查看 flutter_spinkit showcase

能够看到,Flutter EasyLoading的集成以及使用至关的简单,并且有丰富的自定义样式,总会有你满意的。

接下来,咱们来看看Flutter EasyLoading的代码实现。

Flutter EasyLoading 的实现

本文将经过如下两个知识点来介绍Flutter EasyLoading的主要实现过程及思路:

  • OverlayOverlayEntry实现全局弹窗
  • CustomPaintCanvas实现圆形进度条绘制

Overlay、OverlayEntry 实现全局弹窗

先看看官方关于Overlay的描述:

/// A [Stack] of entries that can be managed independently.
///
/// Overlays let independent child widgets "float" visual elements on top of
/// other widgets by inserting them into the overlay's [Stack]. The overlay lets
/// each of these widgets manage their participation in the overlay using
/// [OverlayEntry] objects.
///
/// Although you can create an [Overlay] directly, it's most common to use the
/// overlay created by the [Navigator] in a [WidgetsApp] or a [MaterialApp]. The
/// navigator uses its overlay to manage the visual appearance of its routes.
///
/// See also:
///
/// * [OverlayEntry].
/// * [OverlayState].
/// * [WidgetsApp].
/// * [MaterialApp].
class Overlay extends StatefulWidget {}
复制代码

也就是说,Overlay是一个StackWidget,能够将OverlayEntry插入到Overlay中,使独立的child窗口悬浮于其余Widget之上。利用这个特性,咱们能够用OverlayMaterialAppCupertinoApp包裹起来,这样作的目的是为了确保 loading 组件能覆盖在其余组件之上,由于在Flutter中只会存在一个MaterialAppCupertinoApp根节点组件。(注:这里的作法参考于flutter_oktoast插件,感谢)。

另外,这样作的目的还能够解决另一个核心问题:将 context 缓存到内存中,后续全部调用均不须要提供context。实现以下:

@override
Widget build(BuildContext context) {
  return Directionality(
    child: Overlay(
      initialEntries: [
        OverlayEntry(
          builder: (BuildContext _context) {
            // 缓存 context
            EasyLoading.instance.context = _context;
            // 这里的child必须是MaterialApp或CupertinoApp
            return widget.child;
          },
        ),
      ],
    ),
    textDirection: widget.textDirection,
  );
}
复制代码
// 建立OverlayEntry
OverlayEntry _overlayEntry = OverlayEntry(
  builder: (BuildContext context) => LoadingContainer(
    key: _key,
    status: status,
    indicator: w,
    animation: _animation,
  ),
);

// 将OverlayEntry插入到Overlay中
// 经过Overlay.of()咱们能够获取到App根节点的Overlay
Overlay.of(_getInstance().context).insert(_overlayEntry);

// 调用OverlayEntry自身的remove()方法,从所在的Overlay中移除本身
_overlayEntry.remove();
复制代码

OverlayOverlayEntry的使用及理解仍是很简单,咱们也能够再更多的使用场景使用他们,好比说,相似PopupWindow的弹窗效果、全局自定义Dialog弹窗等等。只要灵活运用,咱们能够实现不少咱们想要的效果。

CustomPaintCanvas实现圆形进度条绘制

几乎全部的UI系统都会提供一个自绘UI的接口,这个接口一般会提供一块2D画布CanvasCanvas内部封装了一些基本绘制的API,咱们能够经过Canvas绘制各类自定义图形。在Flutter中,提供了一个CustomPaint组件,它能够结合一个画笔CustomPainter来实现绘制自定义图形。接下来我将简单介绍下圆形进度条的实现。

咱们先来看看CustomPaint构造函数:

const CustomPaint({
  Key key,
  this.painter,
  this.foregroundPainter,
  this.size = Size.zero,
  this.isComplex = false,
  this.willChange = false,
  Widget child,
})
复制代码
  • painter: 背景画笔,会显示在子节点后面;
  • foregroundPainter: 前景画笔,会显示在子节点前面
  • size:当childnull时,表明默认绘制区域大小,若是有child则忽略此参数,画布尺寸则为child尺寸。若是有child可是想指定画布为特定大小,可使用SizeBox包裹CustomPaint实现。
  • isComplex:是否复杂的绘制,若是是,Flutter会应用一些缓存策略来减小重复渲染的开销。
  • willChange:和isComplex配合使用,当启用缓存时,该属性表明在下一帧中绘制是否会改变。

能够看到,绘制时咱们须要提供前景或背景画笔,二者也能够同时提供。咱们的画笔须要继承CustomPainter类,咱们在画笔类中实现真正的绘制逻辑。

接下来,咱们看下怎么经过CustomPainter绘制圆形进度条:

class _CirclePainter extends CustomPainter {
  final Color color;
  final double value;
  final double width;

  _CirclePainter({
    @required this.color,
    @required this.value,
    @required this.width,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = color
      ..strokeWidth = width
      ..style = PaintingStyle.stroke
      ..strokeCap = StrokeCap.round;
    canvas.drawArc(
      Offset.zero & size,
      -math.pi / 2,
      math.pi * 2 * value,
      false,
      paint,
    );
  }

  @override
  bool shouldRepaint(_CirclePainter oldDelegate) => value != oldDelegate.value;
}
复制代码

从上面咱们能够看到,CustomPainter中定义了一个虚函数paint:

void paint(Canvas canvas, Size size);
复制代码

这个函数是绘制的核心所在,它包含了如下两个参数:

  • canvas: 画布,包括各类绘制方法, 如 drawLine(画线)drawRect(画矩形)drawCircle(画圆)
  • size: 当前绘制区域大小

画布如今有了,那么接下来咱们就须要一支画笔了。Flutter提供了Paint类来实现画笔。并且能够配置画笔的各类属性如粗细、颜色、样式等,好比:

final paint = Paint()
  ..color = color // 颜色
  ..strokeWidth = width // 宽度
  ..style = PaintingStyle.stroke
  ..strokeCap = StrokeCap.round;
复制代码

最后,咱们就是须要使用drawArc方法进行圆弧的绘制了:

canvas.drawArc(
  Offset.zero & size,
  -math.pi / 2,
  math.pi * 2 * value,
  false,
  paint,
);
复制代码

到此,咱们就完成了进度条的绘制。另外咱们也须要注意下绘制性能问题。好在类中提供了重写shouldRepaint的方法,这个方法决定了画布何时会从新绘制,在复杂的绘制中对提高绘制性能是至关有成效的。

@override
bool shouldRepaint(_CirclePainter oldDelegate) => value != oldDelegate.value;
复制代码

结语

毫无疑问,Flutter的前景是一片光明的,也许如今还存在诸多问题,但我相信更多的人会愿意陪着Flutter一块儿成长。期待着Flutter的生态圈的完善。后期我也会逐步完善Flutter EasyLoading,期待您的宝贵意见。

最后,但愿Flutter EasyLoading对您有所帮助。

相关文章
相关标签/搜索