Flutter Changenotifier provider getting disposed after closing and opening of bottom model sheet

437 Views Asked by At

In my Flutter app, I have this ChangeNotifier provider. On the homepage a ChangeNotifier is created.

ChangeNotifierProvider<UserTeam>(create: (_) => UserTeam()),

I am setting the value for this provider on button press using this code below.

late UserTeam _userTeam;
_userTeam = Provider.of<UserTeam>(context);
UserTeam _userTeam = UserTeam(userDetails: test, pageDetails: 3);
_userTeam.setUserTeam(_userTeam);

I am passing this ChangeNotifier provider to the bottom sheet.

showModalBottomSheet<dynamic>(
          isScrollControlled: true,
          shape: const RoundedRectangleBorder(borderRadius: BorderRadius.only(topLeft: Radius.circular(30), topRight: Radius.circular(30))),
          backgroundColor: const Color(0xFFFFFFFF),
          context: context,
          builder: (BuildContext context2) {
            return BlocProvider.value(
              value: BlocProvider.of<AuthenticationBloc>(context),
              child: BlocProvider.value(
                value: BlocProvider.of<AuthBloc>(context),
                child: MultiProvider(
                  providers: [
                    ChangeNotifierProvider<UserTeam?>(create: (_) => _userTeam),
                  ],
                  child: StatefulBuilder(builder: (BuildContext context, StateSetter mystate) {
                    return SingleChildScrollView(
                      child: SizedBox(
                        height: MediaQuery.of(context).size.height - 50,
                        width: MediaQuery.of(context).size.width,
                        child: const teamSearch(),
                      ),
                    );
                  }),
                ),
              ),
            );
          });

When opening the bottom model sheet for first time, ChangeNotifier UserTeam is available. After closing and opening it's getting disposed and throwing an error as this code shows below.

Another exception was thrown: A UserTeam was used after being disposed.

Please help me with this.

1

There are 1 best solutions below

5
Usama Karim On

The code is confusing Provider on which variable to use, please change variable names

final userTeam = Provider.of<UserTeam>(context);
UserTeam _userTeam = UserTeam(userDetails: 'test, pageDetails: 3);
userTeam.setUserTeam(_userTeam);

Rather than creating a whole new Provider later in showModalBottomSheet create a value provider

ChangeNotifierProvider.value<UserTeam?>(value: _userTeam),