问题描述
我在Flutter中有一个应用程序想在初始化数据库时将数据列表添加到sqlite数据库,我对模型类型有疑问。 我有这个数据模型:
import 'dart:convert';
List<Clubs> clubsFromMap(String str) =>
List<Clubs>.from(json.decode(str).map((x) => Clubs.fromMap(x)));
String clubsToMap(List<Clubs> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toMap())));
class Clubs {
Clubs({
this.id,this.club,this.leagueId,this.price,this.surname,this.leagueName,this.counter,this.selected,});
int id;
String club;
int leagueId;
String price;
String surname;
String leagueName;
int counter;
String selected;
factory Clubs.fromMap(Map<String,dynamic> json) => Clubs(
id: json["id"],club: json["club"],leagueId: json["league_id"],price: json["price"],surname: json["surname"],leagueName: json["league_name"],counter: json["counter"],selected: json["selected"],);
Map<String,dynamic> toMap() => {
"id": id,"club": club,"league_id": leagueId,"price": price,"surname": surname,"league_name": leagueName,"counter": counter,"selected": selected,};
}
我有这个模型的数据列表:
var clubs = [
{
"id": 1,"club": "Manchester City","league_id": 1,"price": "10.00","surname": "MCY","league_name": "Premier League","counter": 1,"selected": "No"
},..................etc
]
不,我想将此初始数据添加到 sqflite 数据库,我创建了 :
import 'package:sqflite/sqflite.dart';
class DataBaseService {
static final DataBaseService _instance = DataBaseService.internal();
factory DataBaseService() => _instance;
DataBaseService.internal();
Database _database;
Future<Database> get database async {
if (_database == null) {
_database = await intializeDataBase();
return _database;
}
}
Future<Database> intializeDataBase() async {
var dir = await getDatabasesPath();
var path = dir + "clubs.db";
var database =
await openDatabase(path,version: 1,onCreate: (db,version) {
db.execute('''
create table $clubsTableName(
columnId integer primary key,$columnClub text not null,$columnLeaueId integer,$columnPrice double,$columnSurname text not null,$columnLeagueName text,$columnCounter integer.
$columnSelected text,)
''');
db.insert(clubsTableName,clubs.toMap());
它说 toMap() 没有定义,如果我把它改成 clubsFromMap(clubs) 而不是 clubs.toMap() 它说:The argument type 'List<Clubs>' can't be assigned to the parameter type 'Map<String,Object>'.dart(argument_type_not_assignable)
我该如何解决这个问题?
解决方法
我像这样更改列表格式后解决了它:
var clubs = {"data":{
{
"id": 1,"club": "Manchester City","league_id": 1,"price": "10.00","surname": "MCY","league_name": "Premier League","counter": 1,"selected": "No"
},..................etc}
}