flutter开发实战-可扩展popup弹窗template模版样式

flutter开发实战-可扩展popup弹窗template模版样式

最近在看到一个flutter_beautiful_popup,可以美化弹窗窗口样式。该插件通过一个template模版的类BeautifulPopupTemplate作为抽象的base类。
在这里插入图片描述

一、基类BeautifulPopupTemplate

在BeautifulPopupTemplate中,BeautifulPopupTemplate为抽象类。该类定义了get方法size、width、height、maxWidth、maxHeight、bodyMargin、illustrationPath、primaryColor、close、background、title、content、actions、button。

在一个popup中一般有标题title、内容content、操作的按钮、关闭按钮等,所以这个BeautifulPopupTemplate定义了这些内容。
BeautifulPopupTemplate需要传递一个BeautifulPopup,该类中包括了BeautifulPopupTemplate需要的context、_illustration等。

BeautifulPopupTemplate代码如下

import 'package:flutter/material.dart';
import '../flutter_component_beautiful_popup.dart';
import 'dart:ui' as ui;
import 'package:auto_size_text/auto_size_text.dart';typedef Widget BeautifulPopupButton({required String label,required void Function() onPressed,TextStyle labelStyle,bool outline,bool flat,
});/// You can extend this class to custom your own template.
abstract class BeautifulPopupTemplate extends StatefulWidget {final BeautifulPopup options;BeautifulPopupTemplate(this.options);final State<StatefulWidget> state = BeautifulPopupTemplateState();@overrideState<StatefulWidget> createState() => state;Size get size {double screenWidth = MediaQuery.of(options.context).size.width;double screenHeight = MediaQuery.of(options.context).size.height;double height = screenHeight > maxHeight ? maxHeight : screenHeight;double width;height = height - bodyMargin * 2;if ((screenHeight - height) < 140) {// For keep close button visibleheight = screenHeight - 140;width = height / maxHeight * maxWidth;} else {if (screenWidth > maxWidth) {width = maxWidth - bodyMargin * 2;} else {width = screenWidth - bodyMargin * 2;}height = width / maxWidth * maxHeight;}return Size(width, height);}double get width => size.width;double get height => size.height;double get maxWidth;double get maxHeight;double get bodyMargin;/// The path of the illustration asset.String get illustrationPath => '';String get illustrationKey =>'packages/flutter_component_beautiful_popup/$illustrationPath';Color get primaryColor;double percentW(double n) {return width * n / 100;}double percentH(double n) {return height * n / 100;}Widget get close {return MaterialButton(shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(100)),splashColor: Colors.transparent,hoverColor: Colors.transparent,minWidth: 45,height: 45,child: Container(padding: EdgeInsets.all(20),child: Icon(Icons.close, color: Colors.white70, size: 26),),padding: EdgeInsets.all(0),onPressed: Navigator.of(options.context).pop,);}Widget get background {final illustration = options.illustration;return illustration == null? Image.asset(illustrationKey,width: percentW(100),height: percentH(100),fit: BoxFit.fill,): CustomPaint(size: Size(percentW(100), percentH(100)),painter: ImageEditor(image: illustration,),);}Widget get title {if (options.title is Widget) {return Container(width: percentW(100),height: percentH(10),alignment: Alignment.center,child: options.title,);}return Container(alignment: Alignment.center,width: percentW(100),height: percentH(10),child: Opacity(opacity: 0.95,child: AutoSizeText(options.title,maxLines: 1,style: TextStyle(fontSize: Theme.of(options.context).textTheme.headline6?.fontSize,color: primaryColor,fontWeight: FontWeight.bold,),),),);}Widget get content {return options.content is String? AutoSizeText(options.content,minFontSize: 10,style: TextStyle(color: Colors.black87,),): options.content;}Widget? get actions {final actionsList = options.actions;if (actionsList == null || actionsList.length == 0) return null;return Flex(mainAxisAlignment: MainAxisAlignment.center,crossAxisAlignment: CrossAxisAlignment.center,mainAxisSize: MainAxisSize.max,direction: Axis.horizontal,children: actionsList.map((button) => Flexible(flex: 1,child: Padding(padding: EdgeInsets.symmetric(horizontal: 5),child: button,),),).toList(),);}BeautifulPopupButton get button {return ({required String label,required void Function() onPressed,bool outline = false,bool flat = false,TextStyle labelStyle = const TextStyle(),}) {final gradient = LinearGradient(colors: [primaryColor.withOpacity(0.5),primaryColor,]);final double elevation = (outline || flat) ? 0 : 2;final labelColor =(outline || flat) ? primaryColor : Colors.white.withOpacity(0.95);final decoration = BoxDecoration(gradient: (outline || flat) ? null : gradient,borderRadius: BorderRadius.all(Radius.circular(80.0)),border: Border.all(color: outline ? primaryColor : Colors.transparent,width: (outline && !flat) ? 1 : 0,),);final minHeight = 40.0 - (outline ? 2 : 0);return ElevatedButton(// color: Colors.transparent,// elevation: elevation,// highlightElevation: 0,// splashColor: Colors.transparent,child: Ink(decoration: decoration,child: Container(constraints: BoxConstraints(minWidth: 100,minHeight: minHeight,),alignment: Alignment.center,child: Text(label,style: TextStyle(color: labelColor,).merge(labelStyle),),),),// padding: EdgeInsets.all(0),// shape: RoundedRectangleBorder(//   borderRadius: BorderRadius.circular(50),// ),onPressed: onPressed,);};}List<Positioned> get layout;
}class BeautifulPopupTemplateState extends State<BeautifulPopupTemplate> {OverlayEntry? closeEntry;@overridevoid initState() {super.initState();// Display close buttonFuture.delayed(Duration.zero, () {closeEntry = OverlayEntry(builder: (ctx) {final bottom = (MediaQuery.of(context).size.height -widget.height -widget.bodyMargin * 2) /4 -20;return Stack(// overflow: Overflow.visible,clipBehavior: Clip.none,children: <Widget>[Positioned(child: Container(alignment: Alignment.center,child: widget.options.close ?? Container(),),left: 0,right: 0,bottom: bottom,)],);},);final entry = closeEntry;if (entry != null) Overlay.of(context)?.insert(entry);});}@overrideWidget build(BuildContext context) {return Column(mainAxisSize: MainAxisSize.min,mainAxisAlignment: MainAxisAlignment.center,children: <Widget>[Material(color: Colors.transparent,child: Container(margin: EdgeInsets.all(widget.bodyMargin),height: widget.height,width: widget.width,child: Stack(// overflow: Overflow.visible,clipBehavior: Clip.none,children: widget.layout,),),)],);}@overridevoid dispose() {closeEntry?.remove();super.dispose();}
}class ImageEditor extends CustomPainter {ui.Image image;ImageEditor({required this.image,});@overridevoid paint(Canvas canvas, Size size) {canvas.drawImageRect(image,Rect.fromLTRB(0, 0, image.width.toDouble(), image.height.toDouble()),Rect.fromLTRB(0, 0, size.width, size.height),new Paint(),);}@overridebool shouldRepaint(CustomPainter oldDelegate) => false;
}

二、BeautifulPopup

该类中包括了BeautifulPopupTemplate需要的context、_illustration等。

library flutter_component_beautiful_popup;import 'dart:typed_data';import 'package:flutter/material.dart';
import 'dart:ui' as ui;
import 'package:image/image.dart' as img;
import 'package:flutter/services.dart';
import 'templates/Common.dart';
import 'templates/OrangeRocket.dart';
import 'templates/GreenRocket.dart';
import 'templates/OrangeRocket2.dart';
import 'templates/Coin.dart';
import 'templates/BlueRocket.dart';
import 'templates/Thumb.dart';
import 'templates/Gift.dart';
import 'templates/Camera.dart';
import 'templates/Notification.dart';
import 'templates/Geolocation.dart';
import 'templates/Success.dart';
import 'templates/Fail.dart';
import 'templates/Authentication.dart';
import 'templates/Term.dart';
import 'templates/RedPacket.dart';export 'templates/Common.dart';
export 'templates/OrangeRocket.dart';
export 'templates/GreenRocket.dart';
export 'templates/OrangeRocket2.dart';
export 'templates/Coin.dart';
export 'templates/BlueRocket.dart';
export 'templates/Thumb.dart';
export 'templates/Gift.dart';
export 'templates/Camera.dart';
export 'templates/Notification.dart';
export 'templates/Geolocation.dart';
export 'templates/Success.dart';
export 'templates/Fail.dart';
export 'templates/Authentication.dart';
export 'templates/Term.dart';
export 'templates/RedPacket.dart';class BeautifulPopup {BuildContext _context;BuildContext get context => _context;Type? _template;Type? get template => _template;BeautifulPopupTemplate Function(BeautifulPopup options)? _build;BeautifulPopupTemplate get instance {final build = _build;if (build != null) return build(this);switch (template) {case TemplateOrangeRocket:return TemplateOrangeRocket(this);case TemplateGreenRocket:return TemplateGreenRocket(this);case TemplateOrangeRocket2:return TemplateOrangeRocket2(this);case TemplateCoin:return TemplateCoin(this);case TemplateBlueRocket:return TemplateBlueRocket(this);case TemplateThumb:return TemplateThumb(this);case TemplateGift:return TemplateGift(this);case TemplateCamera:return TemplateCamera(this);case TemplateNotification:return TemplateNotification(this);case TemplateGeolocation:return TemplateGeolocation(this);case TemplateSuccess:return TemplateSuccess(this);case TemplateFail:return TemplateFail(this);case TemplateAuthentication:return TemplateAuthentication(this);case TemplateTerm:return TemplateTerm(this);case TemplateRedPacket:default:return TemplateRedPacket(this);}}ui.Image? _illustration;ui.Image? get illustration => _illustration;dynamic title = '';dynamic content = '';List<Widget>? actions;Widget? close;bool? barrierDismissible;Color? primaryColor;BeautifulPopup({required BuildContext context,required Type? template,})   : _context = context,_template = template {primaryColor = instance.primaryColor; // Get the default primary color.}static BeautifulPopup customize({required BuildContext context,required BeautifulPopupTemplate Function(BeautifulPopup options) build,}) {final popup = BeautifulPopup(context: context,template: null,);popup._build = build;return popup;}/// Recolor the BeautifulPopup./// This method is  kind of slow.RFuture<BeautifulPopup> recolor(Color color) async {this.primaryColor = color;final illustrationData = await rootBundle.load(instance.illustrationKey);final buffer = illustrationData.buffer.asUint8List();img.Image? asset;asset = img.readPng(buffer);if (asset != null) {img.adjustColor(asset,saturation: 0,// hue: 0,);img.colorOffset(asset,red: color.red,// I don't know why the effect is nicer with the number ╮(╯▽╰)╭green: color.green ~/ 3,blue: color.blue ~/ 2,alpha: 0,);}final paint = await PaintingBinding.instance?.instantiateImageCodec(asset != null ? Uint8List.fromList(img.encodePng(asset)) : buffer);final nextFrame = await paint?.getNextFrame();_illustration = nextFrame?.image;return this;}/// `title`: Must be a `String` or `Widget`. Defaults to `''`.////// `content`: Must be a `String` or `Widget`. Defaults to `''`.////// `actions`: The set of actions that are displaed at bottom of the dialog,//////  Typically this is a list of [BeautifulPopup.button]. Defaults to `[]`.////// `barrierDismissible`: Determine whether this dialog can be dismissed. Default to `False`.////// `close`: Close widget.Future<T?> show<T>({dynamic title,dynamic content,List<Widget>? actions,bool barrierDismissible = false,Widget? close,}) {this.title = title;this.content = content;this.actions = actions;this.barrierDismissible = barrierDismissible;this.close = close ?? instance.close;final child = WillPopScope(onWillPop: () {return Future.value(barrierDismissible);},child: instance,);return showGeneralDialog<T>(barrierColor: Colors.black38,barrierDismissible: barrierDismissible,barrierLabel: barrierDismissible ? 'beautiful_popup' : null,context: context,pageBuilder: (context, animation1, animation2) {return child;},transitionDuration: Duration(milliseconds: 150),transitionBuilder: (ctx, a1, a2, child) {return Transform.scale(scale: a1.value,child: Opacity(opacity: a1.value,child: child,),);},);}BeautifulPopupButton get button => instance.button;
}

三、根据需要继承BeautifulPopupTemplate

根据需要指定弹窗的样式,例如TemplateGift继承了BeautifulPopupTemplate
重写了button、layout、等方法

import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'Common.dart';
import '../flutter_component_beautiful_popup.dart';/// ![](https://raw.githubusercontent.com/jaweii/Flutter_beautiful_popup/master/img/bg/gift.png)
class TemplateGift extends BeautifulPopupTemplate {final BeautifulPopup options;TemplateGift(this.options) : super(options);@overridefinal illustrationPath = 'img/bg/gift.png';@overrideColor get primaryColor => options.primaryColor ?? Color(0xffFF2F49);@overridefinal maxWidth = 400;@overridefinal maxHeight = 580;@overridefinal bodyMargin = 30;@overrideBeautifulPopupButton get button {return ({required String label,required void Function() onPressed,bool outline = false,bool flat = false,TextStyle labelStyle = const TextStyle(),}) {final gradient = LinearGradient(colors: [primaryColor.withOpacity(0.5),primaryColor,]);final double elevation = (outline || flat) ? 0 : 2;final labelColor =(outline || flat) ? primaryColor : Colors.white.withOpacity(0.95);final decoration = BoxDecoration(gradient: (outline || flat) ? null : gradient,borderRadius: BorderRadius.all(Radius.circular(80.0)),border: Border.all(color: outline ? primaryColor : Colors.transparent,width: (outline && !flat) ? 1 : 0,),);final minHeight = 40.0 - (outline ? 4 : 0);return ElevatedButton(// color: Colors.transparent,// elevation: elevation,// highlightElevation: 0,// splashColor: Colors.transparent,child: Ink(decoration: decoration,child: Container(constraints: BoxConstraints(minWidth: 100,minHeight: minHeight,),alignment: Alignment.center,child: Text(label,style: TextStyle(color: Colors.white.withOpacity(0.95),fontWeight: FontWeight.bold,).merge(labelStyle),),),),// padding: EdgeInsets.all(0),// shape: RoundedRectangleBorder(//   borderRadius: BorderRadius.circular(50),// ),onPressed: onPressed,);};}@overrideget layout {return [Positioned(child: background,),Positioned(top: percentH(26),child: title,),Positioned(top: percentH(36),left: percentW(5),right: percentW(5),height: percentH(actions == null ? 60 : 50),child: content,),Positioned(bottom: percentW(5),left: percentW(5),right: percentW(5),child: actions ?? Container(),),];}
}

四、调用显示弹窗

调用显示弹窗使用的showGeneralDialog,弹出弹窗代码如下

/// `title`: Must be a `String` or `Widget`. Defaults to `''`.////// `content`: Must be a `String` or `Widget`. Defaults to `''`.////// `actions`: The set of actions that are displaed at bottom of the dialog,//////  Typically this is a list of [BeautifulPopup.button]. Defaults to `[]`.////// `barrierDismissible`: Determine whether this dialog can be dismissed. Default to `False`.////// `close`: Close widget.Future<T?> show<T>({dynamic title,dynamic content,List<Widget>? actions,bool barrierDismissible = false,Widget? close,}) {this.title = title;this.content = content;this.actions = actions;this.barrierDismissible = barrierDismissible;this.close = close ?? instance.close;final child = WillPopScope(onWillPop: () {return Future.value(barrierDismissible);},child: instance,);return showGeneralDialog<T>(barrierColor: Colors.black38,barrierDismissible: barrierDismissible,barrierLabel: barrierDismissible ? 'beautiful_popup' : null,context: context,pageBuilder: (context, animation1, animation2) {return child;},transitionDuration: Duration(milliseconds: 150),transitionBuilder: (ctx, a1, a2, child) {return Transform.scale(scale: a1.value,child: Opacity(opacity: a1.value,child: child,),);},);}

这里看到源码后,觉得格式结构很好。可以参考将flutter_beautiful_popup下载后看下源码。地址:https://pub-web.flutter-io.cn/packages/flutter_beautiful_popup

五、小结

flutter开发实战-可扩展popup弹窗template模版样式

学习记录,每天不停进步。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/667799.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

RabbitMQ——基于 KeepAlived + HAProxy 搭建 RabbitMQ 高可用负载均衡集群

一、集群简介 1.1 集 群架构 当单台 RabbitMQ 服务器的处理消息的能力达到瓶颈时&#xff0c;此时可以通过 RabbitMQ 集群来进行扩展&#xff0c;从而达到提升吞吐量的目的。 RabbitMQ 集群是一个或多个节点的逻辑分组&#xff0c;集群中的每个节点都是对等的&#xff0c;每…

目标检测及相关算法介绍

文章目录 目标检测介绍目标检测算法分类目标检测算法模型组成经典目标检测论文 目标检测介绍 目标检测是计算机视觉领域中的一项重要任务&#xff0c;旨在识别图像或视频中的特定对象的位置并将其与不同类别中的对象进行分类。与图像分类任务不同&#xff0c;目标检测不仅需要…

OfficeWeb365 Readfile 任意文件读取漏洞

免责声明&#xff1a;文章来源互联网收集整理&#xff0c;请勿利用文章内的相关技术从事非法测试&#xff0c;由于传播、利用此文所提供的信息或者工具而造成的任何直接或者间接的后果及损失&#xff0c;均由使用者本人负责&#xff0c;所产生的一切不良后果与文章作者无关。该…

主品牌竞争方向之洞察竞争环境变化

随着市场环境加速变化&#xff0c;如果只停留在过去&#xff0c;未能及时进化的主品牌可能会逐渐老化&#xff0c;失去市场竞争力&#xff0c;甚至被新兴竞争对手所取代。因此&#xff0c;企业需要不断洞察竞争环境变化&#xff0c;避免企业走向衰退&#xff0c;让主品牌进化&a…

TrinityCore安装记录

TrinityCore模拟魔兽世界&#xff08;World of Warcraft&#xff09;的开源项目&#xff0c;并且该项目代码广泛的优化、改善和清理代码。 前期按照官方手册按部就班的安装即可。 注意几点&#xff1a; 1 需要配置Ubuntu22.04版本的服务器或者Debian11 服务器。2 需要使用gi…

Office恢复旧UI|Office UI问题|Word UI|小喇叭找不到

Office恢复旧UI&#xff5c;Office UI问题&#xff5c;Word UI&#xff5c;小喇叭找不到 问题描述&#xff1a;Office新版本默认新UI&#xff0c;主界面没有小喇叭可以切换到旧UI. 解决方案&#xff1a; 以下述内容新建.txt&#xff0c;保存并改后缀为.reg&#xff0c;双击打开…

Flink生产环境常见问题及解决方法

在Flink生产环境中&#xff0c;可能会遇到一些常见的问题。下面简单的介绍几个常见问题&#xff0c;并且提供一些解决方法&#xff0c;来帮助你更好地应对这些问题。 故障转移和高可用性 Flink提供了故障转移和高可用性机制&#xff0c;但在配置和使用时可能会遇到问题。如果…

154基于matlab的二维元胞自动机模拟森林火灾(生命游戏 )和模拟收费站交通流

基于matlab的二维元胞自动机模拟森林火灾&#xff08;生命游戏 &#xff09;和模拟收费站交通流。全国大学生美国建模竞赛&#xff0c;程序已调通&#xff0c;可直接运行。 154 元细胞自动机 森林起火 收费站交通 (xiaohongshu.com)

Linux的库文件

概述&#xff1a; 库文件一般就是编译好的二进制文件&#xff0c;用于在链接阶段同目标代码一块生成可执行文件&#xff0c;或者运行可执行文件的时候被加载&#xff0c;以遍调用库文件中的某段代码。 动态链接都是索引的.so文件&#xff0c;静态链接都是压缩打包的.a文件。 …

Python新春烟花盛宴

写在前面 哈喽小伙伴们&#xff0c;博主在这里提前祝大家新春快乐呀&#xff01;我用Python绽放了一场新春烟花盛宴&#xff0c;一起来看看吧&#xff01; 环境需求 python3.11.4及以上PyCharm Community Edition 2023.2.5pyinstaller6.2.0&#xff08;可选&#xff0c;这个库…

React实例之完善布局菜单(三)

接着上篇的内容继续。规划界面布局。界面分为三个部分&#xff0c;左边为菜单部分&#xff0c;右边上部有个 80 px 高度左右的功能区&#xff0c;下面是主内容区。 依据这个设计&#xff0c;我们进行下面的步骤&#xff1a; 在 SMenu项目中创建一个目录&#xff1a; SLayout, …

C++实战Opencv第二天——色彩空间转换函数和opencv中图像对象创建与赋值(从零开始,保姆教学)

OpenCV是一个强大的计算机视觉库&#xff0c;使用C作为主要编程语言&#xff0c;对于图像处理和计算机视觉领域具有重要意义。其提供了丰富的功能和算法&#xff0c;使得开发者能够快速实现各种图像处理和计算机视觉应用。OpenCV C为图像处理和计算机视觉领域的开发者提供了一个…

【实战】阿里智能编码助手通义灵码

文章目录 前言技术积累通义灵码是什么&#xff1f;Copilot是什么&#xff1f;通义灵码主要功能通义灵码有哪些优势&#xff1f;通义灵码支持语言/工具通义灵码接入方式通义灵码帮助中心 实战演示安装插件行/函数级实时续写自然语言生成代码代码优化单元测试生成代码注释生成解释…

【RPA】什么是RPA

一、什么是RPA? RPA&#xff0c;全称机器人流程自动化&#xff0c;是一种利用机器人技术实现工作信息与业务交互自动化的过程。它能够按照预先设计的流程&#xff0c;高效地处理大量的工作信息与业务交互&#xff0c;极大地节约了人工成本。如今&#xff0c;RPA已成为智能化软…

贪心算法篇

“靠漫步&#xff0c;将生趣填饱~” 贪心算法简介&#xff1f; 贪心算法&#xff08;Greedy Algorithm&#xff09;&#xff0c;也称为贪婪算法&#xff0c;是一种在解决问题时采取贪心策略的方法。其基本原理是很简单的&#xff1a; “在每个决策点上都选择当下看似最好的选项…

《动手学深度学习(PyTorch版)》笔记7.1

注&#xff1a;书中对代码的讲解并不详细&#xff0c;本文对很多细节做了详细注释。另外&#xff0c;书上的源代码是在Jupyter Notebook上运行的&#xff0c;较为分散&#xff0c;本文将代码集中起来&#xff0c;并加以完善&#xff0c;全部用vscode在python 3.9.18下测试通过&…

FANUC机器人PROF-017从机断开故障报警处理方法总结

FANUC机器人PROF-017从机断开故障报警处理方法总结 情况说明&#xff1a; 机器人安装的是PROFINET板卡&#xff0c;按照手册进行PROFINET配置之后&#xff0c;重启控制柜&#xff0c;此时系统提示&#xff1a;PROF-017 从机断开&#xff0c; 如下图所示&#xff0c; 打电话咨…

HTML5和CSS3强化知识总结

HTML5的新特性 HTML5的新增特性主要是针对于以前的不足&#xff0c;增一些新的标签、新的表单和新的表单属性等。这些新特性都有兼容性问题&#xff0c;基本是IE9以上版本的浏览器才支持&#xff0c;如果不考虑兼容性问题&#xff0c;可以大量使用这些新特性。 HTML5新增的语义…

ubuntu 18.04修改网卡名称

1.原来网卡配置 现在要把enp3s0的名称改为eth0 2. 总共修改三个文件 第一个修改 sudo vi /etc/default/grub 添加最后一行 GRUB_CMDLINE_LINUX"net.ifnames0 biosdevname0" 第二个修改sudo vi /etc/udev/rules.d/70-persistent-net.rules 如果没有就新建文件&a…

uniapp android和微信小程序实现PDF在线预览

在使用uniapp开发移动端时&#xff0c;微信开发者工具里webview能正常打开后端接口返回的pdf文件流。正式发布后&#xff0c;在配置了业务域名和服务器域名的前提下&#xff0c;预览pdf文件却只能看到白屏&#xff0c;因此我猜测微信小程序不能通过webview读取文件流。这个想法…