title: How to save api fetched data into local database using sqflite in flutter?
body: <p>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</p>
  <p>//This is the screen from wherein a button click I need to save the data to the local database.
  home.dart</p>
  <pre><code> 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(
                                                        &quot;ADD TO CART&quot;,
                                                        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&lt;FeaturedModel&gt; myAllDatas = [];
  List&lt;FeaturedItemsModel&gt; myItems = [];
  
  Future getDatas() async {
  String basicAuth = 'Basic ' +
      base64.encode(
          utf8.encode('${GlobalVar.consumerKey}:${GlobalVar.secretKey}'));
  
  var response = await http
      .get(&quot;${GlobalVar.url}wp-json/wc/v3/products?featured=1&quot;, 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);
  }
  }
  </code></pre>
  <p>model class</p>
  <pre><code>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&lt;String, dynamic&gt; json) =&gt; new Client(
  id: json[&quot;id&quot;],
  name: json[&quot;name&quot;],
  price: json[&quot;price&quot;],
  category: json[&quot;category&quot;],
  image: json[&quot;image&quot;],
  );
  
  Map&lt;String, dynamic&gt; toMap() =&gt; {
  &quot;id&quot;: id,
  &quot;name&quot;: name,
  &quot;price&quot;: price,
  &quot;category&quot;: category,
  &quot;image&quot;: image
   };
  }
  </code></pre>
  <p>dbhelper class</p>
  <pre><code> 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&lt;Database&gt; 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, &quot;TestDB.db&quot;);
  return await openDatabase(path, version: 1, onOpen: (db) {},
      onCreate: (Database db, int version) async {
        await db.execute(&quot;CREATE TABLE Client (&quot;
            &quot;id INTEGER PRIMARY KEY,&quot;
            &quot;name TEXT,&quot;
            &quot;price TEXT,&quot;
            &quot;category TEXT,&quot;
            &quot;image TEXT,&quot;
            &quot;)&quot;);
      });
  }
  
  newClient(Client newClient) async {
  final db = await database;
  //get the biggest id in the table
  var table = await db.rawQuery(&quot;SELECT MAX(id)+1 as id FROM Client&quot;);
  int id = table.first[&quot;id&quot;];
  //insert to the table using the new id
  var raw = await db.rawInsert(
      &quot;INSERT Into Client (id,first_name,last_name,blocked)&quot;
          &quot; VALUES (?,?,?,?)&quot;,
      [id, newClient.name, newClient.price, 
  newClient.category,newClient.image]);
  return raw;
  }
  
  updateClient(Client newClient) async {
  final db = await database;
  var res = await db.update(&quot;Client&quot;, newClient.toMap(),
      where: &quot;id = ?&quot;, whereArgs: [newClient.id]);
  return res;
  }
  
  getClient(int id) async {
  final db = await database;
  var res = await db.query(&quot;Client&quot;, where: &quot;id = ?&quot;, whereArgs: [id]);
  return res.isNotEmpty ? Client.fromMap(res.first) : null;
  }
  
  Future&lt;List&lt;Client&gt;&gt; getAllClients() async {
  final db = await database;
  var res = await db.query(&quot;Client&quot;);
  List&lt;Client&gt; list =
  res.isNotEmpty ? res.map((c) =&gt; Client.fromMap(c)).toList() : [];
  return list;
  }
  
  deleteClient(int id) async {
  final db = await database;
  return db.delete(&quot;Client&quot;, where: &quot;id = ?&quot;, whereArgs: [id]);
  }
  
  deleteAll() async {
  final db = await database;
  db.rawDelete(&quot;Delete * from Client&quot;);
  }
  }
  </code></pre>