首页 > 解决方案 > Flutter 使用 showDialog 时如何测试 WillPopScope

问题描述

我目前有一个 WillPopScore 小部件,单击后退按钮时会出现一个对话框

class MainView extends StatelessWidget {
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        if (showPopup) {
          return showDialog(
            context: context,
            builder: (context) => new AlertDialog(
              title: Text('Are you sure?'),
              actions: <Widget>[
                FlatButton(
                  child: Text('No'),
                  onPressed: () {
                    Navigator.of(context).pop(false);
                  },
                ),
                FlatButton(
                  child: Text('Yes'),
                  onPressed: () {
                    Navigator.of(context).pop(true);
                  },
                ),
              ],
            ),
          );
        }

        return Future.value(true);
      },
    );
  }
}

这是我的测试:

testWidgets('Should open confirm dialog after clicking back',
      (WidgetTester tester) async {

    await tester.pumpWidget(MainView());

    final dynamic widgetsAppState = tester.state(find.byType(WidgetsApp));
    await widgetsAppState.didPopRoute();
    await tester.pump();

    expect(find.text('Are you sure?'), findsOneWidget);
  });

问题是,我的测试挂起,await widgetsAppState.didPopRoute();因为我正在返回showDialog()而不是falseshowPopup 为真时返回。是否可以在测试期间不添加标志的情况下使其工作?

标签: flutter

解决方案


推荐阅读