VimeshPatel
VimeshPatel

Reputation: 35

How to Store API model object in Local Storage in flutter?

I fatch this issue during use Local Storage(shared_preferences: ^2.0.6) in my code....but i cant store the api model object in local storage...How can i do?

 storeModelInPrefs() async {
    http.Response response =
        await http.get(Uri.parse('http://18.191.193.64/api/view_categories'));
    
    String encodeData = jsonEncode(response.body);
    ///Write Data in local Storage 
    GetStorageUtility.prefs!.write('key', encodeData);
    ///Read Data from local Storage 
    String data = GetStorageUtility.prefs!.read('key');

    if (data == null) {
      print('no data in GetStorage');
    } else {
      Map<String, dynamic> map = jsonDecode(data);
      print(map);
    }
  }

Upvotes: 2

Views: 2077

Answers (1)

Sagar Acharya
Sagar Acharya

Reputation: 3777

This is the sample example that i have created from the code that you have provided.

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_app/utilities.dart';
import 'package:http/http.dart' as http;

void main() {
  runApp(MaterialApp(
    home: MyApp(),
  ));
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    GetStorageUtility.init();
    super.initState();
    getRemoteData();
  }

  getRemoteData() async {
    /// This is where the api is fetching the data
    var response =
        await http.get(Uri.parse('http://18.191.193.64/api/view_categories'));

    /// This is where the string getting
    String encodeData = jsonEncode(response.body);
    GetStorageUtility.write("key", encodeData);

    /// this is where you fetch the data
    String data = GetStorageUtility.read("key");

    if (data == null) {
      print('no data in GetStorage');
    } else {
      Map<String, dynamic> jsonData = json.decode(data);
      jsonData.forEach((key, value) {
        print("$key :  $value\n");
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Text(" Page"),
      ),
    );
  }
}

SharadPrefs Singleton,

import 'dart:async';

import 'package:shared_preferences/shared_preferences.dart';

class GetStorageUtility {
  static Future<SharedPreferences> get _instance async =>
      _prefsInstance ??= await SharedPreferences.getInstance();
  static SharedPreferences _prefsInstance;

  static Future<SharedPreferences> init() async {
    _prefsInstance = await _instance;
    return _prefsInstance;
  }

  static String read(String key, [String defValue]) {
    return _prefsInstance.getString(key) ?? defValue ?? "";
  }

  static Future<bool> write(String key, String value) async {
    var prefs = await _instance;
    return prefs?.setString(key, value) ?? Future.value(false);
  }
}

Now there is on thing that you have see that you have added in you android manifest file

<application android:usesCleartextTraffic="true" />

This one should be there and the internet permission should be there in the debug and the main folders manifestfile.

This will work but this is not the best practice to store the data as string in the sharedprefs. Shared Prefs has only the job to manage the small data like bool or string. For your use case you can use a sqlite as a local data base. where you can fetch the data based on the condititions.

Let me know if it works.

Happy Coding.

Upvotes: 1

Related Questions