Home > Software design >  Pass token between future classes in flutter
Pass token between future classes in flutter

Time:09-28

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.

CodePudding user response:

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);
  }
}
  • Related