我试图以字符串形式接收未来的返回值。我该怎么办呢?
//Get a stock info
Future<String> getStock(int productID) async{
var dbClient = await db;
var result = await dbClient.rawQuery('SELECT * FROM $tableStock WHERE $columnProductID = $productID');
if(result.length == 0) return null;
return Stock.fromMap(result.first).currentStock;
}
Widget _buildProductInfo(Product data){
return Container(
child: ListView(
padding: EdgeInsets.all(8.0),
children: <Widget>[
_infoRow('Product ID', data.name),
_infoRow('Product Name', data.productID),
_infoRow('Cost Price', data.costPrice),
_infoRow('Selling Price', data.salePrice),
_infoRow('CategoryID', data.categoryID),
_infoRow('Currrent Stock', db.getStock(int.parse(data.productID)))
],
),
);
}
我希望这段代码显示一个“值”,而不是说“未来的实例”。但我可以在尝试时打印返回值
final res = await db.getStock(int.parse(data.productID);
print(res);
最佳答案
你必须等待未来才能打开价值。您可以使用未来的生成器来执行此操作。
而不是这样:
_infoRow('Currrent Stock', db.getStock(int.parse(data.productID))),
有这个:
FutureBuilder(
future: db.getStock(int.parse(data.productID),
builder: (context, snapshot) => _infoRow('Currrent Stock', snapshot.data),
),
您的完整代码如下所示:
child: StreamBuilder<Product>(
initialData: barcode,
stream: bloc.scannedCode,
builder: (BuildContext context, AsyncSnapshot snapshot){
if (snapshot.hasError) return Text('Error: ${snapshot.error}');
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('Select lot');
case ConnectionState.waiting:
return _buildProductInfo(snapshot.data);
case ConnectionState.active:
case ConnectionState.done:
return _buildProductInfo(snapshot.data);
}
},
)
Widget _buildProductInfo(Product data){
return Container(
child: ListView(
padding: EdgeInsets.all(8.0),
children: <Widget>[
_infoRow('Product ID', data.name),
_infoRow('Product Name', data.productID),
_infoRow('Cost Price', data.costPrice),
_infoRow('Selling Price', data.salePrice),
_infoRow('CategoryID', data.categoryID),
FutureBuilder(
future: db.getStock(int.parse(data.productID),
builder: (context, snapshot) => _infoRow('Currrent Stock', snapshot.data),
)
],
),
);
}
关于dart - 我如何收到String的 future 值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56069124/