gpt-3.5-turbo-0613· OpenAI
WildChat-4.8M (AI2)
use SharedPreferences to save json flutter
- User
use SharedPreferences to save json flutter
- Assistant
To save JSON using SharedPreferences in Flutter, you can follow these steps:
- Add the
shared_preferencesdependency in yourpubspec.yamlfile:
dependencies: flutter: sdk: flutter shared_preferences: ^2.0.6- Import the necessary packages in your Dart file:
import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'dart:convert';- 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); }- 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; }- Save the JSON data using the
saveJsonToSharedPreferencesfunction:
Map<String, dynamic> jsonData = {'name': 'John Doe', 'age': 25}; await saveJsonToSharedPreferences(jsonData);- Retrieve the JSON data using the
getJsonFromSharedPreferencesfunction:
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. - Add the