0
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 1 year has passed since last update.

FlutterでRiverpodとSharedPreferencesを使ってAppBarの色を設定・保存する

Posted at

この記事を書こうと思ったきっかけ

・Flutterの自己学習でRiverpodとSharedPreferencesを使ってみたいと思った。
・サンプルだとカウンターアプリが多いので別のアプリを作ってみたいと思った。

前提条件

下記バージョンを使用しております
flutter_riverpod: ^2.3.1
shared_preferences: ^2.0.18

1.ファイルの作成

今回は簡単なアプリの作成にしたいため
使用ファイルはデフォルトで作成されている「main.dart」と新たに作成した
「set_color.dart」と「set_color_viewmodel」を使用していきます。

2.set_color_viewmodel内にカラーの設定、保存を行うクラスを作成

今回のアプリでは保存やタスクキルから起動時に値を取得等の処理があるため
StateNotifierProviderを使用していきます。
詳細は下記添付しておりますコードにコメントで記載しておきます。

/// SharedPreferences で使用するカラー保存用のキー
const _colorPrefsKey = 'selectedColorKey';

///StateNotifierProviderにsetColorViewModelを設定
final setColorViewModel = StateNotifierProvider<SetColorViewModel, Color>(
    (ref) => SetColorViewModel());

///クラスを定義(初期値の色は0xffee0000とする)
class SetColorViewModel extends StateNotifier<Color> {
  SetColorViewModel() : super(const Color(0xffee0000)) {
    readColor();
  }

  ///sharedPreferencesをインスタンスを取得
  Future<SharedPreferences> getInstance() async {
    return await SharedPreferences.getInstance();
  }

  ///appbarに色を設定するメソッド
  void setSelectColor(Color color) async {
    state = color;
    //sharedPreferencesをインスタンス化
    SharedPreferences _sharedPreferences = await getInstance();
    //sharedPreferenceにcolorを入れる
    _sharedPreferences.setString(_colorPrefsKey, color.toString());
  }

  ///タスクキルした際のSharedPreferenceの色を読む
  void readColor() async {
    //sharedPreferencesをインスタンス化
    SharedPreferences _sharedPreferences = await getInstance();
    //_colorPrefsKeyに保存されている値を取得
    var result = _sharedPreferences.getString(_colorPrefsKey) ?? "";
    if (result.isEmpty) return;
    //colorの0xがあると読み込めないためresultからとってきた値から取り除く
    try {
      Color color =
          Color(int.parse(result.split('(0x')[1].split(')')[0], radix: 16));
      state = color;
      // エラーの場合は'error'とprintする
    } catch (e, s) {
      print('error');
    }
  }
}

3.set_color.dartに設定した色を反映させる

class setColor extends ConsumerWidget {
   setColor({Key? key}) : super(key: key);

///選択できる色のリストを作成
  var colorList = [const Color(0xffee0000), const Color(0xffFFB831), const Color(0xff33ADEE)];

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    // 選択したカラーを呼び出す
    var color = ref.watch(setColorViewModel);
    return Scaffold(
      resizeToAvoidBottomInset: true,
      appBar: AppBar(backgroundColor: color,
        title: const Text('テーマカラー設定'),
      ),
      body: ListView.builder(
          itemCount: colorList.length,
          itemBuilder:(context,index) {
            var backgroundColor = colorList[index];
            return GestureDetector(
              onTap: () {
                // コンテナーをタップしてカラーを選択する
                ref.read(setColorViewModel.notifier).setSelectColor(backgroundColor);
              },
              child:Container(
                width: 200,
                height: 200,
                decoration:  BoxDecoration(
                  shape: BoxShape.circle,
                  color: colorList[index],
                ),
              ),
            );
          }
      )
    );
  }
}

まとめ

まだまだRiverpod使い慣れない中で作成しまたしたが、
アプリの一つの機能として簡単に実装できるので参考になれば幸いです。
また誤りや修正案等あれば教えて頂けますと幸いです。

0
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
0
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?