0

I want to find a proper solution for use_build_context_synchronously & I'm wondering if the code below is ok?

I'd like to know if I've just fooled flutter_lints or actually solved the issue.

BEFORE FIX:

class _HomeScreenState extends State<HomeScreen> {
  bool _isLoading = false;

  void _menuSelected(value) async {
    if (value == 'logout') {
      setState(() {
        _isLoading = true;
      });
      final uid = context.read<AuthProvider>().user?.uid ?? '';
      await Presence().updateUserPresence(uid);

      // lines in question
      await context.read<FCMProvider>().deleteCurrentDeviceToken(); // use_build_context_synchronously
      await context.read<AuthProvider>().signOut(); // use_build_context_synchronously

      setState(() {
        _isLoading = false;
      });
      return;
    }
    ...

AFTER FIX:

class _HomeScreenState extends State<HomeScreen> {
  bool _isLoading = false;

  // define methods
  late final Future<void> Function() deleteDeviceToken;
  late final Future<void> Function() signOut;

  @override
  void initState() {
    super.initState();

    // use context to extract methods from providers
    deleteDeviceToken = context.read<FCMProvider>().deleteCurrentDeviceToken;
    signOut = context.read<AuthProvider>().signOut;
  }

  void _menuSelected(value) async {
    if (value == 'logout') {
      setState(() {
        _isLoading = true;
      });
      final uid = context.read<AuthProvider>().user?.uid ?? '';
      await Presence().updateUserPresence(uid);

      // use the extracted methods
      await deleteDeviceToken();
      await signOut();

      setState(() {
        _isLoading = false;
      });
      return;
    }
    ...

This way I've extracted the methods before using them, but I'm not sure if this maybe still uses context where it shouldn't be used.

IvanTheDevil
  • 1
  • 1
  • 1

1 Answers1

0

There are two good options to fix the issue depending on what you want. What you did is best if you still want to sign out even if your widget has been disposed and removed from the tree. On the other hand, if performing the sign out action makes no sense if the user has switched to a different route that does not contain your widget then you should just skip performing the signout action if your state is unmounted.