9

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

//这是我需要将数据保存到本地数据库的按钮单击的屏幕。主页.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");
}
}
4

1 回答 1

1

您能否提供更多关于您的实施中不起作用的细节?中的文档sqflite包括您可以使用的帮助器示例。

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

Future<Todo> insert(Todo todo) async {
  todo.id = await db.insert(tableTodo, todo.toMap());
  return todo;
}
于 2020-10-27T20:40:35.243 回答