import 'package:flutter/material.dart';

// 点击空白区域收起键盘的Widget
class NewsTapToDismissKeyBoard extends StatelessWidget {
  final Widget child;
  final bool? enable;

  const NewsTapToDismissKeyBoard({
    Key? key,
    required this.child,
    this.enable = true,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    if (!enable!) return child;

    return GestureDetector(
      onTap: () {
        // 点击时收起键盘
        FocusScopeNode currentFocus = FocusScope.of(context);
        if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
          FocusManager.instance.primaryFocus?.unfocus();
        }
      },
      behavior: HitTestBehavior.translucent,
      child: child,
    );
  }
}

// 全局扩展方法，方便在任意Widget上使用
extension TapToDismiss on Widget {
  Widget get dismissKeyboardOnTap {
    return NewsTapToDismissKeyBoard(child: this);
  }
}
