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

13,304

Solution 1

addContact function has some operation which will return value when operation complete, so make a completion block here.....

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

Solution 2

Either use FutureBuilder or something like this

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

Solution 3

You can use FutureBuilder. Here is an example:

@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();
          }
        }
    );  
}
Share:
13,304
Ben Ghaleb
Author by

Ben Ghaleb

Updated on June 04, 2022

Comments

  • Ben Ghaleb
    Ben Ghaleb almost 2 years

    I'm trying to insert a row to a table in database using flutter framework and when I'm assigning the returned value to a new variable I get the following error message

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

    this is the function to insert new row

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

    and here where I'm getting the returned data

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