我如何以字符串形式接收将来的值

时间:2019-05-10 00:13:24

标签: dart flutter

我正在尝试以字符串形式接收Future的返回值。我该怎么办。

//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);

2 个答案:

答案 0 :(得分:1)

您必须等待未来才能释放价值。您可以使用将来的构建器来执行此操作。

而不是这样:

_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),
           )
        ],
      ),
    );
  }

答案 1 :(得分:0)

您必须在async方法上使用_buildProductInfo(),并在await之前使用db.getStock(int.parse(data.productID))。这样,执行将被挂起,直到Future完成。