i am trying to get data from Database and it returns me this Future<List<dynamic>> how can i iterate this

i am trying to get data from Database and it returns me this Future<List> 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();
  }
}

Note: 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 able to get data from that

Database Structure Screenshot

1 answer

  • answered 2021-07-27 19:36 Madhavam Pratap Shahi

    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'),
            ),
    
    
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum