readSelected function

bool? readSelected(
  1. WidgetTester tester,
  2. Element element
)

Reads the selected semantics flag when the element exposes one. Semantics-disabled snapshots leave the value unknown.

Implementation

bool? readSelected(WidgetTester tester, Element element) {
  final finder =
      find.byElementPredicate((candidate) => identical(candidate, element));
  try {
    final node = tester.getSemantics(finder);
    // `flagsCollection` preserves the tri-state selected value (including
    // unknown). Access it dynamically so the runner also remains compatible
    // with older Flutter SDKs that predate this API.
    final dynamic flags = (node as dynamic).flagsCollection;
    final selected = flags.isSelected.toString().split('.').last;
    return switch (selected) {
      'isTrue' || 'true' => true,
      'isFalse' || 'false' => false,
      _ => null,
    };
  } on NoSuchMethodError {
    // Legacy Flutter exposed only the bit-flag API, which cannot distinguish
    // an explicit false from an unspecified selected state.
    try {
      final node = tester.getSemantics(finder);
      return (node as dynamic).hasFlag(SemanticsFlag.isSelected) as bool;
    } catch (_) {
      return null;
    }
  } catch (_) {
    return null;
  }
}