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.
If you want to store data permenently then you should use cookie to store data. Cookie used to store data on browsers cookie.
Local storage is a crucial part of mobile app development for maintaining and preserving users' data until the app is removed.
Simple example fromJson(Map<String, dynamic> json) : this. value = json['value']; Map<String, dynamic> toJson() => {'value': value}; } ... JsonStore jsonStore = JsonStore(); CounterModel counter; loadFromStorage() async { Map<String, dynamic> json = await jsonStore. getItem('counter'); counter = json !=
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+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);
}
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"]
},
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With