【问题标题】:Is it possible to access children/parent widgets from a given widget, in a Flutter test?在 Flutter 测试中是否可以从给定的小部件访问子/父小部件?
【发布时间】:2018-04-28 00:13:36
【问题描述】:

我正在为 Flutter 编写单元和集成测试。是否可以从给定的小部件访问子/父小部件?

【问题讨论】:

    标签: dart flutter flutter-test


    【解决方案1】:

    是的,您可以使用find.descendantElement.ancestorWidgetOfExactType

    例子:

    // Finds a RichText widget that a descendant (child/grand-child/etc) of a
    // tab widget with text "Tab 1"
    find.descendant(of: find.text('Tab 1'), matching: find.byType(RichText));
    
    // Finds a parent widget of type MyParentWidget.
    tester.element(find.byType(MyChildWidget))
      .ancestorWidgetOfExactType(MyParentWidget);
    

    【讨论】:

      【解决方案2】:

      ancestorWidgetOfExactType 已弃用,建议使用findAncestorWidgetOfExactType

      【讨论】:

        【解决方案3】:
        // Parent with a child & grand child
        class ParentWidget extends StatelessWidget {
          
          @override
          Widget build(BuildContext context) {
            return ChildWidget(
              child: GrandChildWidget(),
            );
          }
        }
        
        // Tests
        void main() {
          testWidgets('parent, child & grand-child hierarchy', (WidgetTester tester) async {
            Widget parentWidget = ParentWidget();
            await tester.pumpWidget(parentWidget);
            
            final childFinder = find.descendant(of: find.byWidget(parentWidget), matching: find.byType(ChildWidget));
            expect(childFinder, findsOneWidget);
            
            final grandChildFinder = find.descendant(of: find.byWidget(parentWidget), matching: find.byType(GrandChildWidget));
            expect(grandChildFinder, findsOneWidget);
            
            final parentFinder = find.ancestor(of: find.byWidget(childWidget), matching: find.byType(ParentWidget));
            expect(parentFinder, findsOneWidget);
          });
        }
        

        Flutter 文档 - descendant & ancestor

        【讨论】:

          猜你喜欢
          • 2022-01-04
          • 2019-06-26
          • 1970-01-01
          • 2021-05-09
          • 2020-01-29
          • 2021-08-02
          • 2019-02-25
          • 2019-05-23
          • 2021-05-04
          相关资源
          最近更新 更多