I’m using provider. The problem in the code below is that I can’t reload the API.
@override
void initState() {
super.initState();
getData(context);
}
Future<void> getData(BuildContext context) async {
final provider = Provider.of<AppDataProvider>(context, listen: false);
final userId = provider.userId;
await Future.wait([
getCourseView(context),
getCourseNew(context),
getAllCourses(context),
getRandomCourse(context),
getTrainer(context),
fetchTrainers(context, userId),
]);
}
Future<bool> checkInternetConnectivity() async {
var connectivityResult = await Connectivity().checkConnectivity();
return connectivityResult != ConnectivityResult.none;
}
void showNoConnectionSnackBar(BuildContext context) {
final snackBar = SnackBar(
content:const Text('No internet connection'),
duration:const Duration(seconds: 3),
);
ScaffoldMessenger.of(context).showSnackBar(snackBar);
}
Future<void> reloadPage() async {
await getData(context);
}
@override
Widget build(BuildContext context) {
//getData(context);
AppDataProvider appDataProvider = Provider.of<AppDataProvider>(context, listen: true);
var courseviews = appDataProvider.courseviews;
var courseadd = appDataProvider.courseadd;
var allCourses = appDataProvider.allCourses;
var randomcourse = appDataProvider.randomcourse;
var users = appDataProvider.users;
String? tpictureUrl = users.isNotEmpty && users[0].tpicture != null ? users[0].tpicture.toString() : null;
return Scaffold(
body: SafeArea(
child: RefreshIndicator(
onRefresh: reloadPage,
Reload page doesn’t work when I use provider to get data from API json file. I try to put setstate
, another method to reload API, but I think problem is in provider.
2
Answers
Wrap your widget with consumer
There are two ways to rebuild the widget or get the value.
Provider.of(context) or context.read()
context.read<TestProvider>()
returns the Model without listening for changes.context.watch<TestProvider>()
makes the widget listen for changes on the Model.Provider.of<TestProvider>(context, listen: false)
works the same ascontext.read<TestProvider>()
.Provider.of<TestProvider>(context)
works the same ascontext.watch<TestProvider>()
.Using Consumer for Specific Widget Rebuilds:
Consumer
.BuildContext
misuseIf it’s helpful to you, then accept the answer and don’t forget to upvote.