Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save api fetched data into local database using sqflite in flutter?

I am developing an app where I need to maintain an add to cart session. I need to store the items in the local DB and retrieve the data from the local DB in another screen when the add to cart button is clicked. I have the data from the API in a list but I am not getting how to save those data in the database. Please help me solve the problem. Thank you

//This is the screen from wherein a button click I need to save the data to the local database. 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);
}
}

model class

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 class

 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");
}
}
like image 519
Bishal Das Avatar asked Feb 07 '19 09:02

Bishal Das


1 Answers

Could you provide more details on what's not working in your implementation? The documentation in sqflite includes example for helpers that you can use.

Since you're mapping the json data into an Object, this helper snippet from the page should help map Objects in the database.

Future<Todo> insert(Todo todo) async {
  todo.id = await db.insert(tableTodo, todo.toMap());
  return todo;
}
like image 80
Omatt Avatar answered Nov 16 '22 00:11

Omatt