【问题标题】:Flutter / Dart: onPressed not called when tapping an AppBar widget in Widget TestFlutter / Dart:在小部件测试中点击AppBar小部件时未调用onPressed
【发布时间】:2021-01-12 03:50:58
【问题描述】:

我的问题是我有一个无状态小部件,它返回带有 onPressed 事件的 AppBar。在我相应的 widgetTest 中,我点击组件并期望调用 onPressed 方法。然而,事实并非如此。

这是我的小部件:

import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';

class IconAppBar extends StatelessWidget with PreferredSizeWidget {
  final VoidCallback onPressed;

  IconAppBar({this.onPressed});

  @override
  Widget build(BuildContext context) {
    return AppBar(
      leading: IconButton(
        color: Colors.black,
        icon: SvgPicture.asset(
          "resources/images/icon.svg",
          width: 24,
          height: 24,
        ),
        onPressed: onPressed,
      ),
    );
  }

  @override
  Size get preferredSize => Size.fromHeight(kToolbarHeight);
}

在测试中,如果组件被点击,我会通过一个简单的 onPressed 测试来创建小部件。

void main() {
    testWidgets("Should run onPressed when tapped",
        (WidgetTester tester) async {
      var counter = 0;
      void callback() {
        counter++;
      }

      await tester.pumpWidget(
        MediaQuery(
          data: MediaQueryData(),
          child: MaterialApp(
            localizationsDelegates: [
              GlobalMaterialLocalizations.delegate,
              GlobalWidgetsLocalizations.delegate,
              GlobalCupertinoLocalizations.delegate,
            ],
            home: IconAppBar(
              onPressed: callback,
            ),
          ),
        ),
      );

      await tester.pump(Duration(milliseconds: 300));
      await tester.tap(find.byType(IconAppBar));
      await tester.pump(Duration(milliseconds: 300));

      expect(counter, 1); // fails because actual counter is 0
    });
}

更改为 tester.pump()tester.pumpAndSettle() 并没有改变任何内容。 该方法未被调用。

在实际设备或模拟器中运行它,onPressed 按预期工作。

另外,find.byType(IconAppBar) 的冒烟测试确实找到了小部件。

我非常感谢任何帮助或想法。谢谢!

编辑:这似乎不适用于IconButton。我只是将其更改为FlatButton,并以 SVG 作为其子元素,这很好。

【问题讨论】:

    标签: flutter testing dart flutter-onpressed widget-test-flutter


    【解决方案1】:

    不知道这是否有帮助:

    class IconAppBar extends StatelessWidget with PreferredSizeWidget {
      final VoidCallback onPressed;
    
      BackButtonAppBar({this.onPressed});
    
      void click() {
        print("Its Working!");
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
          leading: IconButton(
            color: Colors.black,
            icon: SvgPicture.asset(
              "resources/images/icon.svg",
              width: 24,
              height: 24,
            ),
            onPressed: () {
              click();
            },
          ),
        );
      }
    }
    

    【讨论】:

    • 很遗憾,这并没有解决问题。在应用程序中,我实际上总是在Scaffold 中使用这个小部件。
    猜你喜欢
    • 1970-01-01
    • 2021-01-27
    • 1970-01-01
    • 2021-09-22
    • 2020-12-06
    • 2021-05-09
    • 2019-02-25
    • 2021-12-29
    • 2020-11-07
    相关资源
    最近更新 更多