Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 247
Max Weber Avatar asked Apr 26 '20 11:04

Max Weber


2 Answers

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

like image 179
Maxim Saplin Avatar answered Sep 28 '22 01:09

Maxim Saplin


it seems to be solved using:

final textFormFieldFinder = find.byType(TextFormField);

instead of:

final textFormFieldFinder = find.byElementType(TextFormField);
like image 34
camillo777 Avatar answered Sep 28 '22 00:09

camillo777