如何固定类型为future <int>的值不能分配给类型为int的变量

时间:2018-10-11 09:12:59

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

我试图使用flutter框架在数据库中的表中插入一行,当我将返回值分配给新变量时,出现以下错误消息

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

3 个答案:

答案 0 :(得分:1)

您可以使用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();
          }
        }
    );  
}

答案 1 :(得分:0)

使用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 ....

答案 2 :(得分:0)

addContact函数具有一些操作,该操作将在操作完成时返回值,因此请在此处创建一个完成块。.

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