如何在 Flutter/Dart 中将 Future<double> 转换为 double?

Posted

技术标签:

【中文标题】如何在 Flutter/Dart 中将 Future<double> 转换为 double?【英文标题】:How To Convert a Future<double> to a double in Flutter/Dart? 【发布时间】:2020-11-05 13:37:08 【问题描述】:

提前感谢您的帮助。期货总是让我头疼。

这两个替身是我的有状态小部件屏幕中的变量。

double _totalExpenses;
double _totalExpensesForBudget;

我有一个 Sqflite 数据库,它有两种检索两个单独总和的方法:

Future getTotalExpensesForBudget(int budgetId) async 
final db = await database;
var totalExpensesForBudget = await db.rawQuery('SELECT SUM(Amount) FROM TRANSACTIONS WHERE Budget_id = $budgetId');
return totalExpensesForBudget[0]['SUM(Amount)'];


Future getTotalExpenses() async 
final db = await database;
var totalExpenses = await db.rawQuery('SELECT SUM(Amount) FROM Transactions');
return totalExpenses[0]['SUM(Amount)'];

在我的有状态 Flutter 屏幕中,我有一个方法调用两个 Sqflite 方法并将返回值分配给我在上面声明的两个双精度:

Future<double> getExpensePercentage(int budgetId) async 
_totalExpenses = await DbHelper.db.getTotalExpenses();
_totalExpensesForBudget = await DbHelper.db.getTotalExpensesForBudget(budgetId);
return (_totalExpensesForBudget / _totalExpenses);

在我的小部件构建方法中,我需要将 getExpensePercentage(int budgetId) 方法的返回值传递给名为 BudgetCard 的有状态小部件。我的 BudgetCard 有状态小部件的 percentOfExpenses: 参数预期为双倍。

@override
Widget build(BuildContext context) 
getBudgets();
return Column(
  children: <Widget>[
    Image(
      fit: BoxFit.fill,
      image: AssetImage('images/skeemaplaceholder.jpg'),
    ),
    Expanded(
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: ListView.separated(
          itemCount: _budgets.length,
          itemBuilder: (BuildContext context, int index) 
            return BudgetCard(
              icon: IconData(_budgets[index].icon, fontFamily: 'MaterialIcons'),
              name: _budgets[index].name,
              budgetBalance: _budgets[index].budgetBalance,
              budgetAmount: _budgets[index].budgetAmount,
              percentOfTotalBudget: (_budgets[index].budgetAmount / _budgetTotal) * 100,
              percentOfExpenses: 10,
              onPressed: (value) 
                switch (value) 
                  case 'Edit':
                    
                      _action = 'Edit';
                      _id = _budgets[index].id;
                      _name = _budgets[index].name;
                      _icon = IconData(_budgets[index].icon, fontFamily: 'MaterialIcons');
                      _budgetBalance = _budgets[index].budgetBalance;
                      _isPrimary = _budgets[index].isPrimary;
                      goToBudgetActionScreen(context);
                      break;
                    
                  case 'Transfer':
                    
                      break;
                    
                  case 'Delete':
                    
                      if (_budgets[index].id == 3) 
                        Scaffold.of(context).showSnackBar(SnackBar(content: Text('Default budget cannot be deleted.')));
                       else 
                        showDialog(
                          context: context,
                          barrierDismissible: false,
                          builder: (BuildContext context) 
                            return AlertDialog(
                              title: Text(
                                'Are you sure? This action cannot be undone.',
                                style: TextStyle(fontSize: 16),
                              ),
                              actions: <Widget>[
                                FlatButton(
                                  child: Text('Yes'),
                                  onPressed: () 
                                    deleteBudget(_budgets[index].id);
                                    Navigator.pop(context);
                                  ,
                                ),
                                FlatButton(
                                  child: Text('Cancel'),
                                  onPressed: () => Navigator.pop(context),
                                ),
                              ],
                            );
                          ,
                        );
                        break;
                      
                    
                
              ,
            );
          ,
          separatorBuilder: (BuildContext context, int index) 
            return Divider();
          ,
        ),
      ),
    ),
    Padding(
      padding: EdgeInsets.only(bottom: 4),
    ),
    Center(
      child: FlatButton(
        color: Colors.red,
        textColor: Colors.white,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(20),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            const Icon(Icons.add_circle),
            Padding(
              padding: const EdgeInsets.fromLTRB(8, 0, 0, 0),
              child: const Text(
                'New Budget',
              ),
            ),
          ],
        ),
        onPressed: () 
          goToBudgetActionScreen(context);
        ,
      ),
    ),
  ],
);


class BudgetCard extends StatefulWidget 
final IconData icon;
final String name;
final double budgetBalance;
final double budgetAmount;
final double percentOfTotalBudget;
final double percentOfExpenses;
final Function(String) onPressed;

BudgetCard(this.icon, this.name, this.budgetBalance, this.budgetAmount, this.percentOfTotalBudget, this.percentOfExpenses, this.onPressed);

我的编辑告诉我“参数类型 'Future' 不能分配给参数类型 'double'。我到底如何将 Future 解析/转换为 double 以传递给 BudgetCard?

再次感谢。

【问题讨论】:

你必须调用函数和await它才能从Future获取double 这不是我在 getExpensePercentage(int budgetId) 方法中所做的吗? _totalExpenses = await... 而 _totalExpensesForBudget = await...? 在调用函数getExpensePercentage 时,您仍然需要awaitFuture 获取double 当你说我需要等待函数getExpensePercentage时,你的意思是:percentOfExpenses: await getExpensePercentage(_budgets[index].id);如果是这样,程序不允许这样做。 您需要这样做并分配给variable,然后再将其传递给percentOfExpenses 参数。 【参考方案1】:

您可以通过请求函数并将 then() 添加到函数的末尾来将未来值设置为 double 变量。

DbHelper.db.getTotalExpenses().then((value)=>
 _totalExpenses = value
)

这将使未来翻倍。

【讨论】:

以上是关于如何在 Flutter/Dart 中将 Future<double> 转换为 double?的主要内容,如果未能解决你的问题,请参考以下文章

在 Flutter(Dart)中将字符串解析为 DateTime [重复]

Flutter/Dart 中的 TDD。如何减少启动时间

如何在 Windows 上使用 dart-sdk (dart2native) 和 flutter/dart-sdk?

查询时如何在 Flutter (Dart) 中使用变量 Cloud Firestore

如何在视频/图像上添加图像或文本(水印) - Flutter/Dart

如何在 Flutter/Dart 中处理应用程序卸载?