[Flutter]CupertinoDatePickerをポップアップ表示するには?

Flutter

どうも、ちょげ(@chogetarou)です。

iOSでは、DatePickerを下から表示するポップアップ表示が出来ます。

同じようにCupertinoDatePickerをポップアップ表示するには、どうしたらいいのでしょうか?

スポンサーリンク

方法

インターフェース, インターネット, プログラム, ブラウザ, Www

まず、「Cupertino」パッケージをインポートします。

import 'package:flutter/cupertino.dart';

次に、CupertinoDatePickerをポップアップ表示するための関数を用意します。

//選んだ日付を格納する変数 
var selectDate = DateTime.now();

    void _showDatePicker(context) {
//ポップアップ表示する
    showCupertinoModalPopup(
        context: context,
        builder: (_) => Container(
              height: 500,
              child: Column(
                children: [
                  Container(
                    height: 400,
                  color: Color.fromARGB(255, 255, 255, 255),
                    child: CupertinoDatePicker(
                        initialDateTime: DateTime.now(),
                        onDateTimeChanged: (val) {
                          setState(() {
                            //値の更新
                            selectDate = val;
                          });
                        }),
                  ),

                  //ポップアップを閉じる
                  CupertinoButton(
                    child: Text('OK'),
                    onPressed: () => Navigator.of(context).pop(),
                  )
                ],
              ),
            ));
  }

「showCupertinoModalPopup」関数を使うことによって,iOSのようなポップアップ表示をすることが出来ます。

この関数の引数「builder」で、CupertinoDatePickerを使えば、ポップアップ表示が出来るようになります。

ポップアップ表示するContainerウェジェットでは、色に「白」を指定しています。

showCupertinoModalPopup関数で、表示するウェジェットに色を指定しておかないと、スケスケになります。

あとは、ボタンやスワイプのトリガーで、この関数を呼び出してあげるだけです。

  @override
  Widget build(BuildContext context) {
    return Center(
      child: TextButton(
        onPressed: () {
          _showDatePicker(context);
        },
        child: const Text('Pick Date'),
      ),
    );
  }

コメント

タイトルとURLをコピーしました