将API数据存储到SQLite中

xyhw6mcr  于 2022-11-15  发布在  SQLite
关注(0)|答案(2)|浏览(227)

我想从REST API获取数据并将信息存储在本地数据库中,但收到如下错误:
_TypeError(type‘(Map<字符串,Dynamic>)=>QuizDescription’不是‘f’的类型‘(Dynamic)=>QuizDescription’的子类型)
我的榜单模型:

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,
  };

数据库-要在其中存储信息的创建方法:

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

API调用-它使用的是数据库方法:

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);
wgmfuz8q

wgmfuz8q1#

试试这个..。

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);

存储信息的数据库创建方法

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;
}
vulvrdjw

vulvrdjw2#

试试这个:

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

相关问题