flutter日期选择器仅选择年、月

在这里插入图片描述
引入包:flutter_datetime_picker: 1.5.0
封装

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';class ATuiDateTimePicker {static Future<DateTime> showDatePicker(BuildContext context, {bool showTitleActions: true,bool isShowDay: true,DateTime minTime,DateTime maxTime,DateChangedCallback onChanged,DateChangedCallback onConfirm,DateCancelledCallback onCancel,locale: LocaleType.en,DateTime currentTime,DatePickerTheme theme,}) async {return await Navigator.push(context,_DatePickerRoute(showTitleActions: showTitleActions,onChanged: onChanged,onConfirm: onConfirm,onCancel: onCancel,locale: locale,theme: theme,isShowDay: isShowDay,barrierLabel:MaterialLocalizations.of(context).modalBarrierDismissLabel,pickerModel: DatePickerModel(currentTime: currentTime,maxTime: maxTime,minTime: minTime,locale: locale,),),);}
}class _DatePickerRoute<T> extends PopupRoute<T> {_DatePickerRoute({this.showTitleActions,this.onChanged,this.onConfirm,this.onCancel,theme,this.barrierLabel,this.locale,this.isShowDay,RouteSettings settings,pickerModel,})  : this.pickerModel = pickerModel ?? DatePickerModel(),this.theme = theme ?? DatePickerTheme(),super(settings: settings);final bool showTitleActions;final DateChangedCallback onChanged;final DateChangedCallback onConfirm;final DateCancelledCallback onCancel;final DatePickerTheme theme;final LocaleType locale;final BasePickerModel pickerModel;final bool isShowDay;Duration get transitionDuration => const Duration(milliseconds: 200);bool get barrierDismissible => true;final String barrierLabel;Color get barrierColor => Colors.black54;AnimationController _animationController;AnimationController createAnimationController() {assert(_animationController == null);_animationController =BottomSheet.createAnimationController(navigator.overlay);return _animationController;}Widget buildPage(BuildContext context, Animation<double> animation,Animation<double> secondaryAnimation) {Widget bottomSheet = MediaQuery.removePadding(context: context,removeTop: true,child: _DatePickerComponent(onChanged: onChanged,locale: this.locale,route: this,pickerModel: pickerModel,isShowDay: isShowDay,),);return InheritedTheme.captureAll(context, bottomSheet);}
}class _DatePickerComponent extends StatefulWidget {_DatePickerComponent({Key key, this.route,this.onChanged,this.locale,this.pickerModel,this.isShowDay}): super(key: key);final DateChangedCallback onChanged;final _DatePickerRoute route;final LocaleType locale;final BasePickerModel pickerModel;final bool isShowDay;State<StatefulWidget> createState() {return _DatePickerState();}
}class _DatePickerState extends State<_DatePickerComponent> {FixedExtentScrollController leftScrollCtrl, middleScrollCtrl, rightScrollCtrl;void initState() {super.initState();refreshScrollOffset();}void refreshScrollOffset() {
//    print('refreshScrollOffset ${widget.pickerModel.currentRightIndex()}');leftScrollCtrl = FixedExtentScrollController(initialItem: widget.pickerModel.currentLeftIndex());middleScrollCtrl = FixedExtentScrollController(initialItem: widget.pickerModel.currentMiddleIndex());rightScrollCtrl = FixedExtentScrollController(initialItem: widget.pickerModel.currentRightIndex());}Widget build(BuildContext context) {DatePickerTheme theme = widget.route.theme;return GestureDetector(child: AnimatedBuilder(animation: widget.route.animation,builder: (BuildContext context, Widget child) {final double bottomPadding = MediaQuery.of(context).padding.bottom;return ClipRect(child: CustomSingleChildLayout(delegate: _BottomPickerLayout(widget.route.animation.value,theme,showTitleActions: widget.route.showTitleActions,bottomPadding: bottomPadding,),child: GestureDetector(child: Material(color: theme.backgroundColor ?? Colors.white,child: _renderPickerView(theme),),),),);},),);}void _notifyDateChanged() {if (widget.onChanged != null) {widget.onChanged(widget.pickerModel.finalTime());}}Widget _renderPickerView(DatePickerTheme theme) {Widget itemView = _renderItemView(theme);if (widget.route.showTitleActions) {return Column(children: <Widget>[_renderTitleActionsView(theme),itemView,],);}return itemView;}Widget _renderColumnView(ValueKey key,DatePickerTheme theme,StringAtIndexCallBack stringAtIndexCB,ScrollController scrollController,int layoutProportion,ValueChanged<int> selectedChangedWhenScrolling,ValueChanged<int> selectedChangedWhenScrollEnd,) {return Expanded(flex: layoutProportion,child: Container(padding: EdgeInsets.all(8.0),height: theme.containerHeight,decoration: BoxDecoration(color: theme.backgroundColor ?? Colors.white),child: NotificationListener(onNotification: (ScrollNotification notification) {if (notification.depth == 0 &&selectedChangedWhenScrollEnd != null &&notification is ScrollEndNotification &&notification.metrics is FixedExtentMetrics) {final FixedExtentMetrics metrics = notification.metrics;final int currentItemIndex = metrics.itemIndex;selectedChangedWhenScrollEnd(currentItemIndex);}return false;},child: CupertinoPicker.builder(key: key,backgroundColor: theme.backgroundColor ?? Colors.white,scrollController: scrollController,itemExtent: theme.itemHeight,onSelectedItemChanged: (int index) {selectedChangedWhenScrolling(index);},useMagnifier: true,itemBuilder: (BuildContext context, int index) {final content = stringAtIndexCB(index);if (content == null) {return null;}return Container(height: theme.itemHeight,alignment: Alignment.center,child: Text(content,style: theme.itemStyle,textAlign: TextAlign.start,),);},),),),);}Widget _renderItemView(DatePickerTheme theme) {return Container(color: theme.backgroundColor ?? Colors.white,child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween,children: <Widget>[Container(child: widget.pickerModel.layoutProportions()[0] > 0? _renderColumnView(ValueKey(widget.pickerModel.currentLeftIndex()),theme,widget.pickerModel.leftStringAtIndex,leftScrollCtrl,widget.pickerModel.layoutProportions()[0], (index) {widget.pickerModel.setLeftIndex(index);}, (index) {setState(() {refreshScrollOffset();_notifyDateChanged();});}): null,),Text(widget.pickerModel.leftDivider(),style: theme.itemStyle,),Container(child: widget.pickerModel.layoutProportions()[1] > 0? _renderColumnView(ValueKey(widget.pickerModel.currentLeftIndex()),theme,widget.pickerModel.middleStringAtIndex,middleScrollCtrl,widget.pickerModel.layoutProportions()[1], (index) {widget.pickerModel.setMiddleIndex(index);}, (index) {setState(() {refreshScrollOffset();_notifyDateChanged();});}): null,),Text(widget.pickerModel.rightDivider(),style: theme.itemStyle,),widget.isShowDay ?? true? Container(child: widget.pickerModel.layoutProportions()[2] > 0? _renderColumnView(ValueKey(widget.pickerModel.currentMiddleIndex() * 100 +widget.pickerModel.currentLeftIndex()),theme,widget.pickerModel.rightStringAtIndex,rightScrollCtrl,widget.pickerModel.layoutProportions()[2], (index) {widget.pickerModel.setRightIndex(index);}, (index) {setState(() {refreshScrollOffset();_notifyDateChanged();});}): null,): Container(),],),);}// Title ViewWidget _renderTitleActionsView(DatePickerTheme theme) {final done = _localeDone();final cancel = _localeCancel();return Container(height: theme.titleHeight,decoration: BoxDecoration(color: theme.headerColor ?? theme.backgroundColor ?? Colors.white,),child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween,children: <Widget>[Container(height: theme.titleHeight,child: CupertinoButton(pressedOpacity: 0.3,padding: EdgeInsets.only(left: 16, top: 0),child: Text('$cancel',style: theme.cancelStyle,),onPressed: () {Navigator.pop(context);if (widget.route.onCancel != null) {widget.route.onCancel();}},),),Container(height: theme.titleHeight,child: CupertinoButton(pressedOpacity: 0.3,padding: EdgeInsets.only(right: 16, top: 0),child: Text('$done',style: theme.doneStyle,),onPressed: () {Navigator.pop(context, widget.pickerModel.finalTime());if (widget.route.onConfirm != null) {widget.route.onConfirm(widget.pickerModel.finalTime());}},),),],),);}String _localeDone() {return i18nObjInLocale(widget.locale)['done'];}String _localeCancel() {return i18nObjInLocale(widget.locale)['cancel'];}
}class _BottomPickerLayout extends SingleChildLayoutDelegate {_BottomPickerLayout(this.progress,this.theme, {this.itemCount,this.showTitleActions,this.bottomPadding = 0,});final double progress;final int itemCount;final bool showTitleActions;final DatePickerTheme theme;final double bottomPadding;BoxConstraints getConstraintsForChild(BoxConstraints constraints) {double maxHeight = theme.containerHeight;if (showTitleActions) {maxHeight += theme.titleHeight;}return BoxConstraints(minWidth: constraints.maxWidth,maxWidth: constraints.maxWidth,minHeight: 0.0,maxHeight: maxHeight + bottomPadding,);}Offset getPositionForChild(Size size, Size childSize) {final height = size.height - childSize.height * progress;return Offset(0.0, height);}bool shouldRelayout(_BottomPickerLayout oldDelegate) {return progress != oldDelegate.progress;}
}

引用

GestureDetector(
child: Container(width:100,height:45,color:Colors.red)
onTap: (){LocaleType localeType;await ATuiSharedPreferences.getStorage("localType").then((value) {if (value == "zh") {localeType = LocaleType.zh;} else if (value == "en") {localeType = LocaleType.en;}});ATuiDateTimePicker.showDatePicker(context,isShowDay: false,locale: localeType ?? LocaleType.zh,theme: DatePickerTheme(cancelStyle: TextStyle(fontSize: 30.sp,color: Color(0xff5dc8b6),fontWeight: FontWeight.w600),doneStyle: TextStyle(fontSize: 30.sp,color: Color(0xff5dc8b6),fontWeight: FontWeight.w600)),onConfirm: (datetime) async {String newDate = '${datetime.year}-';newDate += datetime.month < 10? '0${datetime.month}': datetime.month.toString();walletListModel.changeDate(newDate);walletListModel.changeShowDate('${datetime.year}${datetime.month}月');walletListModel.refreshData();},onChanged: (datetime) {print('dateTime: ${datetime}');},);},
)

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

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

相关文章

TSINGSEE青犀视频边缘计算AI智能分析网关V4告警消息语音推送的配置流程

TSINGSEE青犀视频边缘计算硬件智能分析网关V4内置了近40种AI算法模型&#xff0c;支持对接入的视频图像进行人、车、物、行为等实时检测分析&#xff0c;上报识别结果&#xff0c;并能进行语音告警播放。今天我们来分享一下如何配置和使用AI智能分析网关V4的语音推送。 提前准备…

django中的cookie与session

获取cookie request.COOKIE.GET 使用cookie response.set-cookie views.py from django.http import HttpResponse from django.shortcuts import render# Create your views here. def cookie_test(request):r HttpResponse("hello world")r.set_cookie(lan, py…

c语言排序算法之八(桶排序)

前言 以下内容是被验证可以有效理解桶排序&#xff0c;代码也较容易理解。如果你发现还有很多需要增加的&#xff0c;欢迎留言。 为什么要单独写排序算法这一系列&#xff0c;看过一些贴子普遍篇幅较长。看完依旧难以直观理解原理及整个过程。代码永远是基于理解的基础上才能…

【刷题】前缀和进阶

送给大家一句话&#xff1a; 生活坏到一定程度就会好起来&#xff0c;因为它无法更坏。努力过后&#xff0c;才知道许多事情&#xff0c;坚持坚持&#xff0c;就过来了。 – 宫崎骏 《龙猫》 ┌(˘⌣˘)ʃ┌(˘⌣˘)ʃ┌(˘⌣˘)ʃ ┌(˘⌣˘)ʃ┌(˘⌣˘)ʃ┌(˘⌣˘)ʃ ┌(˘…

RS2105XN功能和参数介绍及PDF资料

RS2105XN 品牌: RUNIC(润石) 封装: MSOP-10 开关电路: 单刀双掷(SPDT) 通道数: 2 工作电压: 1.8V~5.5V 导通时间(Tonmax): 50ns RS2105XN是一款模拟开关芯片。以下是RS2105XN的功能和参数介绍&#xff1a; 功能&#xff1a; 2通道单刀双掷&#xff08;SPDT&#xff09;模拟开关…

基于springboot+mybatis+vue的项目实战之(后端+前后端联调)

步骤&#xff1a; 1、项目准备&#xff1a;创建数据库&#xff08;之前已经创建则忽略&#xff09;&#xff0c;以及数据库连接 2、建立项目结构文件夹 3、编写pojo文件 4、编写mapper文件&#xff0c;并测试sql语句是否正确 5、编写service文件 6、编写controller文件 …

【数据库原理及应用】期末复习汇总高校期末真题试卷09

试卷 一、填空题(每空1分&#xff0c;共10分) 数据的完整性是指数据的________、有效性和相容性。数据模型通常由________、数据操作以及数据约束条件等三要素组成。在关系的有关术语中&#xff0c;关系表中的每一行称作________&#xff0c;每一列称作属性。信息的三种世界是…

C++:多态-虚函数

C 中的多态性是面向对象编程中的一个重要概念&#xff0c;它允许在运行时选择不同的函数实现&#xff0c;以适应不同类型的对象。 多态的种类 编译时多态性&#xff08;Compile-time Polymorphism&#xff09;&#xff1a;也称为静态多态性或早期绑定&#xff0c;指在编译时确…

【网络协议】----IPv6协议报文、地址分类

【网络协议】----IPv6协议简介 【网络协议】----IPv6协议简介IPv6特点IPv4 和 IPv6报文结构IPv6报文格式-拓展报头 IPv6地址分类IPv6地址表示IPv6单播地址可聚合全球单播地址链路本地地址唯一本地地址特殊地址补充 接口标识&#xff08;主机位&#xff09;生成方法通过EUI-64规…

CISCN 2023 初赛

Web unzip 文件上传页面 upload.php页面源码显示了出来 <?php error_reporting(0); highlight_file(__FILE__);$finfo finfo_open(FILEINFO_MIME_TYPE); if (finfo_file($finfo, $_FILES["file"]["tmp_name"]) application/zip){exec(cd /tmp &am…

IP协议,网络层

一、IP协议报文 在网络层最主要的协议是IP协议&#xff0c;网络层的主要任务是进行&#xff1a;1.地址管理 2.路由选择 地址管理&#xff1a;使用一套地址体系&#xff0c;描述互联网中每个设备所处的位置。 IP地址有两个版本&#xff0c;1.IPV4 2.IPV6 &#xff0c;IP…

信奥数据“信息差”,让你惊掉下巴!

✅ 信奥红利分析 暑假信奥赛即将到来&#xff0c;在全国各地赛事也越来越受到重视&#xff0c;但是似乎关于红利这一块各地如何&#xff0c;并没有太多的老师给各位家长分析清楚。 那么今天曹老师就主要给从各位新手家长分析一下信奥红利地区&#xff0c;在开始分析之前请大家看…

使用 MediaMTX 和 FFmpeg 推拉 RTSP 流媒体

实时流传输协议 RTSP&#xff08;Real-Time Streaming Protocol&#xff09;是 TCP/IP 协议体系中的一个应用层协议&#xff0c;由哥伦比亚大学、网景和 RealNetworks 公司提交的 IETF RFC 标准。该协议定义了一对多应用程序如何有效地通过 IP 网络传送多媒体数据。RTSP 在体系…

初始化创建一个webpack项目

新建一个空的工程 -> % mkdir webpack-project 为了方便追踪执行每一个命令&#xff0c;最终产生了哪些变更&#xff0c;将这个空工程初始化成git项目 -> % cd webpack-project/-> % git init Initialized empty Git repository in /Users/lixiang/frontworkspace/…

初探MFC程序混合使用QT

一、背景 随着操作系统国产化替代的趋势越发明显&#xff0c;软件支持国际化、跨平台&#xff0c;已然是必须做的一件事情。原有的软件UI层用的是MFC&#xff0c;将其换成QT&#xff0c;想必是一种较好的方案。对于大型软件&#xff0c;特别是已发布&#xff0c;但还处于不断迭…

C++进阶之路:探索访问限定符、封装与this指针的奥秘(类与对象_上篇)

✨✨ 欢迎大家来访Srlua的博文&#xff08;づ&#xffe3;3&#xffe3;&#xff09;づ╭❤&#xff5e;✨✨ &#x1f31f;&#x1f31f; 欢迎各位亲爱的读者&#xff0c;感谢你们抽出宝贵的时间来阅读我的文章。 我是Srlua小谢&#xff0c;在这里我会分享我的知识和经验。&am…

数据统计:词频统计、词表生成、排序及计数、词云图生成

文章目录 &#x1f4da;输入及输出&#x1f4da;代码实现 &#x1f4da;输入及输出 输入&#xff1a;读取一个input.txt&#xff0c;其中包含单词及其对应的TED打卡号。 输出 output.txt&#xff1a;包含按频率降序排列的每个单词及其计数&#xff08;这里直接用于后续的词云…

设计模式之单例模式详解

单例模式 描述&#xff1a;单例&#xff08;Singleton&#xff09;模式的定义&#xff1a;指一个类只有一个实例&#xff0c;且该类能自行创建这个实例的一种模式。 核心特点 单例类只有一个实例对象&#xff1b;该单例对象必须由单例类自行创建&#xff1b;单例类对外提供一…

OpenCV 入门(一) —— OpenCV 基础

OpenCV 入门系列&#xff1a; OpenCV 入门&#xff08;一&#xff09;—— OpenCV 基础 OpenCV 入门&#xff08;二&#xff09;—— 车牌定位 OpenCV 入门&#xff08;三&#xff09;—— 车牌筛选 OpenCV 入门&#xff08;四&#xff09;—— 车牌号识别 OpenCV 入门&#xf…

每日两题 / 23. 合并 K 个升序链表 94. 二叉树的中序遍历(LeetCode热题100)

23. 合并 K 个升序链表 - 力扣&#xff08;LeetCode&#xff09; 若lists有k个元素&#xff0c;调用k - 1次&#xff08;两个有序链表的合并&#xff09;即可 /*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNod…