我的目标是使用 Future 函数从数据库中提取单个值,并在文本小部件中显示该值,如下所示:Widget myFlag = Text(myvar);
我的代码解释:
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;
});
}
我的最终目标:我需要在 UI 文本小部件中显示单个值:
小部件 myFlag = Text(myvar);
我不知道如何使用 Future 函数来获取 db 值。
请帮忙。谢谢
你可以试试这个代码片段,它基本上做了同样的事情,但在访问值时略有不同,如果 read_isFlag() 返回一个列表,它将访问列表的第一个值你可以通过这样做获得单个值这个。
Future<String> readFlag() async {
final flagList = await DBHelper.instance.read_isFlag();
if (flagList.isNotEmpty) {
return flagList[0].isFlag.toString();
} else {
throw Exception('Empty List');
}
}