Reputation: 3216
I'm new on SQLite
and flutter
. I'm trying to access an SQLite
database (which is on my computer in the project folder at '~/Work/FlutterTest/ProjectTestFlutter/poa.db'
.
But I have null
when I try to cast
my List
to String
.
There is my code :
class _DbPageState extends State<DbPage> {
String data;
var databasesPath;
String path;
Database database;
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return new Scaffold(
body: Container(
child: Row(
children: <Widget>[
new IconButton(
onPressed: () {
data = getRecords().toString();
},
icon: Icon(Icons.more_vert)),
new Text(
data,
)
],
),
));
}
Future<void> openDb() async {
var databasesPath = await getDatabasesPath();
String path = join(databasesPath, '~/Work/FlutterTest/ProjectTestFlutter/poa.db');
database = await openDatabase(path, version: 1);
}
Future<List<Map>> getRecords() async {
List<Map> list = await database.rawQuery('SELECT * FROM tbl1');
return list;
}
Future<void> closeDb() async {
await database.close();
}
}
Upvotes: 0
Views: 535
Reputation: 3865
When app starts for example, copy the db to your device.
ByteData data = await rootBundle.load("assets/poa.db");
List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
var databasesPath = await getDatabasesPath();
String dbPath = join(databasesPath, "poa.db");
await File(dbPath).writeAsBytes(bytes);
Remember to add the db file to the pubspec.yml, just as you would do with image resources. After that you could open it from the widget with:
var databasesPath = await getDatabasesPath();
String dbPath = join(databasesPath, "poa.db");
var database = await openDatabase(dbPath, version: 1);
Upvotes: 1