3

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;
}
}
markhorrocks
  • 1,199
  • 19
  • 82
  • 151
  • lots of dupes https://stackoverflow.com/questions/72505027/do-not-use-buildcontexts-across-async-gaps-after-update-pub-yaml-to-the-major-v – giorgio79 Sep 10 '22 at 12:06

1 Answers1

4

Update with Flutter 3.7.0

A StatefulWidget is no longer necessary. In a StatelessWidget you can now use context.mounted

Old answer

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.

Robert Sandberg
  • 6,832
  • 2
  • 12
  • 30
  • It is just a `Class Api`, not a widget. I have many similar functions in that class. – markhorrocks May 25 '22 at 02:33
  • 1
    Updated answer based on your comment and edits. – Robert Sandberg May 25 '22 at 04:15
  • If you need this, and there's no other way, you should create an interface/medium between UI and logic. This interface might be implemented by your StatefulWidget and sent to this `Api` class. Interface should be able to give you methods like `isMounted()`, `navigateTo(destination)`, etc. without accessing context in your logic. – rupinderjeet Aug 17 '22 at 03:21
  • `The getter 'mounted' isn't defined for the type 'BuildContext'` – Aseem Feb 25 '23 at 09:01