在 flutter dart 中将 Future 转换为 int

2024-02-29

我在用sqflite https://pub.dev/packages/sqflite我通过以下代码获取特定记录的行数:

  Future<int> getNumberOfUsers() async {
    Database db = await database;
    final count = Sqflite.firstIntValue(
        await db.rawQuery('SELECT COUNT(*) FROM Users'));
    return count;
  }
  Future<int> getCount() async {
    DatabaseHelper helper = DatabaseHelper.instance;
    int counter = await helper.getNumberOfUsers();
    return counter;
  }

我想将此函数的结果放入 int 变量中以在内部使用它onPressed in FloatingActionButton

int count = getCount();
int countParse = int.parse(getCount());
    return Stack(
      children: <Widget>[
        Image.asset(
          kBackgroundImage,
          height: MediaQuery.of(context).size.height,
          width: MediaQuery.of(context).size.width,
          fit: BoxFit.cover,
        ),
        Scaffold(
          floatingActionButton: FloatingActionButton(
            backgroundColor: Colors.white,
            child: Icon(
              Icons.add,
              color: kButtonBorderColor,
              size: 30.0,
            ),
            onPressed: () {
              showModalBottomSheet(
                context: context,
                builder: (context) => AddScreen(
                  (String newTitle) {
                    setState(
                      () {
                        //--------------------------------------------
                        //I want to get the value here
                        int count = getCount();
                        int countParse = int.parse(getCount());
                        //--------------------------------------------
                        if (newTitle != null && newTitle.trim().isNotEmpty) {
                          _save(newTitle);
                        }
                      },
                    );
                  },
                ),
              );
            },
          ),

但我得到了这个例外:

“Future”类型的值不能分配给“int”类型的变量。


我通过为 OnPressed 添加异步解决了这个问题

onPressed: () async {...}

然后使用这行代码

int count = await getCount();

thx

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 flutter dart 中将 Future 转换为 int 的相关文章

随机推荐