Flutter take action based on snapshot of Future. You can check for a statusCode inside your Async method, and use setState to erase the value of the token based on the statusCode value; otherwise, if the connection is authorized, return your desired data. Now, in your FutureBuilder , check if the you snapshot is null to show a SignIn() page instead.
For example, your method that handles the http requests might look something like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
_Request() async { var httpClinet = createHttpClient(); var response = await httpClinet.get( url, headers: {'Authorization': "Bearer $_currentUserToken"}); if (response.statusCode == 200) { var myRequest = JSON.decode(response.body); var myDesiredData; ///TODO: Some data conversions and data extraction return myDesiredData; } else { setState(() { _currentUserToken = null; }); return null; } } |
Then you can have a FutureBuilder like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
@override Widget build(BuildContext context) { return new FutureBuilder( future: _request(), builder: (BuildContext context, AsyncSnapshot response) { response.hasData==false? new SignIn(): new Scaffold( appBar: new AppBar(title: new Text("Future Builder"),), body: new Center( child: new Text("Build your widgets"), ), ); }, ); } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.