我想从数据库中获取数据。我有2个api 1:获取记录信息,如姓名,地址,公司等。另一个api 2:获取ProfilePhoto。我从第一个api获得输出,但无法获得profilePhoto api。那么我如何在一个函数中调用这两个api呢?函数是
Future<DataDetails> getData1() async {
var id = 34;
final response1 = await http.get(Uri.parse("Api Url"));
if(response1.statusCode == 200) {
var temp = DataDetails.fromJson(jsonDecode(response1.body));
print(temp);
return temp;
}
return DataDetails.fromJson(jsonDecode(response1.body)) ;
}
FutureBuilder(
future: getData(),
builder: (context, snapshot) {
return Screenshot(
controller: _ssController,
child: GestureDetector(
onTap: () {
Navigator.push(context, MaterialPageRoute(builder: (context) => OntapView()));
},
child: Stack(
children: [
Container(
padding: const EdgeInsets.all(10),
width: 350,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
// color: Colors.amber[100]
color: const Color(0xffccf7ff)
),
child: Column(
children: [
Container(
padding: EdgeInsets.all(10),
child: Row(
children: [
Container(
height: 15,
width: 200,
child: Text('${snapshot.data!.cardName} ',
style: TextStyle(fontWeight: FontWeight.bold),),
),
SizedBox(height: 8),
Row(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: [
CircleAvatar(
radius: 45,
backgroundColor: Colors.grey,
backgroundImage: FileImage(File('${snapshot.data!.profilePhotoPath}')),
),
const SizedBox(width: 10),
Container(
padding: const EdgeInsets.only(left: 20,top: 10),
width: 130,
height: 100,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Text('${snapshot.data!.name} ',
style: const TextStyle(fontSize: 22,fontWeight: FontWeight.bold),),
const SizedBox(height: 5),
Container(
child: Text('${snapshot.data!.address}',
style: const TextStyle(fontSize: 12),),
)
],
)
),
我是新手。如果可能,请分享示例代码。
我不确定我是否理解正确,但如果你需要调用另一个API(我猜"ProfilePhoto"),你不应该放任何"返回"在调用API之前,因为"返回temp"and "返回DataDetails.fromJson(jsonDecode(response1.body));"将停止您的下列功能。如果对API的第一次调用是:
final response1 = await http.get(Uri.parse("Api Url"));
这意味着你也应该返回这个响应。
应该是这样的:
Future<DataDetails> getData1() async {
var id = 34;
// Call first api ?
final response1 = await http.get(Uri.parse("Api Url"));
if(response1.statusCode == 200) {
// Call second API ?
var temp = DataDetails.fromJson(jsonDecode(response1.body));
print(temp);
// return both of variable
return [temp, response1];
} else {
return error;
}
还有,打印出来可以吗?您还可以执行打印操作来查看response1的样子,以了解statusCode是否为200