34

I have a web site built with flutter for web and currently, am trying to save to web local storage or cookie but can't seem to find any plugin or way to archive that.

ikben
  • 4,246
  • 4
  • 21
  • 27

6 Answers6

27

You can use window.localStorage from dart: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');
  }
}
Dariusz Bacinski
  • 8,324
  • 9
  • 38
  • 47
  • 1
    @dazza5000 No this does not work on flutter 1.9 check it yourself you will see that it does not – ikben Oct 16 '19 at 10:38
18

shared_preferences dart package now supports local storage for the web from version 0.5.4.7+

Similar to shared preference on Android and iOS, the following is the code snippet for local storage on 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);
}
slamarseillebg
  • 306
  • 2
  • 6
12

I ran into a similar issue where my preferences weren't being persisted across runs. I thought window.localStorage was broken. I discovered that Flutter was simply launching with a new port number every time by default, so window.localStorage was getting wiped out.

This ticket talks about setting an explicit port. This fixed my issue, and now window.localStorage persists across runs:

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

In VS Code, you can set the port number in your launch.json file:

{
    "name": "Flutter",
    "request": "launch",
    "type": "dart",
    "args": ["--web-port", "8686"]
},
Aaron Scherbing
  • 507
  • 6
  • 6
10

With flutter 1.10 we can use universal_html package:

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

Binozo
  • 145
  • 2
  • 10
Spatz
  • 18,640
  • 7
  • 62
  • 66
6

I am using shared_preferences package to store data on local storage

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") ?? "";
  }
}

shared_preferences store data for the current session only.

If you want to store data permanently then you should use cookie to store data.

   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;
      }
    }
Dhanaji Yadav
  • 1,202
  • 1
  • 14
  • 22
  • you are mistaken about **shared_preferences (web)** package, it stores data in `LocalStorage` not `SessionStorage`. – Redanium Sep 15 '22 at 14:52
  • The cookie manager doesn't work for me. Do I need to configure anything in my browsers or store the cookie on the server side? – Anneress Sep 20 '22 at 12:41
  • you should be using Hive: https://pub.dev/packages/hive, extremally fast! – Xao Dec 17 '22 at 21:47
3

After upgrading to flutter 1.9, 'dart:html' is not compiled anymore as it is not part of dart SDK that shipped with Flutter. We can use this package at the moment as it support Android, IOS and WEB: crypted_preferences

yshahak
  • 4,996
  • 1
  • 31
  • 37
  • Although, as someone wrote in slack, looks like It's still available, but there is a bug in the analyzer that make IDE show an error but if you run it it works. – yshahak Sep 16 '19 at 10:19
  • This package requires a path. Anyone know what that is supposed to be? – Jason Spick Oct 07 '19 at 20:28
  • It can be anything, this is just where it will save the data. You can see their example where they use:`Preferences.preferences(path: './example/prefs')` – yshahak Oct 10 '19 at 07:16
  • Does this file need to exist? will it be created if it doesn't. If not what format does it need to be and what is the base of the path? – Jason Spick Oct 10 '19 at 14:24
  • 1
    it will be created if not exist AFAIK. The `./` is the root of your project. – yshahak Oct 11 '19 at 05:03