
今回もFlutterのプログラム解説をしていこうと思います!

今回は、端末に入力した内容を保存できるようにしてみたわ

ドラムロールで行えるようにしてみたぞ

もくじ
解説動画もあるよ!

こちらを見ていただけると嬉しいです!

内容自体はあまり進んでないわね

このアプリ制作は前座のつもりだったから1回で終えるはずだったんだけどね

どうしても時間がかかってしまったというわけですね
Githubにプロジェクトをアップロードしてます!
Githubのプロジェクトリンク:https://github.com/Syungetu/text_editor

ソースを見せろ!といった方はGithubにプロジェクトファイルを上げてますのでご確認ください~



動画について補足的解説をします




端末にデータを保存する



https://github.com/Syungetu/text_editor/blob/main/lib/page/memo_page.dart

データを端末に保存する

インポートはごく普通な感じですね
SharedPreferences prefs = await SharedPreferences.getInstance();
// titleという項目に文字列データを保存する
prefs.setString(‘title’, titleTextEditingController.text);
// contentsという項目に文字列データを保存する
prefs.setString(‘contents’, contentsTextEditingController.text);

今回はテキストデータを保存するものになるわね
// インスタンス取得
SharedPreferences prefs = await SharedPreferences.getInstance();

データをやり取りするときは必ずSharedPreferences.getInstance();を呼び出す必要があるぞ

// titleという項目に文字列データを保存する
prefs.setString(‘title’, titleTextEditingController.text);


保存する「setString()」関数の第一引数は項目名を指定するわ


今回は文字列を入力しています
prefs.setInt(‘hogehoge’, title1); → int型で保存
prefs.setDouble(‘hogehoge’, title1.0001); → double型で保存
prefs.setBool(‘hogehoge’, title true); → bool型で保存
prefs.setString(‘hogehoge’, title “hagehage”); → String型で保存
prefs.getStringList(‘hogehoge’, title [“aaa”, “bbb”, “ccc”]); → String型のリストで保存

第二引数に入れるデータは関数ごとに分かれてます

保存したデータの読み込み
// インスタンス取得
SharedPreferences prefs = await SharedPreferences.getInstance();
// titleという項目に保存した文字列データを読み込む
String? titleText = prefs.getString(‘title’);
if (titleText != null) {
titleTextEditingController.text = titleText;
}
// contentsという項目に保存した文字列データを読み込む
String? contentsText = prefs.getString(‘contents’);
if (contentsText != null) {
contentsTextEditingController.text = contentsText;
}

こちらも同じ様な処理で出来るからわかりやすいな
// インスタンス取得
SharedPreferences prefs = await SharedPreferences.getInstance();

保存時と同じようにインスタンスが生成されるまで待ちます
// titleという項目に保存した文字列データを読み込む
String? titleText = prefs.getString(‘title’);
if (titleText != null) {
titleTextEditingController.text = titleText;
}



保存されてないものを呼び出そうとするとnullが返されるぞ

ドラムロールの選択ウィジェットを追加する

パッケージを追加する

まずはドラムロールが出来るFlutter Datetime Pickerを追加するわ


ドラムロールを追加する
import ‘package:flutter_datetime_picker/flutter_datetime_picker.dart’;
import ‘package:timezone/data/latest.dart’ as tz;
import ‘package:timezone/timezone.dart’ as tz;

先程追加した2つのパッケージを追加した感じですね



そのため別名で飛び出すことでエラーを回避する事ができます
// 通知日付設定を行う
await DatePicker.showDateTimePicker(
context,
showTitleActions: true,
locale: LocaleType.jp,
currentTime: DateTime.now(),
// ピッカーを動かしたときに呼ばれる
onChanged: (time) {},
// 日付設定が完了したときに呼ばれる
onConfirm: (time) {
setSheetState(() {
selectDateTime = time;
});
},
);

「 DatePicker.showDateTimePicker()」がドラムロールを呼び出す処理となります



次回はローカル通知の解説です



