如何在flutter中使用sqflite将api获取的数据保存到本地数据库中?

时间:2019-02-07 09:38:45

标签: json api flutter sqflite

我正在开发一个需要维护购物车会话的应用程序。单击添加到购物车按钮时,我需要将项目存储在本地数据库中,并在另一个屏幕中从本地数据库检索数据。我在列表中有来自api的数据,但是我没有得到如何将这些数据保存在数据库中的信息。请帮我解决问题。谢谢

///这是从中单击按钮需要将数据保存到本地数据库的屏幕。 home.dart

 ClipRRect(
                                              borderRadius:
                                                  BorderRadius.only(
                                                bottomLeft:
                                                    Radius.circular(5.0),
                                                bottomRight:
                                                    Radius.circular(5.0),
                                              ),
                                              child: Container(
                                                decoration: BoxDecoration(
                                                    border: Border(
                                                  right: BorderSide(
                                                    color: Colors.black12,
                                                  ),
                                                  left: BorderSide(
                                                    color: Colors.black12,
                                                  ),
                                                  bottom: BorderSide(
                                                    color: Colors.black12,
                                                  ),
                                                )),
                                                height: 40.0,
                                                width: 200.0,
                                                child: ActionChip(
                                                    label: Text(
                                                      "ADD TO CART",
                                                      style: TextStyle(
                                                          fontSize: 16.0),
                                                    ),
                                                    pressElevation: 0.0,
                                                    avatar: Icon(
                                                      Icons
                                                          .add_shopping_cart,
                                                      size: 20.0,
                                                      color: Color(
                                                        0xFFD1A155,
                                                      ),
                                                    ),
                                                    backgroundColor:
                                                        Colors.transparent,
                                                    onPressed: () async {
                                                      await DBProvider.db
                                                          .newClient(
                                                              clientList(
                                                                  index));
                                                    }),
                                              ),
                                            ),

//This is how i am fetching the data from the api
List<FeaturedModel> myAllDatas = [];
List<FeaturedItemsModel> myItems = [];

Future getDatas() async {
String basicAuth = 'Basic ' +
    base64.encode(
        utf8.encode('${GlobalVar.consumerKey}:${GlobalVar.secretKey}'));

var response = await http
    .get("${GlobalVar.url}wp-json/wc/v3/products?featured=1", headers: {
  'Authorization': basicAuth,
  'Accept': 'application/json',
});
if (response.statusCode == 200) {
  String responseBody = response.body;
  var jsonBody = json.decode(responseBody);
  for (var data in jsonBody) {
    myAllDatas.add(new FeaturedModel(
        data['id'], data['name'], data['price'], data['average_rating']));
    for (var items in jsonBody) {
      myItems.add(new FeaturedItemsModel(items['images'][0]['src']));
    }
  }
  setState(() {});
} else {
  print(response.statusCode);
  print(response.body);
}
}

模型类

import 'dart:convert';

Client clientFromJson(String str) {
final jsonData = json.decode(str);
return Client.fromMap(jsonData);
}

String clientToJson(Client data) {
final dyn = data.toMap();
return json.encode(dyn);
}

class Client {
int id;
String name;
String price;
 String category;
String image;


Client({this.id, this.name, this.price, this.category, this.image});

factory Client.fromMap(Map<String, dynamic> json) => new Client(
id: json["id"],
name: json["name"],
price: json["price"],
category: json["category"],
image: json["image"],
);

Map<String, dynamic> toMap() => {
"id": id,
"name": name,
"price": price,
"category": category,
"image": image
 };
}

dbhelper类

 import 'dart:async';
import 'dart:io';

import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:restaurant_app/models/cartModel.dart';
import 'package:sqflite/sqflite.dart';

class DBProvider {
DBProvider._();

static final DBProvider db = DBProvider._();

Database _database;

Future<Database> get database async {
if (_database != null) return _database;
// if _database is null we instantiate it
_database = await initDB();
return _database;
}

initDB() async {
Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, "TestDB.db");
return await openDatabase(path, version: 1, onOpen: (db) {},
    onCreate: (Database db, int version) async {
      await db.execute("CREATE TABLE Client ("
          "id INTEGER PRIMARY KEY,"
          "name TEXT,"
          "price TEXT,"
          "category TEXT,"
          "image TEXT,"
          ")");
    });
}

newClient(Client newClient) async {
final db = await database;
//get the biggest id in the table
var table = await db.rawQuery("SELECT MAX(id)+1 as id FROM Client");
int id = table.first["id"];
//insert to the table using the new id
var raw = await db.rawInsert(
    "INSERT Into Client (id,first_name,last_name,blocked)"
        " VALUES (?,?,?,?)",
    [id, newClient.name, newClient.price, 
newClient.category,newClient.image]);
return raw;
}

updateClient(Client newClient) async {
final db = await database;
var res = await db.update("Client", newClient.toMap(),
    where: "id = ?", whereArgs: [newClient.id]);
return res;
}

getClient(int id) async {
final db = await database;
var res = await db.query("Client", where: "id = ?", whereArgs: [id]);
return res.isNotEmpty ? Client.fromMap(res.first) : null;
}

Future<List<Client>> getAllClients() async {
final db = await database;
var res = await db.query("Client");
List<Client> list =
res.isNotEmpty ? res.map((c) => Client.fromMap(c)).toList() : [];
return list;
}

deleteClient(int id) async {
final db = await database;
return db.delete("Client", where: "id = ?", whereArgs: [id]);
}

deleteAll() async {
final db = await database;
db.rawDelete("Delete * from Client");
}
}

1 个答案:

答案 0 :(得分:0)

您能否提供更多有关实施中不起作用的细节? sqflite中的documentation包括您可以使用的帮助程序的示例。

由于您要将json数据映射到对象中,因此页面上的此帮助程序片段应有助于映射数据库中的对象。

Future<Todo> insert(Todo todo) async {
  todo.id = await db.insert(tableTodo, todo.toMap());
  return todo;
}