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】webのlocalStorageをshared_preferencesを通して使用する

Posted at

概要

webでブラウザに何か保存する際に、localStorageを使用すると思いますが、Flutter Webの場合にどう実装するかのメモ書きです。
How to save to web local storage in flutter webのstackoverflowの記事に、色々と対応案が書いてあります。shared_preferencesという端末にデータ保存するライブラリが、バージョン0.5.4.7以降ではlocalStorageに対応しているようなので、今回これを使用してみます。

前提

  • Flutterのバージョンは3.3.10を使用します。
  • shared_preferencesのバージョンは2.0.17を使用します。

実装サンプル

shared_preferencesのライブラリのページに記載ある通りですが、アプリでの実装と同じ形式で以下のようにlocalStorageを使用できます。

import 'package:shared_preferences/shared_preferences.dart';

class LocalStorageManagementService {
  static const String localStorageKey = "localStorageKey";

  static Future<void> setLocalStorage(String value) async {
    final localStorage = await SharedPreferences.getInstance();
    localStorage.setString(localStorageKey, value);
  }

  static Future<String?> getAuthTokenLocalStorage() async {
    final localStorage = await SharedPreferences.getInstance();
    return localStorage.getString(localStorageKey);
  }

  static Future<void> removeAuthTokenLocalStorage() async {
    final localStorage = await SharedPreferences.getInstance();
    localStorage.remove(localStorageKey);
  }
}
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?