在下面的代码中,我正在制作一个登录屏幕,在其中进行 API 调用之后,因此在获取我想要导航到下一个屏幕的数据后,我正在从未来的构建器进行导航,但它不起作用。
所以,请帮忙。
futureBuilder<Album>(
future: userFuture,
builder: (ctx, snapshot) {
if (snapshot.hasData) {
isApiCall = false;
print("hasDat");
if (snapshot.data.errorMsg == "") {
_showToast(snapshot.data.errorMsg);
} else {
// I added this part to navigate screen, but it did not works
Navigator.of(context).push(MaterialPageRoute(builder: (context) => Home()));
//_showToast(snapshot.data.errorMsg);
//return Home();
if(snapshot.connectionState == ConnectionState.waiting){
return CircularProgressIndicator();
}
else{
navigateToNextScreen=true;
}
Navigator.of(context).push(MaterialPageRoute(builder: (context) => Home()));
//return Text(snapshot.data.errorMsg);
}
} else if (snapshot.hasError) {
}
return CircularProgressIndicator();
},
)),
触发 API 的按钮中的逻辑
onPressed: () {
setState(() {
isApiCall = true;
userFuture=_futureAlbum();
print(_futureAlbum);
});
},
下面是 statefull 小部件中的 future 对象,
Future<Album> userFuture;
@override
void initState() {
super.initState();
userFuture=_futureAlbum();
}
Future<Album>_futureAlbum()async{
if (isApiCall){
return await createAlbum("http://api/login01", {
'userPhoneNumber':
"91" + controller.text.toString(),
'userPassword':
_passwordController.text.toString()
});}
else{
return null;
}
}
以下是我的 API 的调用类和方法,它们被上述函数调用
class Album {
final String errorMsg ;
final Map success;
Album({this.errorMsg, this.success});
factory Album.fromJson(Map<String, dynamic> json) {
if (json.containsKey("error")){
print(json["error"]["errorMsg"]);
print("sfsdfdsdfsfd");
return Album(errorMsg:json["error"]["errorMsg"].toString());
}
else{return Album(success:json["success"]);}
}
}
Future<Album> createAlbum(String url, Map reqBody) async {
final Map success={};
final Map errorMsg={};
final Map res={};
final http.Response response = await http.post(
url,
headers: <String, String>{
'Content-Type': 'application/json',
},
body: jsonEncode(reqBody),
);
if (response.statusCode == 200) {
print(response.body);
Map<dynamic, dynamic>res = json.decode(response.body);
return Album.fromJson(json.decode(response.body));
} else {
throw Exception('Failed to create album.');
}
}