我从服务器获取一个int Id,该服务器在HTTP请求中波动,可以,并且我想将此值保存在变量中,但是当我调用返回的值时,我得到了这个错误'Future'的实例,有什么建议吗? 这是代码
child: RaisedButton(onPressed:() {
CurrentPrjId= SaveProject();
print("CurrentPrjId Is saved CurrentPrjId :::::::: " );
print(CurrentPrjId);
Navigator.of(context).pushReplacementNamed('/AllUSerStories');
}
//Save Project
Future SaveProject() async {
//SaveProjectResult has the id of the current created project which i need that for its user stories
var SaveProjectResult = await GetPostProjects().createProject(_ProjectnameController.text, _CustomernameController.text, _dropNewItem, _dropNewItem2, _StartDateController.text, _EndDateController.text,);
print(":::::::::::::::::::::::::::::::The Project Is Created And Here Its ID In SaveProject:::::::::");
print(SaveProjectResult);
return SaveProjectResult;
}
答案 0 :(得分:0)
没有代码,很难猜测,这是怎么回事。但是您可以尝试等待将来的完成。
methOdThatLoadsId().then((id) => print("Id that was loaded: $id"));
或
var id = await methodThatLoadsId();
祝你好运:)
答案 1 :(得分:0)
对不起,您的答复很晚。 不幸的是,您将等待添加到了错误的位置。 尝试这样的事情:
child: RaisedButton(onPressed:() async {
CurrentPrjId= await SaveProject();
print("CurrentPrjId Is saved CurrentPrjId :::::::: " );
print(CurrentPrjId);
Navigator.of(context).pushReplacementNamed('/AllUSerStories');
}
//Save Project
Future SaveProject() async {
//SaveProjectResult has the id of the current created project which i need that for its user stories
var SaveProjectResult = await GetPostProjects().createProject(_ProjectnameController.text, _CustomernameController.text, _dropNewItem, _dropNewItem2, _StartDateController.text, _EndDateController.text,);
print(":::::::::::::::::::::::::::::::The Project Is Created And Here Its ID In SaveProject:::::::::");
print(SaveProjectResult);
return SaveProjectResult;
或更短:
child: RaisedButton(onPressed:() async {
CurrentPrjId= await GetPostProjects().createProject(_ProjectnameController.text, _CustomernameController.text, _dropNewItem, _dropNewItem2, _StartDateController.text, _EndDateController.text,);
print("CurrentPrjId Is saved CurrentPrjId :::::::: " );
print(CurrentPrjId);
Navigator.of(context).pushReplacementNamed('/AllUSerStories');
}
答案 2 :(得分:0)
您必须使用FutureBuilder小部件从异步调用中获取Future值。
CurrentPrjId=FutureBuilder<String>(
future: SaveProject(),
builder: (context, snapshot) {
if (snapshot.hasData) return Text(snapshot.data);
else if (snapshot.hasError) return Text(snapshot.error);
return return Text("Await for data");
},
);