1

Flutter gives me the warning "Don't use 'BuildContext's across async gaps. Try rewriting the code to not use the 'BuildContext', or guard the use with a 'mounted' check". The warning is in my app twice and I can't make any of them go away by adding a "mounted guard". Below is a full standalone app that demonstrates a simple version of my app. Can you please show me what is the ideal way of solving this problem, and if it's the "mounted guard", where should I put them?

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Search History Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Search History'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            clearEnglishHistory(context);
          },
          child: const Text('Clear History'),
        ),
      ),
    );
  }

  Future<void> clearEnglishHistory(BuildContext context) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    bool confirmClear = await showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('Confirmation'),
          content: const Text('Do you really want to clear search history?'),
          actions: <Widget>[
            TextButton(
              onPressed: () {
                Navigator.of(context).pop(false);
              },
              child: const Text('No'),
            ),
            TextButton(
              onPressed: () {
                Navigator.of(context).pop(true);
              },
              child: const Text('Yes'),
            ),
          ],
        );
      },
    );

    if (confirmClear == true) {
      await prefs.remove('english history');
      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
        content: Text('History cleared'),
      ));
    }
  }
}

0

3 Answers 3

2

you need to either disable the message using lint message, or you can add a mounted check before you show your snackbar. Something like this:

if (confirmClear == true) {
      await prefs.remove('english history');
      if(!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
        content: Text('History cleared'),
      ));
    }

Sign up to request clarification or add additional context in comments.

2 Comments

In the code above when I did that it would say !mounted is undefined, but in my main app which complex and I have handled the snackbar in the exact way, there is no error, but doesn't also make the warnings go away. I also looked at all questions in the SO and none worked for me.
I also tried if (confirmClear == true && mounted) {, but the warnings still persist, even after restarting VScode to make sure the warnings weren't cached.
2

Devon Ray was almost right but it is a StatelessWidget so you have to write if(!context.mounted) return; instead of if(!mounted) return;

Comments

0

Others have answered where to add the mounted guard, but I wanted to point out that

await SharedPreferences.getInstance()

should really appear only in your main, saving the result into a global prefs var. Once you get the instance, you have the instance, and you can use it totally synchronously to get values as well. The only async you'll need to worry about then is the writing of new values, and even that can be fire-and-forget for the most part.

2 Comments

I really have no programming background (just a teacher making an educational app). I build the app by googling and courses. Would it be fine if I keep them? because when I tried to remove them, it made other errors I didn't know how to fix. Maybe until I get more experience, then I will in a few years fix them.
By the way, the other answers didn't solve my problem. Could you share your own?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.