My goal is to extract a single value from the database using Future function and show this value in a text widget like this: Widget myFlag = Text(myvar);
My Code explanation:
final String myTable = 'myFlag';
// the PhilaFields and myPhila Classes are part of the model class.
class PhilaFields {
static final List<String> values = [id, myFlag];
static final String id = '_id'; // SQL convention
static final String myFlag = 'isFlag';
}
class myPhila {
late final int? id;
late int isFlag=0;
myPhila({required this.id,required this.isFlag});
myPhila copy({int? id,int? isFlag}) => myPhila(id: id ?? this.id,isFlag: isFlag ?? this.isFlag);
Map<String, Object?> toJson() => {if (id != null) PhilaFields.id: id,PhilaFields.myFlag: isFlag};
static myPhila fromJson(Map<String, Object?> json) => myPhila(id: json[PhilaFields.id] as int?,isFlag: json[{PhilaFields.myFlag}] as int);
}
//This function is doing DB rawquery to extract a list of values form myTable
//The following code extracts the List of values.
Future<List<myPhila>> read_isFlag() async {
final db = await instance.dataBase;
final result = await db.rawQuery('SELECT isFlag FROM $myTable');
final list = result.map((json) => myPhila.fromJson(json)).toList();
if(list.isNotEmpty) return list; else throw Exception('Empty List');
}
//Here I need to convert Future function result into a single String variable
//This is Future function returning Future List which I don't know how to convert to a
//single String value:
Future readFlag() async {
List xp=[];
late String str;
await DBHelper.instance.read_isFlag().then((xp) {
str = xp.toString();
return str;
});
}
My ultimate goal: I need to show a single value in the UI text widget:
Widget myFlag = Text(myvar);
I don’t know how to use Future function to get db value.
Please help. Thank You
2
Answers
You can try this code snippet, it basically does the same thing, but it is slightly different when accessing the value, it will access the first value of the list if the read_isFlag() returns a list you can get the single value by doing this.
You need to use a FutureBuilder.
I have created a super simple example of the counter app using sqflite here: https://github.com/alextekartik/flutter_app_example/tree/master/demo_sqflite