init_state_test.dart 1.21 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
Ian Hickson's avatar
Ian Hickson committed
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

Adam Barth's avatar
Adam Barth committed
5
import 'package:flutter_test/flutter_test.dart';
Ian Hickson's avatar
Ian Hickson committed
6 7 8 9
import 'package:flutter/widgets.dart';

List<String> ancestors = <String>[];

10
class TestWidget extends StatefulWidget {
11
  const TestWidget({ Key? key }) : super(key: key);
12
  @override
13
  TestWidgetState createState() => TestWidgetState();
Ian Hickson's avatar
Ian Hickson committed
14 15
}

16
class TestWidgetState extends State<TestWidget> {
17
  @override
Ian Hickson's avatar
Ian Hickson committed
18 19 20 21 22 23 24 25
  void initState() {
    super.initState();
    context.visitAncestorElements((Element element) {
      ancestors.add(element.widget.runtimeType.toString());
      return true;
    });
  }

26
  @override
27
  Widget build(BuildContext context) => Container();
Ian Hickson's avatar
Ian Hickson committed
28 29 30
}

void main() {
31
  testWidgets('initState() is called when we are in the tree', (WidgetTester tester) async {
32 33
    await tester.pumpWidget(const Parent(child: TestWidget()));
    expect(ancestors, equals(<String>['Parent', 'RenderObjectToWidgetAdapter<RenderBox>']));
Ian Hickson's avatar
Ian Hickson committed
34 35
  });
}
36 37 38 39 40 41 42 43 44

class Parent extends StatelessWidget {
  const Parent({ Key? key, required this.child }) : super(key: key);

  final Widget child;

  @override
  Widget build(BuildContext context) => child;
}