0

I have decoded my response.body i.e var jsonData = jsonDecode(response.body); and its working fine But when i convert it into object and saved into local storage using sharedpref like this

if (response.statusCode == 200) {
      jsonData['categoryList'].forEach((data) => {
            categoryList.add(new ExpertCategory(
                id: jsonData['_id'],
                color: jsonData['color'],
                type: jsonData['category_name'],
                icon: ":)"))
          });
      print(categoryList) ;   
      localStorage.setCategoryData(categoryList.toString());

It stored in it And whenever i try to decode this its not working i.e

 localStorage.getCategoryData().then((data) => {
         userMap =  jsonDecode(data),
          
        });

class LocalStorage {
Future setCategoryData(data) async {
    final prefs = await SharedPreferences.getInstance();
    prefs.setString('category', data);
  
  }

  Future getCategoryData() async {
    final prefs = await SharedPreferences.getInstance();
    final category = prefs.getString('category');
    return category;
  }
}
import 'package:flutter/foundation.dart';

class ExpertCategory {
  final String  id;
  final String  type;
  final String  icon;
  final String  color;

const ExpertCategory( {
                  @required this.id,
                  @required this.type,
                  @required this.icon,
                  @required this.color,
                });
}

its not the same as before,its showing error and after fixing some 1st element of string '[' is showing. please help with this thanks in advance.

5
  • What is the error you are getting? also try printing the type of the variable before passing it through jsonDecode just to make sure it's actually string, data.runtimeType refer to: programming-idioms.org/idiom/94/print-type-of-variable/2210/… if it's string, try printing it, make sure it's a valid json Commented Mar 5, 2021 at 14:06
  • Please share the full code of your localStorage class showing the methods you are using to store the data and how they are retrieved. Commented Mar 5, 2021 at 14:07
  • @AliAlNoaimi userMap = jsonEncode(data), userMap1 = jsonDecode(userMap), print( userMap1[0]), I/flutter (25831): [ if i do this under that fuction userMap1 = jsonDecode(data), print( userMap1[0]), gives this [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: FormatException: Unexpected character (at character 2) E/flutter (25831): [Instance of 'ExpertCategory', Instance of 'ExpertCategory', Instance of 'E.. Commented Mar 5, 2021 at 14:14
  • @JayParmar Provide the full code of the class ExpertCategory Commented Mar 5, 2021 at 14:19
  • @Omotayo4i i hv updated my comment please check Commented Mar 6, 2021 at 3:51

1 Answer 1

1

Change your ExpertCategory model to this:

import 'package:flutter/material.dart';

class ExpertCategory {
  String id;
  String type;
  String icon;
  String color;

  ExpertCategory(
      {@required this.id,
      @required this.type,
      @required this.icon,
      @required this.color});

  ExpertCategory.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    type = json['type'];
    icon = json['icon'];
    color = json['color'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['type'] = this.type;
    data['icon'] = this.icon;
    data['color'] = this.color;
    return data;
  }
}

For your LocalStorage class, there are two approaches to setting your data into SharedPreferences. One using setString, the other being setStringList since you are storing the list of categories.

Checkout both approaches below.

APPROACH 1

class LocalStorage {
  Future setCategoryData(List<ExpertCategory> data) async {
    final prefs = await SharedPreferences.getInstance();
    prefs.setString(
        'category', jsonEncode(data.map((e) => e.toJson()).toList()));
  }

  Future<List<ExpertCategory>> getCategoryData() async {
    final prefs = await SharedPreferences.getInstance();
    final category = prefs.getString('category');
    return List<ExpertCategory>.from(
        List<Map<String, dynamic>>.from(jsonDecode(category))
            .map((e) => ExpertCategory.fromJson(e))
            .toList());
  }
}

APPROACH 2

class LocalStorage {
  Future setCategoryData(List<ExpertCategory> data) async {
    final prefs = await SharedPreferences.getInstance();
    prefs.setStringList('category',
        List<String>.from(data.map((e) => jsonEncode(e.toJson())).toList()));
  }

  Future<List<ExpertCategory>> getCategoryData() async {
    final prefs = await SharedPreferences.getInstance();
    final category = prefs.getStringList('category');
    return List<ExpertCategory>.from(
        category.map((e) => ExpertCategory.fromJson(jsonDecode(e))).toList());
  }
}

And finally you set your data into the SharedPreferences using

localStorage.setCategoryData(categoryList);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.