【发布时间】:2022-01-11 11:00:06
【问题描述】:
在 Future Builder 中,我尝试使用两种不同类型的方法,它们都从 api 获取数据,
我遇到的主要问题是这两个函数都有不同的类型,所以我在放置时遇到了问题
这两种方法是因为它们的类型。我尝试使用
Future.wait(Future[]) 也是如此,但我遇到了很多错误,这些错误主要在 List 上,
我仍在尝试了解 Future Builders 的工作原理,我之前使用过 FutureBuilders,但不必在 FutureBuilder 中使用两个函数。因此,如果有人可以在我的代码上实现他们的解决方案,那将真的很有帮助,并且可能会添加一些关于您为什么要进行更改的 cmets,以便我为未来学习。作为奖励,我得到 List 也不是类型 Map
buildSwipeButton() {
return MenuPage( // other class name from a different file
sendData: fetchLoginData(),
);
}
buildSwipeButton2() {
return MenuPage( // other class name from a different file
sendData2: fetchWorkingLocationData(),
);
}
Future<LoginData>? fetchLoginData() async {
var url = 'https://dev.api.wurk.skyver.co/api/employees';
String basicAuth = 'Basic ' +
base64Encode(
utf8.encode('${emailController.text}:${passwordController.text}'),
);
var response = await http.get(
Uri.parse(url),
headers: <String, String>{'authorization': basicAuth},
);
print(response.body);
if (response.statusCode == 200) {
print(response.statusCode);
return LoginData.fromJson(
jsonDecode(response.body),
);
} else {
throw Exception('Failed to load LoginData');
}
}
Future<WorkingLocationData>? fetchWorkingLocationData() async {
var url = 'https://dev.api.wurk.skyver.co/api/locations';
String basicAuth = 'Basic ' +
base64Encode(
utf8.encode('${emailController.text}:${passwordController.text}'),
);
var response2 = await http.get(
Uri.parse(url),
headers: <String, String>{'authorization': basicAuth},
);
print(response2.body);
if (response2.statusCode == 200) {
print(response2.statusCode);
return WorkingLocationData.fromJson(
jsonDecode(response2.body),
);
} else {
throw Exception('Failed to load Working Location Data');
}
}
// other file where im trying to use Future Builder
late LoginData data;
Future<LoginData>? sendData;
Future<WorkingLocationData>? sendData2;
body: FutureBuilder<LoginData>(
future: sendData, // trying to use sendData and sendData2
builder: (context, snapshot) {
if (snapshot.hasData) {
LoginData? data1 = snapshot.data;
data = data1!;
print(data.loginPhoneNumber);
return afterLoginBody();
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
return Center(child: const CircularProgressIndicator());
},
),
),
【问题讨论】:
标签: flutter dart flutter-layout flutter-dependencies