Reputation: 11
I have class which is with
a ChangeNotifer. When I'm calling a method in this class i'd like a list view to be updated.
Here is the class:
class WorkoutProvider with ChangeNotifier
{
List<Exercise> _workoutList = <Exercise>[];
///constructor
WorkoutProvider();
///get&set
List<Exercise> get workout => _workoutList;
set workout(List<Exercise> value) {
_workoutList = value;
}
///removing an exercise to the list
void removeExercise(Exercise exercise)
{
_workoutList.remove(exercise);
print("deleting");
notifyListeners();
}
}
Here is the list view:
myPro = Provider.of<WorkoutProvider>(context);
body:Consumer<WorkoutProvider>(
builder: (BuildContext context, WorkoutProvider value, Widget? child)
{
print("building cons");
return ListView.builder(
padding: EdgeInsets.symmetric(horizontal: 30, vertical: 10),
itemCount: value.workout.length,
itemBuilder: (context, index) =>
Container(
margin: EdgeInsets.symmetric(vertical: 3),
child: exerciseCard(value.workout.elementAt(index))),
);
},
),
/// used to delete the exercise from the list of exercises
Widget buildDeleteExerciseBt(Exercise delExercise)
{
return IconButton(
onPressed: (){
myPro.removeExercise(delExercise);
},
icon: Icon(
Icons.delete,
color: Colors.red,
));
}
After checking, it is deleting the exercise from the class but the UI isn't get update.
Here is the registration of the provider:
Future<void> main() async {
GlobalContextService.navigatorKey = GlobalKey<NavigatorState>();
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(
MultiProvider(
providers: [
Provider<WorkoutProvider>(create: (_) => WorkoutProvider()),
],
child: MaterialApp(
debugShowCheckedModeBanner: false,
routes: {
'/' : (context) => AlreadyLoggedChecker(),
'/login-screen': (context) => LoginScreen(),
'/workout-review' : (context) => WorkoutReviewScreen(),
'/create-training' : (context) => TrainingCreateScreen(),
},
initialRoute: '/',
),
),
);
}
I tried to put some print(), and i so the consumer isn't build when the method which has the notifylistners() is called.
Upvotes: 0
Views: 36
Reputation: 11
Apparently, I should have used ChangeNotifierProvider
instead of Provider
, when registering the provider in main
.
Upvotes: 0