2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Flutter】TimeOfDay型をshared_preferencesで保存する

Posted at

はじめに

最近、FlutterでTimeOfDay型の値を保存するのに苦労して、日本語の記事もあんまり見かけなかったので記事にします!
ちなみにtimePickerで選んだ時刻を保存するのに使いました。

手順1 TimeOfDay型をString型で保存する

現時点でshared_preferencesで標準で保存できる方は以下の五つ
 ・int
 ・double
 ・string
 ・bool
 ・list
となっておりTimeOfDay型を保存するにはひと工夫しないといけません。

そこでまず、TimeOfDay型の値をString型に変換します。
String型からTimeOfDay型に直接変換できないため、StringDateTimeみたいなフォーマットのString型TimeOfDayというふうに変換していきます。

TimeOfDay型をString型に変換したものをDateTime型っぽいString型に変換するんですが、TimeOfDay型は時と分を持っていて、DateTime型は年、月、日を持っているため少し工夫します。

store_TimeOfDay.dart
//変換の際に使うDATETIME型やつ
  DateTime now = DateTime.now();

  //タイムピッカーデフォルトの変数
  TimeOfDay _selectedTime = TimeOfDay(hour: 10, minute: 00);

  // String型を保存する関数を用意
  _saveTime(String key, String value) async {
    var prefs = await SharedPreferences.getInstance();
    prefs.setString(key, value);
  }

  ------------------------------------------------------

if (取得した値 != null) {
        setState(() {
          _selectedTime = 取得した値;
          _saveTime('time',  DateTime(
            now.year,//DateTime
            now.month,//DateTime
            now.day,//DateTime
            _selectedTime.hour, // TimeOfDay
            _selectedTime.minute, //TimeOfDay
          ).toString());
          // これで 2022-06-22 10:00:00.000 こんな感じになる
        });
      }

手順2 保存したStringの値取得する際にTimeOfDayに変換する

store_TimeOfDay.dart
_restoreValues() async {
    var prefs = await SharedPreferences.getInstance();

    setState(() {
      //保存した`String`型の値を新しい変数に入れる
      String stringTimeData = prefs.getString('time') ?? "2022-06-22 10:00:00.000";
      //上のstringTimeDataをTimeOfDay型に変換する
      _selectedTime = TimeOfDay.fromDateTime(
          DateTime.parse(stringTimeData));
    });
  }

void initState() {
    super.initState();
    _restoreValues(); //次回のget
  }

おまけ

timePickerで選択させた時刻をテキストで表示させる場合(例)↓

時刻表示.dart

String timeText = ''; //時刻表示につかうString型の変数

//選択した時刻のテキスト
    String _getTimeText() {
      if (_selectedTime == null) {
        return '10:00';
      } else {
        var hours = _selectedTime.hour.toString();
        var minutes = _selectedTime.minute.toString().padLeft(2, '0');

        if (hours == '12') {
          hours = '24';
        }

        if (hours == '0') {
          hours = '12';
        }

        timeText = '$hours : $minutes';


        return timeText;
      }
    }

timePickerのinitialTimeにselectedTime.hour,_selectedTime.minuteを指定すると前回選択した時刻から時刻の選択をさせることもできますね

お疲れ様でした。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?