Error "Could not find the correct Provider<AppThemeNotifier> above this Consumer<AppThemeNotifier>"

Issue

I’m currently working on a Flutter app and I have some issue to write tests.

When I run my test I have the following exception :
"The following ProviderNotFoundException was thrown building Consumer(dirty):
Error: Could not find the correct Provider above this Consumer
Widget"

This is a piece of my main.dart

Widget build(BuildContext context) {
    themeData = Theme.of(context);
    return Consumer<AppThemeNotifier>(
      builder: (BuildContext context, AppThemeNotifier value, Widget? child) {
        customAppTheme = AppTheme.getCustomAppTheme(value.themeMode());
        return MultiBlocProvider(
            providers: [
              BlocProvider<AuthentificationBloc>(
                create: (context) => AuthentificationBloc(),
              ),
              BlocProvider<RegisterBloc>(
                create: (context) => RegisterBloc(),
              ),
              BlocProvider<EventsBloc>(
                create: (context) => EventsBloc(),
              ),
              BlocProvider<UsersBloc>(
                create: (context) => UsersBloc(),
              ),
            ],

And this is the test that I try to run

void main() {

Widget skeleton(widgetToTest)
{
  return Consumer<AppThemeNotifier>(
      builder: (BuildContext context, AppThemeNotifier value, Widget? child) {
        return widgetToTest;
      });

}

  testWidgets('My login page contains two textfield to enter my credentials',
      (WidgetTester tester) async {
    await tester.pumpWidget(skeleton(Login2Screen()));

    final textFormFieldFinder = find.byElementType(TextFormField);

    expect(textFormFieldFinder, findsNWidgets(2));

  });
}

I tried to create the "skeleton" function to add the Provider but it doesn’t work…

Any help is really appreciate 🙂

Solution

You need to load AppThemeNotifier via ChangeNotifierProvider or any other suitable provider.

await tester.pumpWidget(
  ChangeNotifierProvider<AppThemeProvider>(
    create: (context) => AppThemeProvider(),
    child: skeleton(Login2Screen()),
  ),
);

Answered By – Tirth Patel

Answer Checked By – Terry (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *