Gopal Awasthi
Gopal Awasthi

Reputation: 433

Convert the Future<List<String>> to List<String> when calls the Sqflite function

I want to get all the items from the database, but i am stuck how to convert the Future list of strings to list of strings.

var x =  DataBaseHelper.instance.queryAllRows();


 Future<List<String>> queryAllRows() async {
    Database db = await instance._initDatabase();
    List<Map<String,dynamic>> s =  await db.query(table ,columns: [columnname]);
    List<String> list = new List();
    for(var x in s){
      x.forEach((k,v)=>list.add(v));
    }
    return list;
 }

I want to get all the values in the database but dont know how to convert those values to the List

Upvotes: 2

Views: 11266

Answers (4)

user1462442
user1462442

Reputation: 8202

You have two of choices. You can use future builder to create widgets or use plain futures + setState

https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html

https://dart.dev/tutorials/language/futures

https://api.flutter.dev/flutter/widgets/State/setState.html

List<String> _databaseList

queryAllRows().then((rows) {

   setState(() {_databaseList = rows});
})

setState will tell the flutter to rebuild the widget tree. then to process the future.

Upvotes: 2

fvillalba
fvillalba

Reputation: 1058

You need to await the queryAllRows() to complete. If you are in the context of a function that can be marked as async just need to use the keyword :

void someFunction() async {
var x =  await DataBaseHelper.instance.queryAllRows(); // x is List<String>
}

Instead, if you want to render the list you can use the FutureBuilder and manage the render widget based on Future state :

Widget test(BuildContext context) {
  return FutureBuilder<List<String>>(
    future: DataBaseHelper.instance.queryAllRows(),
    builder: (context, snap) {
      if (snap.hasData && !snap.hasError) {
        return ListView(
          padding: const EdgeInsets.all(8.0),
          children: <Widget>[...snap.data],
        );
      }
      else {
        return Container();
      }
    },
  );
}

Upvotes: 0

diegoveloper
diegoveloper

Reputation: 103541

You need an asynchronous function to retrieve the data.

void yourFunction() async {
     var x =  await DataBaseHelper.instance.queryAllRows();

}

Upvotes: 2

sfung3
sfung3

Reputation: 2377

Because db.querys are asynchronous, they are going to return a Future<List<Map<String,dynamic>>. To get their result without a future, we can get a call back and it will return a List<Map<String,dynamic>> instead.

var x =  DataBaseHelper.instance.queryAllRows();

  Future<List<String>> queryAllRows() async {
    Database db = await instance._initDatabase();
    db.query(table ,columns: [columnname]).then((data){
      List<Map<String,dynamic>> s = data;
      List<String> list = new List();
      for(var x in s){
        x.forEach((k,v)=>list.add(v));
      }
    });
    return list;
  }

Upvotes: 1

Related Questions