0

i am trying to get data from Database and it returns me this Future<List<dynamic>>. how can i iterate this to get a specific row or data?

ElevatedButton(
          onPressed: () async {
            var result = DatabaseHelper.instance
                .readNote("SELECT name FROM users where name='ali'");
            result.forEach((row) => print(row));
            // print(getdata[0].toString());
          },
          child: Text('Run'),
        ),

this is my DB Helper class

import 'dart:io';

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

class DatabaseHelper {
  static final DatabaseHelper instance = DatabaseHelper._init();

  static Database? _database;

  DatabaseHelper._init();

  Future<Database> get database async {
    if (_database != null) return _database!;

    _database = await _initDB('sample.db');
    return _database!;
  }

  Future<Database> _initDB(String filePath) async {
    final dbPath = await getDatabasesPath();
    final path = join(dbPath, filePath);
    final exist = await databaseExists(path);
    if (exist) {
      print('Database Already Exsit');
      await openDatabase(path);
    } else {
      print('New Database created from Assets');
      try {
        await Directory(dirname(path)).create(recursive: true);
        print('DB Created');
        ByteData data = await rootBundle.load(join("assets", "sample.db"));
        List<int> bytes =
            data.buffer.asInt8List(data.offsetInBytes, data.lengthInBytes);
        await File(path).writeAsBytes(bytes, flush: true);
        print('DB Coppied');
      } catch (e) {
        print(e);
      }
    }

    return await openDatabase(path);
  }

  Future<List> readNote(String query) async {
    final db = await instance.database;

    final maps = await db.rawQuery(query);

    return maps;
  }

  Future close() async {
    final db = await instance.database;
    db.close();
  }
}

I am using the sample.db file from assets and then want to replace it with SQFLITE Database which is working fine but I can get data from that.

Database Structure Screenshot

James Z
  • 12,209
  • 10
  • 24
  • 44
  • Does this answer your question? [What is a Future and how do I use it?](https://stackoverflow.com/questions/63017280/what-is-a-future-and-how-do-i-use-it) – nvoigt Jul 27 '21 at 18:26

1 Answers1

0

You have to wait for that future to complete, then perform your operations.

ElevatedButton(
          onPressed: () async {
            var result = await DatabaseHelper.instance
                .readNote("SELECT name FROM users where name='ali'");
            result.forEach((row) => print(row));
            // print(getdata[0].toString());
          },
          child: Text('Run'),
        ),


Madhavam Shahi
  • 1,166
  • 6
  • 17