【问题标题】:How to fix a value of type future<int> can not be assigned to a variable of type int如何修复 future<int> 类型的值不能分配给 int 类型的变量
【发布时间】:2019-03-16 07:39:47
【问题描述】:

我正在尝试使用颤振框架在数据库中的表中插入一行,当我将返回的值分配给新变量时,我收到以下错误消息

 a value of type future<int> can not be assigned to a variable of type int

这是插入新行的函数

Future<int> addContact(String contact_name, String contact_phone) async {
    Database c = await getConnection;
    Map<String, dynamic> contact = getMap(contact_name, contact_phone);
    return await c.insert("contacts", contact);
  }

这里是我获取返回数据的地方

int result=db.addContact(name, phone);

【问题讨论】:

  • 可能是int result= await db.addContact(name, phone);?
  • @alexkucksdorf 不起作用,因为 awaitat 需要异步的方法,你不能修改 satefulWidget 类的构建函数
  • 异步具有传染性。您无法从异步返回到同步。调用者还需要async 关键字并使用await 来依赖在执行继续之前完成的异步代码。
  • 那么你应该使用FutureBuilter
  • @GünterZöchbauer 能否提供 FutureBuilder 教程的链接,我无法得到很好的解释

标签: dart flutter hybrid-mobile-app mobile-application


【解决方案1】:

addContact函数有一些操作,操作完成后会返回值,所以在这里做一个完成块.....

addContact(contact_name, contact_phone).then((value) {
  //this 'value' is in int
  //This is just like a completion block
});

【讨论】:

    【解决方案2】:

    使用FutureBuilder 或类似的东西

    int value; //should be state variable. As we want to refresh the view after we get data
    
    @override  
    Widget build(BuildContext context) {
      db.addContact(name, phone).then((value) {
           setState(() {this.value = value;});
      })
     return ....
    

    【讨论】:

      【解决方案3】:

      您可以使用FutureBuilder。这是一个例子:

      @override  
      Widget build(BuildContext context) {
          return new FutureBuilder (
              future: loadFuture(), //This is the method that returns your Future
              builder: (BuildContext context, AsyncSnapshot snapshot) {
                if (snapshot.hasData) {
                  if (snapshot.data) {               
                    return customBuild(context);  //Do stuff and build your screen from this method
                  }
                } else {
                  //While the future is loading, show a progressIndicator
                  return new CustomProgressIndicator();
                }
              }
          );  
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-12-03
        • 1970-01-01
        • 2020-09-09
        • 1970-01-01
        • 2021-08-29
        • 1970-01-01
        • 2023-01-20
        相关资源
        最近更新 更多