How to save to web local storage in flutter web How to save to web local storage in flutter web dart dart

How to save to web local storage in flutter web


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');  }}


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+8void 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);}


With flutter 1.10 we can use universal_html package:

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