flutter_datetime_picker.dart 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. library flutter_datetime_picker;
  2. import 'package:flutter/cupertino.dart';
  3. import 'package:flutter/material.dart';
  4. import 'package:flutter_datetime_picker/src/datetime_picker_theme.dart';
  5. import 'package:flutter_datetime_picker/src/date_model.dart';
  6. import 'package:flutter_datetime_picker/src/i18n_model.dart';
  7. export 'package:flutter_datetime_picker/src/datetime_picker_theme.dart';
  8. export 'package:flutter_datetime_picker/src/date_model.dart';
  9. export 'package:flutter_datetime_picker/src/i18n_model.dart';
  10. typedef DateChangedCallback(DateTime time);
  11. typedef String StringAtIndexCallBack(int index);
  12. class DatePicker {
  13. ///
  14. /// Display date picker bottom sheet.
  15. ///
  16. static Future showDatePicker(
  17. BuildContext context, {
  18. bool showTitleActions: true,
  19. DateTime minTime,
  20. DateTime maxTime,
  21. DateChangedCallback onChanged,
  22. DateChangedCallback onConfirm,
  23. locale: LocaleType.en,
  24. DateTime currentTime,
  25. DatePickerTheme theme,
  26. }) {
  27. return Navigator.push(
  28. context,
  29. new _DatePickerRoute(
  30. showTitleActions: showTitleActions,
  31. onChanged: onChanged,
  32. onConfirm: onConfirm,
  33. locale: locale,
  34. theme: theme,
  35. barrierLabel: MaterialLocalizations.of(context).modalBarrierDismissLabel,
  36. pickerModel: DatePickerModel(
  37. currentTime: currentTime, maxTime: maxTime, minTime: minTime, locale: locale)));
  38. }
  39. ///
  40. /// Display time picker bottom sheet.
  41. ///
  42. static Future showTimePicker(
  43. BuildContext context, {
  44. bool showTitleActions: true,
  45. DateChangedCallback onChanged,
  46. DateChangedCallback onConfirm,
  47. locale: LocaleType.en,
  48. DateTime currentTime,
  49. DatePickerTheme theme,
  50. }) {
  51. return Navigator.push(
  52. context,
  53. new _DatePickerRoute(
  54. showTitleActions: showTitleActions,
  55. onChanged: onChanged,
  56. onConfirm: onConfirm,
  57. locale: locale,
  58. theme: theme,
  59. barrierLabel: MaterialLocalizations.of(context).modalBarrierDismissLabel,
  60. pickerModel: TimePickerModel(currentTime: currentTime, locale: locale)));
  61. }
  62. ///
  63. /// Display date&time picker bottom sheet.
  64. ///
  65. static Future showDateTimePicker(
  66. BuildContext context, {
  67. bool showTitleActions: true,
  68. DateTime minTime,
  69. DateTime maxTime,
  70. DateChangedCallback onChanged,
  71. DateChangedCallback onConfirm,
  72. locale: LocaleType.en,
  73. DateTime currentTime,
  74. DatePickerTheme theme,
  75. }) {
  76. return Navigator.push(
  77. context,
  78. new _DatePickerRoute(
  79. showTitleActions: showTitleActions,
  80. onChanged: onChanged,
  81. onConfirm: onConfirm,
  82. locale: locale,
  83. theme: theme,
  84. barrierLabel: MaterialLocalizations.of(context).modalBarrierDismissLabel,
  85. pickerModel: DateTimePickerModel(
  86. currentTime: currentTime, minTime: minTime, maxTime: maxTime, locale: locale)));
  87. }
  88. ///
  89. /// Display date picker bottom sheet witch custom picker model.
  90. ///
  91. static Future showPicker(
  92. BuildContext context, {
  93. bool showTitleActions: true,
  94. DateChangedCallback onChanged,
  95. DateChangedCallback onConfirm,
  96. locale: LocaleType.en,
  97. BasePickerModel pickerModel,
  98. DatePickerTheme theme,
  99. }) {
  100. return Navigator.push(
  101. context,
  102. new _DatePickerRoute(
  103. showTitleActions: showTitleActions,
  104. onChanged: onChanged,
  105. onConfirm: onConfirm,
  106. locale: locale,
  107. theme: theme,
  108. barrierLabel: MaterialLocalizations.of(context).modalBarrierDismissLabel,
  109. pickerModel: pickerModel));
  110. }
  111. }
  112. class _DatePickerRoute<T> extends PopupRoute<T> {
  113. _DatePickerRoute({
  114. this.showTitleActions,
  115. this.onChanged,
  116. this.onConfirm,
  117. theme,
  118. this.barrierLabel,
  119. this.locale,
  120. RouteSettings settings,
  121. pickerModel,
  122. }) : this.pickerModel = pickerModel ?? DatePickerModel(),
  123. this.theme = theme ?? DatePickerTheme(),
  124. super(settings: settings);
  125. final bool showTitleActions;
  126. final DateChangedCallback onChanged;
  127. final DateChangedCallback onConfirm;
  128. final DatePickerTheme theme;
  129. final LocaleType locale;
  130. final BasePickerModel pickerModel;
  131. @override
  132. Duration get transitionDuration => const Duration(milliseconds: 200);
  133. @override
  134. bool get barrierDismissible => true;
  135. @override
  136. final String barrierLabel;
  137. @override
  138. Color get barrierColor => Colors.black54;
  139. AnimationController _animationController;
  140. @override
  141. AnimationController createAnimationController() {
  142. assert(_animationController == null);
  143. _animationController = BottomSheet.createAnimationController(navigator.overlay);
  144. return _animationController;
  145. }
  146. @override
  147. Widget buildPage(
  148. BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) {
  149. Widget bottomSheet = new MediaQuery.removePadding(
  150. context: context,
  151. removeTop: true,
  152. child: _DatePickerComponent(
  153. onChanged: onChanged,
  154. locale: this.locale,
  155. route: this,
  156. pickerModel: pickerModel,
  157. ),
  158. );
  159. ThemeData inheritTheme = Theme.of(context, shadowThemeOnly: true);
  160. if (inheritTheme != null) {
  161. bottomSheet = new Theme(data: inheritTheme, child: bottomSheet);
  162. }
  163. return bottomSheet;
  164. }
  165. }
  166. class _DatePickerComponent extends StatefulWidget {
  167. _DatePickerComponent(
  168. {Key key, @required this.route, this.onChanged, this.locale, this.pickerModel});
  169. final DateChangedCallback onChanged;
  170. final _DatePickerRoute route;
  171. final LocaleType locale;
  172. final BasePickerModel pickerModel;
  173. @override
  174. State<StatefulWidget> createState() {
  175. return _DatePickerState();
  176. }
  177. }
  178. class _DatePickerState extends State<_DatePickerComponent> {
  179. FixedExtentScrollController leftScrollCtrl, middleScrollCtrl, rightScrollCtrl;
  180. @override
  181. void initState() {
  182. super.initState();
  183. refreshScrollOffset();
  184. }
  185. void refreshScrollOffset() {
  186. leftScrollCtrl =
  187. new FixedExtentScrollController(initialItem: widget.pickerModel.currentLeftIndex());
  188. middleScrollCtrl =
  189. new FixedExtentScrollController(initialItem: widget.pickerModel.currentMiddleIndex());
  190. rightScrollCtrl =
  191. new FixedExtentScrollController(initialItem: widget.pickerModel.currentRightIndex());
  192. }
  193. @override
  194. Widget build(BuildContext context) {
  195. DatePickerTheme theme = widget.route.theme;
  196. return new GestureDetector(
  197. child: new AnimatedBuilder(
  198. animation: widget.route.animation,
  199. builder: (BuildContext context, Widget child) {
  200. return new ClipRect(
  201. child: new CustomSingleChildLayout(
  202. delegate: new _BottomPickerLayout(widget.route.animation.value, theme,
  203. showTitleActions: widget.route.showTitleActions),
  204. child: new GestureDetector(
  205. child: Material(
  206. color: Colors.transparent,
  207. child: _renderPickerView(theme),
  208. ),
  209. ),
  210. ),
  211. );
  212. },
  213. ),
  214. );
  215. }
  216. void _notifyDateChanged() {
  217. if (widget.onChanged != null) {
  218. widget.onChanged(widget.pickerModel.finalTime());
  219. }
  220. }
  221. Widget _renderPickerView(DatePickerTheme theme) {
  222. Widget itemView = _renderItemView(theme);
  223. if (widget.route.showTitleActions) {
  224. return Column(
  225. children: <Widget>[
  226. _renderTitleActionsView(theme),
  227. itemView,
  228. ],
  229. );
  230. }
  231. return itemView;
  232. }
  233. Widget _renderColumnView(
  234. ValueKey key,
  235. DatePickerTheme theme,
  236. StringAtIndexCallBack stringAtIndexCB,
  237. ScrollController scrollController,
  238. int layoutProportion,
  239. ValueChanged<int> selectedChangedWhenScrolling,
  240. ValueChanged<int> selectedChangedWhenScrollEnd) {
  241. return Expanded(
  242. flex: layoutProportion,
  243. child: Container(
  244. padding: EdgeInsets.all(8.0),
  245. height: theme.containerHeight,
  246. decoration: BoxDecoration(color: theme.backgroundColor ?? Colors.white),
  247. child: NotificationListener(
  248. onNotification: (ScrollNotification notification) {
  249. if (notification.depth == 0 &&
  250. selectedChangedWhenScrollEnd != null &&
  251. notification is ScrollEndNotification &&
  252. notification.metrics is FixedExtentMetrics) {
  253. final FixedExtentMetrics metrics = notification.metrics;
  254. final int currentItemIndex = metrics.itemIndex;
  255. selectedChangedWhenScrollEnd(currentItemIndex);
  256. }
  257. return false;
  258. },
  259. child: CupertinoPicker.builder(
  260. key: key,
  261. backgroundColor: theme.backgroundColor ?? Colors.white,
  262. scrollController: scrollController,
  263. itemExtent: theme.itemHeight,
  264. onSelectedItemChanged: (int index) {
  265. selectedChangedWhenScrolling(index);
  266. },
  267. useMagnifier: true,
  268. itemBuilder: (BuildContext context, int index) {
  269. final content = stringAtIndexCB(index);
  270. if (content == null) {
  271. return null;
  272. }
  273. return Container(
  274. height: theme.itemHeight,
  275. alignment: Alignment.center,
  276. child: Text(
  277. content,
  278. style: theme.itemStyle,
  279. textAlign: TextAlign.start,
  280. ),
  281. );
  282. }))),
  283. );
  284. }
  285. Widget _renderItemView(DatePickerTheme theme) {
  286. return Container(
  287. color: theme.backgroundColor ?? Colors.white,
  288. child: Row(
  289. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  290. children: <Widget>[
  291. _renderColumnView(
  292. ValueKey(widget.pickerModel.currentLeftIndex()),
  293. theme,
  294. widget.pickerModel.leftStringAtIndex,
  295. leftScrollCtrl,
  296. widget.pickerModel.layoutProportions()[0], (index) {
  297. widget.pickerModel.setLeftIndex(index);
  298. }, (index) {
  299. setState(() {
  300. refreshScrollOffset();
  301. _notifyDateChanged();
  302. });
  303. }),
  304. Text(
  305. widget.pickerModel.leftDivider(),
  306. style: theme.itemStyle,
  307. ),
  308. _renderColumnView(
  309. ValueKey(widget.pickerModel.currentLeftIndex()),
  310. theme,
  311. widget.pickerModel.middleStringAtIndex,
  312. middleScrollCtrl,
  313. widget.pickerModel.layoutProportions()[1], (index) {
  314. widget.pickerModel.setMiddleIndex(index);
  315. }, (index) {
  316. setState(() {
  317. refreshScrollOffset();
  318. _notifyDateChanged();
  319. });
  320. }),
  321. Text(
  322. widget.pickerModel.rightDivider(),
  323. style: theme.itemStyle,
  324. ),
  325. _renderColumnView(
  326. ValueKey(
  327. widget.pickerModel.currentMiddleIndex() + widget.pickerModel.currentLeftIndex()),
  328. theme,
  329. widget.pickerModel.rightStringAtIndex,
  330. rightScrollCtrl,
  331. widget.pickerModel.layoutProportions()[2], (index) {
  332. widget.pickerModel.setRightIndex(index);
  333. _notifyDateChanged();
  334. }, null),
  335. ],
  336. ),
  337. );
  338. }
  339. // Title View
  340. Widget _renderTitleActionsView(DatePickerTheme theme) {
  341. String done = _localeDone();
  342. String cancel = _localeCancel();
  343. return Container(
  344. height: theme.titleHeight,
  345. decoration: BoxDecoration(color: theme.backgroundColor ?? Colors.white),
  346. child: Row(
  347. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  348. children: <Widget>[
  349. Container(
  350. height: theme.titleHeight,
  351. child: CupertinoButton(
  352. pressedOpacity: 0.3,
  353. padding: EdgeInsets.only(left: 16, top: 0),
  354. child: Text(
  355. '$cancel',
  356. style: theme.cancelStyle,
  357. ),
  358. onPressed: () => Navigator.pop(context),
  359. ),
  360. ),
  361. Container(
  362. height: theme.titleHeight,
  363. child: CupertinoButton(
  364. pressedOpacity: 0.3,
  365. padding: EdgeInsets.only(right: 16, top: 0),
  366. child: Text(
  367. '$done',
  368. style: theme.doneStyle,
  369. ),
  370. onPressed: () {
  371. Navigator.pop(context);
  372. if (widget.route.onConfirm != null) {
  373. widget.route.onConfirm(widget.pickerModel.finalTime());
  374. }
  375. },
  376. ),
  377. ),
  378. ],
  379. ),
  380. );
  381. }
  382. String _localeDone() {
  383. return i18nObjInLocale(widget.locale)['done'];
  384. }
  385. String _localeCancel() {
  386. return i18nObjInLocale(widget.locale)['cancel'];
  387. }
  388. }
  389. class _BottomPickerLayout extends SingleChildLayoutDelegate {
  390. _BottomPickerLayout(this.progress, this.theme, {this.itemCount, this.showTitleActions});
  391. final double progress;
  392. final int itemCount;
  393. final bool showTitleActions;
  394. final DatePickerTheme theme;
  395. @override
  396. BoxConstraints getConstraintsForChild(BoxConstraints constraints) {
  397. double maxHeight = theme.containerHeight;
  398. if (showTitleActions) {
  399. maxHeight += theme.titleHeight;
  400. }
  401. return new BoxConstraints(
  402. minWidth: constraints.maxWidth,
  403. maxWidth: constraints.maxWidth,
  404. minHeight: 0.0,
  405. maxHeight: maxHeight);
  406. }
  407. @override
  408. Offset getPositionForChild(Size size, Size childSize) {
  409. double height = size.height - childSize.height * progress;
  410. return new Offset(0.0, height);
  411. }
  412. @override
  413. bool shouldRelayout(_BottomPickerLayout oldDelegate) {
  414. return progress != oldDelegate.progress;
  415. }
  416. }