Introduction
Local storage saves data directly on your device. This lets your app work even without internet.
Local storage saves data directly on your device. This lets your app work even without internet.
final prefs = await SharedPreferences.getInstance(); await prefs.setString('key', 'value'); String? value = prefs.getString('key');
final prefs = await SharedPreferences.getInstance(); await prefs.setInt('counter', 10); int? count = prefs.getInt('counter');
final prefs = await SharedPreferences.getInstance(); await prefs.setBool('isLoggedIn', true); bool? loggedIn = prefs.getBool('isLoggedIn');
This app shows a counter that saves its value locally. You can close and open the app, and the number stays the same without internet.
import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; void main() => runApp(MyApp()); class MyApp extends StatefulWidget { @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { int _counter = 0; @override void initState() { super.initState(); _loadCounter(); } Future<void> _loadCounter() async { final prefs = await SharedPreferences.getInstance(); setState(() { _counter = prefs.getInt('counter') ?? 0; }); } Future<void> _incrementCounter() async { final prefs = await SharedPreferences.getInstance(); setState(() { _counter++; }); await prefs.setInt('counter', _counter); } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: Text('Offline Counter')), body: Center( child: Text('You have pressed the button $_counter times.'), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, child: Icon(Icons.add), tooltip: 'Increment counter', ), ), ); } }
Local storage is fast and works without internet, but it is limited in size.
Use local storage for small data like settings, counters, or cached info.
For bigger or complex data, consider databases like SQLite.
Local storage keeps data on the device so apps can work offline.
SharedPreferences is a simple way to save small key-value data in Flutter.
Use local storage to improve user experience when internet is unavailable.
final prefs = await SharedPreferences.getInstance();
String? name = prefs.getString('username');
print(name ?? 'No user');SharedPreferences prefs;
prefs.setString('token', 'abc123');Pass the test and this pattern moves unknown