0

我必须进行多次 API 调用才能获取实际数据。我编写了以下代码来进行第一个 API 调用。它有效,但我必须使用第一次调用的返回值(假设它返回访问令牌),并将此访问令牌用作第二个 API 调用的标头的一部分。我怎样才能做到这一点?

class Service {
  final String url;
  Map<String, String> header = new Map();
  Map<String, String> body = new Map();

  Service(this.url, this.header, this.body);

  Future<Data> postCall() async {    
    final response = await http.post(url, headers: header, body: body);
    return Data.fromJson(json.decode(response.body));
  }
}




class MyApp extends StatelessWidget {
  Service service;
  Service serviceTwo;
  ....
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
      body: Center(
        child: FutureBuilder<Data>(
          future: service.postCall,
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              return Text(snapshot.data.accessToken);
            } else if (snapshot.hasError) {
              return Text("${snapshot.error}");
           }
          // By default, show a loading spinner.
          return CircularProgressIndicator();
        },
      ),
    ),
  ),
);}}
4

1 回答 1

1

有很多方法可以实现这一点,最简单的一种是在您的方法上使用await来附加未来的调用。

所以你的方法postCall()是这样的:

Future<Data> postCall() async {
  // The first call, suppose you'll get the token
  final responseToken = await http.post(url, headers: header, body: body);

  // Decode it as you wish
  final token = json.decode(responseToken.body);
  
  // The second call to get data with the token
  final response = await http.get(
    url,
    headers: {authorization: "Bearer $token"},
  );

  // Decode your data and return
  return Data.fromJson(json.decode(response.body));
}

如果它是一个你会多次使用的令牌,我建议你将它存储在flutter_secure_storage中并根据需要使用它。

于 2019-06-12T14:53:04.150 回答