集成测试flutter期间无法通过按键访问小部件

问题描述 投票:0回答:1
class LandingScreen extends StatefulWidget {
  const LandingScreen({super.key});

  @override
  _LandingScreenState createState() => _LandingScreenState();
}

class _LandingScreenState extends State<LandingScreen> {
  String marqueeText = Constants.DUMMY_TEXT;

  @override
  Widget build(BuildContext context) {
    var deviceWidth = MediaQuery.of(context).size.width;
    var deviceHeight = MediaQuery.of(context).size.height;
    Widget individualGridItem(
        {required Key? key,
        required String img,
        required String name,
        String? url}) {
      return GestureDetector(
        onTap: () async {
          selectedIcon.value = name;
          print('ss: ${AuthPrefs.userLoggedIn(null, name)}++++$name');
          if (url != null) {
            Navigator.of(context).push(MaterialPageRoute(
                builder: (BuildContext context) => CustomWebView(
                      title: name,
                      url: url,
                    )));
          } else {
            AuthPrefs.userLoggedIn(null, name) == true
                ? Navigator.pushNamed(context, HomeScreen.routeName)
                : Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) =>
                          LoginScreen(imageAsset: img, pageName: name),
                    ),
                  );
          }
        },
        child: Card(
          elevation: 8.0,
          borderOnForeground: true,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: <Widget>[
              Hero(
                tag: img,
                child: Image.asset(
                  img,
                  width: 75,
                  height: 75,
                ),
              ),
              Text(
                name,
                style: const TextStyle(
                    fontWeight: FontWeight.bold, fontSize: 14.0),
              )
            ],
          ),
        ),
      );
    }

    List<Widget> gridItems() {
      return [
        individualGridItem(
            key: Key('carKey'),
            img: ImageConstants.carImg,
            name: context.tr("car")),
        individualGridItem(
            img: ImageConstants.busImg,
            name: context.tr("school_bus"),
            key: Key('schoolBusKey')),
        individualGridItem(
            img: ImageConstants.famImg,
            name: context.tr("family"),
            key: Key('familyKey')),
        individualGridItem(
            img: ImageConstants.empImg,
            name: context.tr("employee"),
            key: Key('employeeKey')),
        individualGridItem(
            img: ImageConstants.localBusImg,
            name: context.tr("local_bus"),
            url: ApiConstants.localBusUrl,
            key: Key('localBusKey')),
        individualGridItem(
            img: ImageConstants.technoSalesLogo,
            name: context.tr("mt"),
            url: ApiConstants.mtUrl,
            key: Key('mtKey')),
      ];
    }

    Widget individualBannerItem(
        {required String img, required Function onClick}) {
      return GestureDetector(
        onTap: () => onClick,
        child: Card(
          borderOnForeground: true,
          color: Colors.transparent,
          elevation: 20,
          child: ClipRRect(
              borderRadius: BorderRadius.circular(5.0),
              child: SizedBox(
                width: deviceWidth / 1.2,
                height: deviceHeight * 0.21,
                child: img.contains("http")
                    ? Image.network(img, fit: BoxFit.fill)
                    : Image.asset(
                        img,
                        fit: BoxFit.fill,
                      ),
              )),
        ),
      );
    }

    tempClick() {
      if (Platform.isIOS) {
        Utilities.demoShowDialog(
            title: "Information",
            body:
                "Int test test",
            context: context);
      } else {
      }
    }

    List<Widget> bannerItems() {
      return [
        individualBannerItem(
            img: ImageConstants.banner,
            onClick: () {
              tempClick();
            }),
        individualBannerItem(
            img:
                "http://www.gpsnepal.com.np/wp-content/uploads/2017/04/Untitledfddc.gif",
            onClick: () {
              tempClick();
            }),
      ];
    }

    Widget bannerSlider = Positioned(
        top: deviceHeight / 11,
        left: deviceWidth / 12.5,
        child: Container(
          color: Colors.transparent,
          width: deviceWidth / 1.2,
          child: CarouselSlider(
            items: bannerItems(),
            options: CarouselOptions(
                height: deviceHeight * 0.21,
                aspectRatio: 16 / 9,
                viewportFraction: 1.0,
                initialPage: 0,
                enableInfiniteScroll: true,
                reverse: false,
                autoPlay: true,
                autoPlayInterval: const Duration(seconds: 5),
                autoPlayAnimationDuration: const Duration(milliseconds: 800),
                autoPlayCurve: Curves.easeInCubic,
                pauseAutoPlayOnTouch: true,
                scrollDirection: Axis.horizontal),
          ),
        ));
    var logo = Positioned(
      top: deviceHeight / 50,
      left: deviceWidth / 40,
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          CircleAvatar(
              backgroundImage: AssetImage(ImageConstants.gpsLogo), radius: 16),
          SizedBox(
            width: deviceWidth * 0.05,
          ),
          const Text(
            appTitle,
            style: TextStyle(
                color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold),
          ),
        ],
      ),
    );
    var infoButton = Positioned(
      top: deviceHeight / 70,
      right: deviceWidth / 40,
      child: Hero(
        tag: 'info',
        child: Material(
          color: Colors.transparent,
          child: IconButton(
            icon: Icon(
              Icons.info,
              size: deviceHeight * 0.05,
              color: Colors.white,
            ),
            onPressed: () {
              Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => CompanyInfoScreen()),
              );
            },
          ),
        ),
      ),
    );
    var marqueeContainer = Container(
      height: deviceHeight * 0.04,
      color: Theme.of(context).primaryColor,
      child: Marquee(
        text: marqueeText,
        blankSpace: 5,
        style: const TextStyle(color: Colors.white, fontSize: 15.0),
        velocity: 30,
      ),
    );
    var menuGrid = SizedBox(
      width: deviceWidth,
      height: deviceHeight / 1.66,
      child: GridView.count(
        childAspectRatio: 16 / 11.5,
        addAutomaticKeepAlives: true,
        addRepaintBoundaries: true,
        padding: const EdgeInsets.all(20.0),
        mainAxisSpacing: 12,
        crossAxisSpacing: 25,
        crossAxisCount: 2,
        children: gridItems(),
      ),
    );
    return SafeArea(
      child: Scaffold(
        body: Stack(
          children: <Widget>[
            SingleChildScrollView(
              child: Column(
                children: <Widget>[
                  Container(
                    width: double.infinity,
                    height: deviceHeight * 0.24,
                    color: Theme.of(context).primaryColor,
                  ),
                  SizedBox(
                    height: deviceHeight * 0.08,
                  ),
                  marqueeContainer,
                  Sizing.smallHeight,
                  CustomLargeText(
                      text: "Version: $appVersion", color: Colors.black),
                  menuGrid,
                ],
              ),
            ),
            bannerSlider,
            logo,
            infoButton,
          ],
        ),
      ),
    );
  }
}

//这是integration_test文件:

void main() {
  IntegrationTestWidgetsFlutterBinding.ensureInitialized();

  testWidgets("On entering wrong username for GPS tracking of private car",
      (tester) async {
    app.main();
    await Future.delayed(const Duration(seconds: 1));
    await tester.tap(find.byKey(Key('carKey')));
    await Future.delayed(const Duration(seconds: 2));
    expect(find.byType(LoginScreen), findsOneWidget);
  });
}

收到错误:
══╡ Flutter测试框架捕获异常╞══════════════════════════════ ══════════ ════════════

运行测试时抛出以下断言:

查找器“Found 0 widgets with key [<'carKey'>]: []”(用于调用“tap()”)无法找到

任何匹配的小部件。

我期待测试通过使用键('carKey')点击小部件来加载登录屏幕。

flutter testing widget integration-testing
1个回答
0
投票

您的

individualGridItem
函数不会对其获取的
key
参数执行任何操作。我想你想将它分配给它返回的
GestureDetector

© www.soinside.com 2019 - 2024. All rights reserved.