首页 > 解决方案 > 在颤动的WebView输入之外点击时关闭键盘

问题描述

我正在为此工作超过 4 小时,但无法完成。我想要做的是在输入焦点区域外点击时隐藏键盘。不知何故,键盘无法隐藏。

我在 StackOverflow 上尝试了所有可能的答案,但找不到我的解决方案。

输出:即使在谷歌输入搜索后键盘仍然存在

我的方法

// ignore_for_file: prefer_const_constructors
// ignore: use_key_in_widget_constructors
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:flutter/services.dart';
 
void main(){
  SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
    statusBarColor: Color(0xff1e2229)
  ));
   runApp(MyApp());
}

 
class MyApp extends StatelessWidget {
 
  @override
  Widget build(BuildContext context) {
    return  MaterialApp(
            debugShowCheckedModeBanner: false,
            home:  Scaffold(
                       body:WebViewClass()        
                            ),
            );
  
  }
}
 
class WebViewClass extends StatefulWidget {
  WebViewState createState() => WebViewState();
}

class WebViewState extends State<WebViewClass> {

  bool isLoading = false;

  final key = UniqueKey();
  
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
         onTap: () {
            FocusScopeNode currentFocus = FocusScope.of(context);
            if (!currentFocus.hasPrimaryFocus) {
              currentFocus.unfocus();
            }
           },
        child: Scaffold(
                appBar: null,
                body: SafeArea(
                    child: IgnorePointer(
                      ignoring: isLoading,
                      child: Stack(
                        children: [
                          WebView(
                            initialUrl: 'https://google.com',
                            javascriptMode: JavascriptMode.unrestricted,
                            key: key,
                            onPageFinished: (value) {
                              setState(() {
                                isLoading = false;
                              });
                            },
                            onPageStarted: (value) {
                              setState(() {
                                isLoading = true;
                              });
                            },
                          ),
                          isLoading ? Container(
                            width: MediaQuery.of(context).size.width,
                            height: MediaQuery.of(context).size.height,
                            color: Colors.grey.withOpacity(0.5),
                            child: const Center(child: CircularProgressIndicator())  ,
                          ) : Container(),
                        ],
                      ),
                    )),));

  }
}

如果有人指导我解决这个问题,那就太好了。

标签: flutterdart

解决方案


请在有状态小部件的 initstate 中使用此代码。

 if (Platform.isAndroid) WebView.platform = SurfaceAndroidWebView();

推荐阅读