如何在Flutter Web中保存到Web本地存储

ikb*_*ben 8 dart flutter flutter-web

我有一个使用flutter构建的网站,目前正在尝试保存到Web本地存储或cookie,但似乎找不到任何插件或归档方式。

Aar*_*ing 15

我遇到了类似的问题,我的偏好在运行过程中没有得到保留。我以为window.localStorage坏了。我发现 Flutter每次默认都会使用新的端口号window.localStorage启动,因此被淘汰了。

这张票讨论了设置显式端口。这解决了我的问题,现在window.localStorage在运行中仍然存在:

https://github.com/Dart-Code/Dart-Code/issues/1769

在 VS Code 中,您可以在文件中设置端口号launch.json

{
    "name": "Flutter",
    "request": "launch",
    "type": "dart",
    "args": ["--web-port", "8686"]
},
Run Code Online (Sandbox Code Playgroud)


小智 13

shared_preferences0.5.4.7+版本开始, dart 包现在支持 Web 的本地存储

类似于Android和iOS上的共享首选项,以下是Web本地存储的代码片段

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart'; // rememeber to import shared_preferences: ^0.5.4+8


void main() {
  runApp(MaterialApp(
    home: Scaffold(
      body: Center(
      child: RaisedButton(
        onPressed: _incrementCounter,
        child: Text('Increment Counter'),
        ),
      ),
    ),
  ));
}

_incrementCounter() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  int counter = (prefs.getInt('counter') ?? 0) + 1;
  print('Pressed $counter times.');
  await prefs.setInt('counter', counter);
}
Run Code Online (Sandbox Code Playgroud)


Dar*_*ski 8

您可以使用window.localStoragedart:html

import 'dart:html';

class IdRepository {
  final Storage _localStorage = window.localStorage;

  Future save(String id) async {
    _localStorage['selected_id'] = id;
  }

  Future<String> getId() async => _localStorage['selected_id'];

  Future invalidate() async {
    _localStorage.remove('selected_id');
  }
}
Run Code Online (Sandbox Code Playgroud)


Dha*_*dav 6

我正在使用shared_preferences包将数据存储在本地存储上

class SessionManager {
  static SessionManager manager;
  static SharedPreferences _prefs;

  static Future<SessionManager> getInstance() async {
    if (manager == null || _prefs == null) {
      manager = SessionManager();
      _prefs = await SharedPreferences.getInstance();
    }
    return manager;
  }

  void putCityId(String cityId) {
    _prefs.setString("KEY_CITY_ID", cityId);
  }

  String getCityId() {
    return _prefs.getString("KEY_CITY_ID") ?? "";
  }
}
Run Code Online (Sandbox Code Playgroud)

shared_preferences 仅存储当前会话的数据。

如果你想永久存储数据,那么你应该使用cookie来存储数据。

   import 'dart:html';
      
   class CookieManager {
      static CookieManager _manager;
    
      static getInstance() {
        if (_manager == null) {
          _manager = CookieManager();
        }
        return _manager;
      }
    
      void _addToCookie(String key, String value) {
        // 2592000 sec = 30 days.
        document.cookie = "$key=$value; max-age=2592000; path=/;";
      }
    
      String _getCookie(String key) {
        String cookies = document.cookie;
        List<String> listValues = cookies.isNotEmpty ? cookies.split(";") : List();
        String matchVal = "";
        for (int i = 0; i < listValues.length; i++) {
          List<String> map = listValues[i].split("=");
          String _key = map[0].trim();
          String _val = map[1].trim();
          if (key == _key) {
            matchVal = _val;
            break;
          }
        }
        return matchVal;
      }
    }
Run Code Online (Sandbox Code Playgroud)


Spa*_*atz 5

flutter 1.10我们可以使用universal_html包:

import 'package:universal_html/prefer_universal/html.dart';
// ...
// read preference
var myPref = window.localStorage['mypref'];
// ...
// write preference
window.localStorage['mypref'] = myPref;

Run Code Online (Sandbox Code Playgroud)