flutter_datetime_picker.dart 14 KB

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