Saving Data in Flutter

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

Part 3: Reading & Writing Files

17. Using JSON (Part 2)

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: 16. Using JSON (Part 1) Next episode: 18. Challenge: Implement The FileStat Object

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.

Transcript: 17. Using JSON (Part 2)

Now let’s use our class in our SPHelper class, in the sp_helper.dart file.

Actually here we could delete all the getter and setter methods, as they won’t be needed any more, but I’ll just leave them for reference, so that you can compare how simpler this new approach is for this class.

Here we’ll add two new methods to read and write data from sharedPreferences. But first, let’s create a constant for the settings key, that will just take “settings”:

  static const String _settingsKey = 'settings'; 

The method to read the app settings returns an AppSettings object, and we can call it getAppSettings

Let’s declare a final, called jsonString, that calls the _preferences getString method, passing the settingsKey. This can return the string value at the settings key, or null

So in the return statement, if jsonString is not null, we’ll create an AppSettings calling the fromJson constructor, and passing json.decode of jsonString as a map of string dynamic.

This requires importing the dart convert library, and we can do this with the code actions.

If jsonString is null, than let’s just return an Appsettings instance with some default data: the listName is My List Name, for the calories let’s place 2000, and showDate and showFIleSize will both take true as default.

AppSettings getAppSettings() { 
    final jsonString = _preferences.getString(_settingsKey); 
    return jsonString != null 
        ? AppSettings.fromJson(json.decode(jsonString) as Map<String, dynamic>) 
        : AppSettings( 
            listName: 'My list name', 
            calories: 2000, 
            showDate: true, 
            showFileSize: true); 
  } 

All write actions are asynchronous, so our setAppSettings method returns a Future, of bool, takes an AppSettings object and as usual is marked as async.

In the method, first let’s create a fina string called jsonString, thatn calls the json ENCODE method of settings.toJSON. The encode method transforms our Map into a string, which we can then write to sharedPreferences.

Here let’s return preferences setString, passing the settings key and jsonString.

Excellent, the helper is now ready. Let’s call it from the UI then.

In the settings_screen.dart file, in the _SettingsScreenState class, in the initState method, let’s retrieve all the settings with a single method: so final settings will just take prefs.getAppSettings.

final settings = prefs.getAppSettings(); 

Next, instead of calling the getters from prefs, let’s just set the variables with the settings fields: So the listName takes settings.listname…

_listName = settings.listName; 
_calories = settings.calories; 
_showFileSize = settings.showFileSize; 
_showDate = settings.showDate; 

In the same way, in the saveSettings, let’s comment out the setter methods.

Now create an AppSettings object, passing the listnamecontroller.text, the caloriescontroller parsed as an int, the showfilesize boolean, and the showDate boolean

final settings = AppSettings( 
  listName: _listNameController.text, 
  calories: int.tryParse(_caloriesController.text) ?? 0, 
  showFileSize: _showFileSize, 
  showDate: _showDate); 

Next let’s await the prefs setAppSettings method, passing the newly created settings.

await prefs.setAppSettings(settings); 

OK, we are finally ready to try this out!

Let’s open the settings screen, change the List name, the number of calories, then let’s save this, and as you can see the app works as expected! Well done! Again, this didn’t change the user experience, but made our code easier to read and more solid!