import 'package:flutter/cupertino.dart'; /// Keeps the web input's semantics stable when its clear action appears. /// Nesting the clear button in CupertinoSearchTextField changes its merged /// editable node into a disabled child node on web. Native sibling controls /// retain both an enabled input and an independently accessible clear action. class CupertinoWebSearchField extends StatefulWidget { const CupertinoWebSearchField({ super.key, required this.controller, required this.placeholder, required this.onCleared, this.fieldKey, this.focusNode, this.autofocus = false, this.inBar = false, this.onChanged, this.onSubmitted, }); final TextEditingController controller; final String placeholder; final VoidCallback onCleared; final Key? fieldKey; final FocusNode? focusNode; final bool autofocus; final bool inBar; final ValueChanged? onChanged; final ValueChanged? onSubmitted; @override State createState() => _CupertinoWebSearchFieldState(); } class _CupertinoWebSearchFieldState extends State { FocusNode? _localFocus; FocusNode get _focus => widget.focusNode ?? (_localFocus ??= FocusNode()); void _clear() { final focus = _focus; // The browser can keep the old editing session focused on the semantic // clear button after it is removed. This explicit action ends that edit, // then hands focus back after layout; ordinary query changes never refocus. focus.unfocus(); widget.onCleared(); WidgetsBinding.instance.addPostFrameCallback((_) { if (!mounted || !identical(focus, _focus)) return; final current = FocusManager.instance.primaryFocus; if (current == null || current == focus || current is FocusScopeNode) { focus.requestFocus(); } }); WidgetsBinding.instance.ensureVisualUpdate(); } @override void dispose() { _localFocus?.dispose(); super.dispose(); } @override Widget build(BuildContext context) => DecoratedBox( decoration: BoxDecoration( color: widget.inBar ? const Color(0x00000000) : CupertinoColors.tertiarySystemFill.resolveFrom(context), borderRadius: BorderRadius.circular(9), ), child: ConstrainedBox( constraints: const BoxConstraints( minHeight: kMinInteractiveDimensionCupertino, ), child: TextFieldTapRegion( child: Row( children: [ Expanded( child: CupertinoSearchTextField( key: widget.fieldKey, controller: widget.controller, focusNode: _focus, autofocus: widget.autofocus, placeholder: widget.placeholder, backgroundColor: const Color(0x00000000), suffixMode: OverlayVisibilityMode.never, onChanged: widget.onChanged, onSubmitted: widget.onSubmitted, ), ), ValueListenableBuilder( valueListenable: widget.controller, builder: (context, value, _) => value.text.isEmpty ? const SizedBox.shrink() : CupertinoButton( padding: const EdgeInsets.symmetric(horizontal: 8), onPressed: _clear, child: Icon( CupertinoIcons.clear_thick_circled, color: CupertinoColors.secondaryLabel.resolveFrom( context, ), size: 20, semanticLabel: CupertinoLocalizations.of( context, ).clearButtonLabel, ), ), ), ], ), ), ), ); }