I'm facing a warning of Do not use BuildContexts across async gaps.
Kindly tell me what is meant by this warning and why I'm facing this warning.
I couldn't resolve this warning from few days. Please help me on solving this warning.
class CategoryService extends ChangeNotifier {
List<Data> list = [];
showCategory(BuildContext context) async {
var connectivityResult = await (Connectivity().checkConnectivity());
if (connectivityResult == ConnectivityResult.mobile ||
connectivityResult == ConnectivityResult.wifi) {
Utils.showLoader(context); // facing warning on this line
ApiCall.getCategory().then((value) async {
if (value.statusCode == 200) {
if (json.decode(value.body)["success"] != null) {
if (json.decode(value.body)["success"]) {
CategoryModel categoryModel =
CategoryModel.fromJson(json.decode(value.body));
list.clear();
list.addAll(categoryModel.data ?? []);
notifyListeners();
Get.back();
notifyListeners();
} else {
Utils.flushBarErrorMessage(
json.decode(value.body)["en_message"], context);
Utils.hideLoader(context);
}
} else {
Utils.flushBarErrorMessage(
jsonDecode(value.body)["error"], context);
Utils.hideLoader(context);
}
} else {
Utils.flushBarErrorMessage('Invalid Data', context);
Utils.hideLoader(context);
}
}).catchError((onError) {
Utils.hideLoader(context);
log("my Error");
debugPrint(onError.toString());
});
} else {
Utils.hideLoader(context); // facing warning on this line
Utils.flushBarErrorMessage('No Internet', context); // facing warning on this line
}
}
}
EDITED
I'm using my showCategory
here in HomeScreen
class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key}) : super(key: key);
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
late CategoryService categoryService;
bool isCalled = false;
@override
Widget build(BuildContext context) {
if (!isCalled) {
isCalled = true;
categoryService = Provider.of<CategoryService>(context);
categoryService.showCategory(context);
}
return Scaffold(
appBar: AppBar(
title: const Text('Home'),
centerTitle: true,
),
body: Column(
children: [
const Align(
alignment: Alignment.centerLeft,
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 15),
child: Text('Category'),
),
),
const SizedBox(height: 10),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 15),
child: GridView.builder(
itemCount: categoryService.list.length,
shrinkWrap: true,
primary: false,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
crossAxisSpacing: 8,
mainAxisSpacing: 10,
),
itemBuilder: (context, index) => Center(
child: GridCategory(
category: categoryService.list[index],
),
),
),
),
const SizedBox(height: 20),
],
),
);
}
}