Saving Data in Flutter

Jan 31 2024 · Dart 3, Flutter 3.10, Visual Studio Code

Part 2: Use SharedPreferences & Secure Storage

05. Perform CRUD Tasks with SharedPreferences

Episode complete

Play next episode

Next
About this episode
Leave a rating/review
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 04. Using SharedPreferences Next episode: 06. Connect the User Interface to the Data (Part 1)

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

We are finally ready to write some code! From now on, we’ll work at creating “My Recipes”, the app that you’ll build in this course.

flutter pub add shared_preferences
import 'package:shared_preferences/shared_preferences.dart'; 
class SPHelper {} 
static const String _listNameKey = 'listName'; 
static const String _caloriesKey = 'calories'; 
static const String _showFileSizeKey = 'showFileSize'; 
SPHelper._internal(); 
static final SPHelper _instance = SPHelper._internal(); 
late SharedPreferences _preferences; 
static Future<SPHelper> getInstance() async { 
    _instance._preferences = await SharedPreferences.getInstance(); 
    return _instance; 
  } 
Future<bool> setListName(String listName) async { 
    return await _preferences.setString(_listNameKey, listName); 
} 
String getListName() { 
    return _preferences.getString(_listNameKey) ?? 'My Recipes'; 
  } 
Future<bool> setCalories(int calories) async { 
  return await _preferences.setInt(_caloriesKey, calories); 
} 
int getCalories() { 
  return _preferences.getInt(_caloriesKey) ?? 2000; 
} 
Future<bool> setShowFileSize(bool showFileSize) async { 
  return await _preferences.setBool(_showFileSizeKey, showFileSize); 
} 

bool getShowFileSize() { 
  return _preferences.getBool(_showFileSizeKey) ?? true; 
} 
Future<bool> deleteSettings() async { 
    return await _preferences.remove(_listNameKey) && 
        await _preferences.remove(_caloriesKey) && 
        await _preferences.remove(_showFileSizeKey); 
  }