title: Logout based on unauthorized API response
body: <p>I have created Rest API helper like this.</p>
  <pre class="lang-dart prettyprint-override"><code>class Api {
    final String _url = baseUrl + &quot;api/&quot;;
  
    _logout() async {
      // EXIT ALL ONGOING PROCESSES HERE &amp; NAVIGATE TO LOGOUT SCREEN
      await navigatorKey.currentState.pushReplacement(
        MaterialPageRoute(
          builder: (context) =&gt; Login(),
        ),
      );
  
      return {'success': false, 'error': 'Authentication failed!'};
    }
  
    Future get(url) async {
      // Getting token from sharedprefs
      String token = Prefs.prefs.getString(&quot;token&quot;);
  
      // Set authorization header
      Map&lt;String, String&gt; headers = {
          'accept': 'application/json',
          'authorization': 'Bearer ' + token;
      };
  
      return await http.get(_url + url, headers: headers).then((response) {
        if (response.statusCode == 200) {
          // Valid response
          return convert.jsonDecode(response.body);
        } else {
          // 401 Status code
          return _logout();
        }
      });
    }
  }
  </code></pre>
  <p>Then in screen/view, I am calling APIs like this.</p>
  <pre class="lang-dart prettyprint-override"><code>@override
  void initState() {
    super.initState();
  
    Api().get('getdata').then((response) {
        setState(() {
          _data = response;
        })
    });
  }
  </code></pre>
  <h3>For Valid/Un-Expired API Token</h3>
  <p>For successful api response, fetched data will be updated in view using setstate method. It's working perfectly fine.</p>
  <h3>For Invalid/Expired API Token</h3>
  <p>For invalid token, API will give 401 status code &amp; API helper will navigate to Login screen using _logout() function.</p>
  <p>Here, it's not working as expected. Here app pushed to loginscreen, but then it gives me error like this.</p>
  <blockquote>
  <p>This error happens if you call setState() on a State object for a widget that no longer appears in the widget tree (e.g., whose parent widget no longer includes the widget in its build). This error can occur when code calls setState() from a timer or an animation callback. The preferred solution is to cancel the timer or stop listening to the animation in the dispose() callback. Another solution is to check the &quot;mounted&quot; property of this object before calling setState() to ensure the object is still in the tree.</p>
  </blockquote>
  <h1>My question is,</h1>
  <p>Is this correct way to do logout based on REST API response?</p>
  <h1>Edit:</h1>
  <p>In simple terms, I want to logout whenever I get unauthorized response in REST API helper.</p>
  <p>Also without API helper, writing if-else statement manually for every single place is not feasible.</p>