Flutter - Do not use BuildContexts across async gaps

Viewed 2355

In my flutter Api, I have code like the following but lint 2.0.1 warns me at Navigator.pushnamed(context

Do not use BuildContext across async gaps

This SO has some information but I get an error that mounted is undefined if I try to use that solution. I can't figure out how to convert my Api class to a StatefulWidget as suggested by the answer below.

class Api {

Future<List<Author>> getAuthors(BuildContext context) async {
List<Author> authors = [];

try {
  final response = await _helper.get(context, "/authors");

  if (response.statusCode == 200) {
    var parsed = json.decode(response.body);

    if (parsed is List<dynamic>) {
      for (var author in parsed) {
        authors.add(Author.fromJson(author));
      }
    }
  } else {
    Navigator.pushNamed(context, RoutePaths.login);
    return authors;
  }
} catch (e) {
  return authors;
}

return authors;
}
}
1 Answers

Change to a StatefulWidget instead of a StatelessWidget. That will give you the mounted variable to use.

Edit:

Based on your comment and your first edits. You had left that piece of code (class Api) out of the question before. Now it shows some structural problems in your code. You are mixing ui code with your business logic. You are using BuildContext here, which comes from your widget!

Don't do the routing here. You shouldn't use the BuildContext in this class! I strongly advice against that. But if you want to, try and pass the mounted flag into this class from the widget calling this "Api-class", and see what happens. Yet again, I strongly advice against that.

Related