Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· OpenAIAi2 WildChat-4.8M (AI2)

use SharedPreferences to save json flutter

  1. User

    use SharedPreferences to save json flutter

  2. Assistant

    To save JSON using SharedPreferences in Flutter, you can follow these steps:

    1. Add the shared_preferences dependency in your pubspec.yaml file:
    dependencies:
      flutter:
        sdk: flutter
      shared_preferences: ^2.0.6
    
    1. Import the necessary packages in your Dart file:
    import 'package:flutter/material.dart';
    import 'package:shared_preferences/shared_preferences.dart';
    import 'dart:convert';
    
    1. Define a function to save the JSON data to SharedPreferences:
    Future<void> saveJsonToSharedPreferences(Map<String, dynamic> jsonData) async {
      final SharedPreferences prefs = await SharedPreferences.getInstance();
      final String jsonString = jsonEncode(jsonData);
      prefs.setString('json_data', jsonString);
    }
    
    1. Define a function to retrieve the JSON data from SharedPreferences:
    Future<Map<String, dynamic>> getJsonFromSharedPreferences() async {
      final SharedPreferences prefs = await SharedPreferences.getInstance();
      final String jsonString = prefs.getString('json_data');
      if (jsonString != null) {
        final jsonData = jsonDecode(jsonString) as Map<String, dynamic>;
        return jsonData;
      }
      return null;
    }
    
    1. Save the JSON data using the saveJsonToSharedPreferences function:
    Map<String, dynamic> jsonData = {'name': 'John Doe', 'age': 25};
    await saveJsonToSharedPreferences(jsonData);
    
    1. Retrieve the JSON data using the getJsonFromSharedPreferences function:
    Map<String, dynamic> retrievedJsonData = await getJsonFromSharedPreferences();
    print(retrievedJsonData);
    

    Make sure to replace 'json_data' with your desired key to store the JSON data. The above code will save the JSON data as a String in SharedPreferences. When retrieving, it will decode the JSON string back to a Map.