Trending Articles       10 Flutter Listview Examples       Flutter Custom Button Example       Flutter Audio Recording       Flutter 2.0 Autocomplete TextField       Current Location Google Maps

Copy flutter assets database inside application

How to copy database from assets list in flutter. If we have an existing database file, that we need to copy into current flutter application.

To read an existing database we will do following steps.

  • Add database file in assets list.
  • Create a Database file to check existing database
  • Copy current database to the Sqflite database.

 

Read create simple Sqflite database in flutter 

 

Let's get started

Step 1: Create a Flutter application

Step 2: Add sqflite dependency plugin in pubspec.yaml file

dependencies:
  flutter:
  sqflite:
  path:

 

Step 3:  Create a file databse.dart and add below code

This code will check existing database is available or not, if it there it won't create again, if the database is not exist, will read database file from assets file and create database.

Future<String> initDatabase() async {


  var databasesPath = await getDatabasesPath();
  var path = join(databasesPath, "demo_asset_example.db");

// Check if the database exists
  var exists = await databaseExists(path);

  if (!exists) {
    // Should happen only the first time you launch your application
    print("Creating new copy from asset");

    // Make sure the parent directory exists
    try {
      await Directory(dirname(path)).create(recursive: true);
    } catch (_) {}

    // Copy from asset
    ByteData data = await rootBundle.load(join("assets", "example.db"));
    List<int> bytes =
    data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);

    // Write and flush the bytes written
    await File(path).writeAsBytes(bytes, flush: true);

  } else {
    print("Reading Existing Database");
  }
// open the database
 // database = await openDatabase(path, readOnly: true);


  return path;
}

 

Read database tables from Sqflite database

To read created tables from database we will use below code

Future<String> readTables() async
{
  Database db = await database;
  var res=await  db.rawQuery("select * FROM  sqlite_master WHERE type ='table'");
  if(res.length>0)
  {
    return res.first.entries.toString();

  }
  return "No Tables found";
}

 

Read assets database file flutter

 

Complete example to read database from assets file here

import 'dart:async';

import 'package:flutter/material.dart';

import 'databse.dart';

class AssetsDatabase extends StatefulWidget{
  @override
  _AssetsDatabaseState createState() => _AssetsDatabaseState();
}

class _AssetsDatabaseState extends State<AssetsDatabase> {

  bool readTable=false;
  String table_info="";
  final _tables = StreamController<String>();
  Sink get updateUser => _tables.sink;
  Stream<String> get user => _tables.stream;
  @override
  Widget build(BuildContext context) {
    // TODO: implement build


    return MaterialApp(home: Scaffold(
      appBar: AppBar(title: Text("Read Assets Database"),),
      body:
      Column(
        children: [
          FutureBuilder(
            builder:(context, snapshot)  {
              if (snapshot.hasData) {
              return  SingleChildScrollView(
                child: Card(
                  margin: EdgeInsets.all(8),
                  child: Column(
                    mainAxisSize: MainAxisSize.max,
                    children: [
                          Text("Database Created, Now you can load tables"),
                          RaisedButton(onPressed: (){
                          readTable=true;
                            readTablesFromDb();
                              },child: Text("Load Tables"),
                          ),

                          stream(),
                    ],

                  ),
                ),
              );
              }
              else{
                   return  Text("Database Not created");
              }


            } ,
            future: initDatabase(),
          ),

        ],
      ),

    ),);
  }
  stream()
  {
   return StreamBuilder<String>(
      initialData: "",
      stream: _tables.stream,
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.active)
          return Text(" ${snapshot.data}");
        if (snapshot.connectionState == ConnectionState.active)
          return   Text(" ${snapshot.data}");
        return CircularProgressIndicator();
      },
    );
  }

  readTablesFromDb()
  {
    if(readTable)
      (readTables().then((value) => {
        _tables.add(value)
      }));
    else   _tables.add("No Tables");
  }

}

 

import 'dart:io';

import 'package:flutter/services.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';

 Database _database;
int _databaseVersion=1;
/// delete the db, create the folder and returnes its path
Future<String> readTables() async
{
  Database db = await database;
  var res=await  db.rawQuery("select * FROM  sqlite_master WHERE type ='table'");
  if(res.length>0)
  {
    //mapData.entries.map( (entry) => Weight(entry.key, entry.value)).toList();
    String s="";
    for(int k=0;k<res.length;k++)
      {
        print("reading ");

        for (var entry in res[k].entries) {
          print(entry.key);
          print(entry.value);
          if(entry.key=="tbl_name")
          s=s+ "Table Name: ${entry.value}\n";
          else if(entry.key=="sql")
            s=s+ "Table Query: ${entry.value}\n";
        }

        s=s+"  \n\n  -----------  \n\n";

      }
    return s;

  }
  return "No Tables found";
}

Future<String> readTables() async
{
  Database db = await database;
  var res=await  db.rawQuery("select * FROM  sqlite_master WHERE type ='table'");
  if(res.length>0)
  {
    return res.first.entries.toString();

  }
  return "No Tables found";
}

Future get database async {
  if (_database != null) return _database;
  // lazily instantiate the db the first time it is accessed
  _database = await _initDatabase();
  return _database;
}
_initDatabase() async {
  var databasesPath = await getDatabasesPath();
  var path = join(databasesPath, "demo_asset_example.db");

  return await openDatabase(path,
      version: _databaseVersion,
      onCreate: _onCreate);
}

// SQL code to create the database table
Future _onCreate(Database db, int version) async {

}


 

 


987 Views

Author: RRTutors

Flutter Questions

Android Questions