🚀

flutter_datetime_pickerで年月のみにする方法

2023/01/14に公開

初めに

簡単にドラムロール形式の日付選択を実装することができるflutter_datetime_pickerですが、デフォルトのまま利用すると「年月日」は実装できますが、「年月」のみを表示し選択可能にすることができません。
今回は、「年月」のみを実装する方法を記述します。

実装方法

flutter_datetime_pickerをカスタマイズする為のpickerModelというオプションが用意されているので、そこに独自に作成したModelを設定することで、カスタマイズする事ができます。

Modelを用意する

コピペでokです

import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';

class YearMonthModel extends DatePickerModel {
  YearMonthModel({required DateTime currentTime,required DateTime minTime,required DateTime maxTime,
   required LocaleType locale}) : super(locale: locale, minTime: minTime, maxTime:
  maxTime, currentTime: currentTime);

  @override
  List<int> layoutProportions() {
    return [1, 1, 0];
  }
}

pickerModelにModelを登録

先ほど実装したModelをpickerModelで利用するだけです!

await DatePicker.showPicker(context, showTitleActions: true,
  pickerModel: YearMonthModel(
    currentTime: DateTime.now(),
    minTime: DateTime(2022, 1, 1),
    maxTime: DateTime.now(),
    locale: LocaleType.jp),
  locale: LocaleType.en,
  onConfirm: (date) {},
);

[参考]

公式サンプルコード
https://stackoverflow.com/questions/53749248/flutter-datepicker-without-day-using-futuredatetime-showdatepicker-plugin-r
https://github.com/Realank/flutter_datetime_picker/issues/80

Discussion