0

I been reading multiple threads about passing data between futures, but for some reason I can get this to work.:(

I have two futures, where the first future is doing post request to retrieve a token

    Future<AuthStart> fetchAuthStart() async {
      final response = await http.post(
      Uri.parse('http://ipsum.com/auth/start'),
    body: jsonEncode(<String, String>{
      'IdNumber': '198805172387',
      
    }));

    if (response.statusCode == 200) {
      final responseJson = jsonDecode(response.body);
      return AuthStart.fromJson(responseJson);
    } else {
      throw Exception("Failed");
    }
  }

this request will generate an GUID that I need in my next future

 Future<AuthStatus> fetchAuthStatus(String token) async {
    final response = await http.post(Uri.parse('http://ipsum/auth/status'),
    body: jsonEncode(<String, String>{
      'Token':token,
    }),
    );

    if (response.statusCode == 200) {
      return AuthStatus.fromJson(jsonDecode(response.body));
    } else {
      throw Exception("Failed");
    }
  }

I have tried multiple ways, one that worked was to pass the variable in my FutureBuilder like this

FutureBuilder(
          future: futureAuthStart,
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              fetchAuthStatus(snapshot.data!.Token);
              return Text(snapshot.data!.Token);

            } else if (snapshot.hasError) {
              return Text('${snapshot.error}');
            }

            return const CircularProgressIndicator();
          },
        ),

But this does not make sense? I would rather pass it in my InitState something like this.

  void initState() {
    super.initState();
    futureAuthStart = fetchAuthStart();
    futureAuthStatus = fetchAuthStatus(token);
    
  }

Am I totally on the wrong path? Any tutorials out there that can give better info :)? Thanks in advance.

Dymond
  • 2,158
  • 7
  • 45
  • 80

1 Answers1

1

Create a void function and pass it the functions and one at a time it will be executed with async/await. You should take a look at Asynchronous programming: futures, async, await.

void initState() {
  super.initState();
  _onInit();
}


void _onInit() async {
  try {
    var futureAuthStart = await fetchAuthStart();
    var futureAuthStatus = await fetchAuthStatus(futureAuthStart.data.token);
  }catch(e, stackTrace){
    //handler error
    print(e);
    print(stackTrace);
  }
}
Chance
  • 1,497
  • 2
  • 15
  • 25
  • Thank you! I was following that tutorial but could really get it to be implemented. Now it actually works. Question though, the variable futureAuthStatus is giving me an warning that is not being used. I can of course ignore this. but is that good practice to ignore? Thanks again for the answer – Dymond Sep 27 '22 at 19:08
  • If you're not going to use remove, it's an unnecessary allocation. – Chance Sep 27 '22 at 20:34