简体   繁体   中英

Do not use BuildContexts across async gaps - Flutter

I use SnackBar after, the await .

So, It's showing error like this:

Do not use BuildContexts across async gaps 

I used if (!mounted) this line to remove the error. It removed the problem but, SnackBar is not showing. When complete the task

My code here:

Future removeMethod() async {
    String res = await DatabaseMethods().idReject(widget.uid);
    if (res == "success") {
      if (!mounted) return;
      showSnackBar(context, "Job done!");
    } else {
      if (!mounted) return;
      showSnackBar(context, "Error!!");
    }
  }

showSnackBar is customWidget. code of it:

void showSnackBar(BuildContext context, String title) {
  final snackBar = SnackBar(
    content: CustomText(
      text: title,
      size: 16,
    ),
    backgroundColor: darkblueColor,
  );
  ScaffoldMessenger.of(context).showSnackBar(snackBar);
}

What can I do about this?. I want to show snackbar after await.

This basic example works based on your snippets. Here a snackbar is called after the result of a future is returned (eg a database call). If this helps?

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

class SnackBarAfterFutureResult extends StatelessWidget {
  const SnackBarAfterFutureResult({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: OutlinedButton(
            onPressed: () async {
              await removeMethod()
                  .then((value) => showSnackBar(context, value));
            },
            child: const Text('Database call')),
      ),
    );
  }
}

void showSnackBar(BuildContext context, bool result) {
  String text = "Job done!";
  if (!result) {
    text = "Error!!";
  }
  final snackBar = SnackBar(content: Text(text), backgroundColor: Colors.blue);
  ScaffoldMessenger.of(context).showSnackBar(snackBar);
}

Future<bool> removeMethod() async {
  //e.g. getting result from database call
  bool isSuccess = false;
  await Future.delayed(const Duration(seconds: 2), () {
    isSuccess = Random().nextBool();
  });
  return isSuccess;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM