Max Weber
Max Weber

Reputation: 1088

Cannot find Widgets in test inside of Consumer Widget of Provider

I created the following Flutter test for my widget

testWidgets("", (WidgetTester tester) async {
      await tester.pumpWidget(
        ChangeNotifierProvider<SettingsViewProvider>(
          create: (context) => SettingsViewProvider(),
          child: MaterialApp(
            localizationsDelegates: [S.delegate],
            home: SettingsScreen(),
          ),
        ),
      );

      final textFormFieldFinder = find.byElementType(TextFormField);
      await tester.pump();
      expect(textFormFieldFinder, findsNWidgets(3));
    });

The widget is a stateful widget which uses a ChangeNotifierProvider and the Consumer surrounds a List of three "TextFormFields".

Consumer<State>(
   builder: (context, value, child)=> Column(
       children: [TextFormField(...), TextFormField(...), TextFormField(...)];
   )
)

Expected: exactly 3 matching nodes in the widget tree

Actual: _ElementTypeFinder:

Which: means none were found but some were expected

Unfortunatly I receive that no widget is found in the widget tree.

Upvotes: 11

Views: 2846

Answers (2)

Maxim Saplin
Maxim Saplin

Reputation: 4652

As pointed out before, you should be using find.byType which is aimed at seaching Widgets rather than find.byElementType which deals with Elements.

Flutter has 3 UI building blocks:

Widgets (immutable) -> Elements (mutable) -> Render Objects -- they are not inherited from one another, those are separate types of objects with different purposes.

TextFormField is a Widget, while it is being passed to find.byElementType which expects an ancestor of Element

Upvotes: 14

camillo777
camillo777

Reputation: 2377

it seems to be solved using:

final textFormFieldFinder = find.byType(TextFormField);

instead of:

final textFormFieldFinder = find.byElementType(TextFormField);

Upvotes: 8

Related Questions