How to test semantic properties in Flutter widget tests

148 views Asked by At

How can semantic properties been tested in Flutter widget tests?

I would like to test if a specific widget has the expected semantic label.

This is the widget:

class Tag extends StatelessWidget {
  const Tag({
    required this.semanticsLabel,
    required this.name,
    required this.onPressed,
    super.key,
  });

  final String name;

  final VoidCallback onPressed;

  final String semanticsLabel;

  @override
  Widget build(BuildContext context) {
    return Semantics(
      label: semanticsLabel,
      button: true,
      child: ExcludeSemantics(
          child: OutlinedButton(
            onPressed: onPressed,
            child: Text(
              name,
            ),
          ),
        ),
      );
    }
  }
1

There are 1 answers

0
MCB On

A test case for the label could look like this:

final tagCategorySemantics = tester.getSemantics(find.byType(Tag));
 expect(tagCategorySemantics.label, 'Semantic Tag Label');

If you also have a semantic action, it can be tested like:

final semanticsOwner =
          RendererBinding.instance.rootPipelineOwner.semanticsOwner;

final tagSemantics = tester.getSemantics(find.byType(Tag));

semanticsOwner?.performAction(
        tagSemantics.id,
        SemanticsAction.didGainAccessibilityFocus,
      );