✨ flutter_easyloading: 一个简单易用的 Flutter插件,包含23种loading动画效果、进度条展现、Toast展现。纯Flutter端实现,支持iOS、Android。✨开源地址:https://github.com/huangjiank...git
Flutter
是Google
在2017年推出的一套开源跨平台UI
框架,能够快速地在iOS
、Android
和Web
平台上构建高质量的原生用户界面。Flutter
发布至今,不可谓不说是大受追捧,吸引了大批App
原生开发者、Web
开发者前赴后继的投入其怀抱,也正因为Flutter
是跨平台领域的新星,总的来讲,其生态目前还不是十分完善,我相信对于习惯了原生开发的同窗们来讲,找轮子确定没有了那种章手就莱的感受。好比说这篇文章即将讲到的,如何在Flutter
应用内简单、方便的展现Toast
或者Loading
框呢?github
起初,我也在pub上找到了几个比较优秀的插件:canvas
Flutter
的同窗们都使用过的,它依赖于原生,但对于UI层级的问题,最好在Flutter端解决,这样便于后期维护,也能够减小兼容性问题;Flutter
端实现,调用方便。但缺乏loading
、进度条展现,仍可自定义实现;试用事后,发现这些插件都或多或少不能知足咱们的产品需求,因而便结合本身产品的需求来造了这么个轮子,也但愿能够帮到有须要的同窗们。效果预览:缓存
先看看初期咱们实现弹窗的方式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
方法中:建立StatelessWidget
的build
方法State
对象中:建立StatefulWidget
的State
对象的build
方法中,另外一个是State
的成员变量有关BuildContext
更深刻的探讨不在此文的探讨范围内,若是使用showDialog
实现弹窗操做,那么咱们所考虑的问题即是,如何方便快捷的在任意地方去获取BuildContext
,从而实现弹窗。若是有同窗恰巧也用了showDialog
这种方式的话,我相信,你也会发现,在任意地方获取BuildContext
并非那么简单,并且会产生不少没必要要的代码量。less
那么,咱们就只能使用这种体验极其不友好的方法么?ide
固然不是的,请继续看。函数
Flutter EasyLoading
是一个简单易用的Flutter
插件,包含23种loading
动画效果、进度条展现、Toast
展现。纯Flutter
端实现,兼容性好,支持iOS
、Android
。先简单看下如何使用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
的主要实现过程及思路:
Overlay
、OverlayEntry
实现全局弹窗CustomPaint
与Canvas
实现圆形进度条绘制先看看官方关于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
是一个Stack
的Widget
,能够将OverlayEntry
插入到Overlay
中,使独立的child
窗口悬浮于其余Widget
之上。利用这个特性,咱们能够用Overlay
将 MaterialApp
或CupertinoApp
包裹起来,这样作的目的是为了确保 loading
组件能覆盖在其余组件之上,由于在Flutter
中只会存在一个MaterialApp
或CupertinoApp
根节点组件。(注:这里的作法参考于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();
Overlay
、OverlayEntry
的使用及理解仍是很简单,咱们也能够再更多的使用场景使用他们,好比说,相似PopupWindow
的弹窗效果、全局自定义Dialog
弹窗等等。只要灵活运用,咱们能够实现不少咱们想要的效果。
CustomPaint
与Canvas
实现圆形进度条绘制几乎全部的UI
系统都会提供一个自绘UI
的接口,这个接口一般会提供一块2D
画布Canvas
,Canvas
内部封装了一些基本绘制的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, })
child
为null
时,表明默认绘制区域大小,若是有child
则忽略此参数,画布尺寸则为child
尺寸。若是有child
可是想指定画布为特定大小,可使用SizeBox
包裹CustomPaint
实现。Flutter
会应用一些缓存策略来减小重复渲染的开销。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);
这个函数是绘制的核心所在,它包含了如下两个参数:
drawLine(画线)
、drawRect(画矩形)
、drawCircle(画圆)
等画布如今有了,那么接下来咱们就须要一支画笔了。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
对您有所帮助。