在Flutter Dart中将Future<int>转换为int

8

我正在使用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变量中,以便在FloatingActionButton 中的onPressed函数中使用。

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”类型的变量。


1
看起来你已经知道如何使用 await 关键字了。你能解释一下为什么在这里它不够用吗? - nvoigt
这个回答解决了你的问题吗?如何在Flutter中从Future对象(Future<int>)获取原始值? - nvoigt
1
要么使用FutureBuilder,要么使用await关键字来获取Future的值。 - Augustin R
@nvoigt 这行代码会导致异常:int count = getCount(); 我想要将值作为整数获取,然后检查它是否不大于100。 - Huda
我知道你想要什么。但是你在发布的代码中已经使用了3次将Future<T>解析为T的方法,为什么现在这还不够好呢?为什么不能再用一次呢? - nvoigt
4个回答

10
我通过为OnPressed添加async来解决了这个问题。
onPressed: () async {...}

然后使用这行代码

int count = await getCount();

谢谢


2

你所需要做的就是在调用Future之前设置关键字"await":

您要做的事情:

int count = getCount(); 

哪个是正确的:

int count = await getCount();

2

使用await来获取Future的响应

int number = await getNumberOfUsers();

int count = await getCount();

1
you need to add the "await" keyword before calling the function

int count = await getCount();


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接