Home > Blockchain >  Storing API data into SQLite
Storing API data into SQLite

Time:10-04

I want to fetch data from a REST API and store the information in my local database but get errors like :

_TypeError (type '(Map<String, dynamic>) => QuizDescription' is not a subtype of type '(dynamic) => QuizDescription' of 'f')

My List model:

  factory QuizDescription.fromJson(Map<String, dynamic> json) =>
  QuizDescription(
    quizID: json['id'],
    quizname: json['quizname'],
    kurzbeschreibung: json['kurzbeschreibung'],
    beschreibung: json['beschreibung'],
    preis: json['preis'],
    quizbild: json['quizbild']['url'],
    rating: json['_rating_of_quiz']['rating_rating'],
  );

  Map<String, dynamic> toJson() => {
    "quizID": quizID,
    "quizname": quizname,
    "kurzbeschreibung": kurzbeschreibung,
    "beschreibung": beschreibung,
    "preis": preis,
    "quizbild": quizbild,
    "rating": rating,
  };

Database-Create method where I want to store information in :

static Future<int> createQuiz(QuizDescription quiz) async {
    Database db = await DBQUIZProvider.initQuizDB();
    return await db.insert('quiz', quiz.toJson());
}

API Call - which is using the Database method:

var url = Uri.parse('${Constants.BASE_URL}/QUIZ/getall');
var headers = {'Content-Type': 'application/json'};
var res = await http.get(
  url,
  headers: headers,
);

final body = json.decode(res.body);
QuizDescription quizliste =
    body.map<QuizDescription>(QuizDescription.fromJson).toList();

DBQUIZProvider.createQuiz(quizliste);

CodePudding user response:

try this...

var url = Uri.parse('${Constants.BASE_URL}/QUIZ/getall');
var headers = {'Content-Type': 'application/json'};
var res = await http.get(url, headers: headers,);
List tempList = json.decode(res.body);

Database-Create method where store information in

static Future<int> createQuiz(List quiz) async {
  int result = 0;
  Database db = await DBQUIZProvider.initQuizDB();
  for (var element in planets) {
  QuizDescription quizD = QuizDescription. fromJson(element);
   result = await db.insert(
   'quiz',
   quizD.toMap(),
  conflictAlgorithm: ConflictAlgorithm.replace,
 );
 }
return result;
}

CodePudding user response:

try this:

static Future<int> createQuiz(Map<String, dynamic> row) async {
    Database db = await DBQUIZProvider.initQuizDB();
    return await db.insert('quiz', row);
}
  • Related