【问题标题】:Why, when I tap the text Field , the keyboard close immediately in Flutter?为什么,当我点击文本 Field 时,Flutter 中的键盘立即关闭?
【发布时间】:2022-08-10 04:30:27
【问题描述】:

这是我的问题:

我有一个带有列表视图的小部件,其中包含一个文本字段,首先,当我点击文本字段时,它工作得很好,但是,如果我点击文本字段,我写了一些东西,然后我关闭了在外面的文本字段录音键盘,我导航到另一个屏幕并返回到上一个屏幕,文本字段立即关闭。

如果我只有一个手势检测器、列表视图和一个文本字段,怎么会出现问题?这是我的代码:

// ignore_for_file: prefer_const_constructors, prefer_const_literals_to_create_immutables

import \'dart:math\';
import \'package:flutter/cupertino.dart\' as cupertino;
import \'package:flutter/material.dart\' hide BoxDecoration, BoxShadow;
import \'package:flutter/services.dart\';
import \'package:flutter_animator/flutter_animator.dart\';
import \'package:flutter_inset_box_shadow/flutter_inset_box_shadow.dart\';
import \'package:font_awesome_flutter/font_awesome_flutter.dart\';
import \'package:google_fonts/google_fonts.dart\';
import \'package:iknowApp/constant.dart\';
import \'package:animated_theme_switcher/animated_theme_switcher.dart\' as theme;
import \'package:like_button/like_button.dart\';
import \'package:string_similarity/string_similarity.dart\';
import \'package:flutter_gen/gen_l10n/app_localizations.dart\';

import \'../data/sentencesData.dart\';
import \'../data/sentencesDataEN.dart\';
import \'../data/sharedPreferences/sharedPreferences.dart\';
import \'../data/theme.dart\';
import \'../main.dart\';

class QuizMode extends StatefulWidget {
  const QuizMode({
    Key key,
  }) : super(key: key);

  @override
  State<QuizMode> createState() => _QuizModeState();
}

class _QuizModeState extends State<QuizMode> {
  bool isPressed = false;
  var result;
  bool correct = true;
  int contador = 0;
  int quizScore = 0;
  final controller = TextEditingController();
  var list = sentences;
  // generates a new Random object
  var _random = new Random();
  var element;
  final formKey = GlobalKey();
  FocusNode myFocusNode;
  bool check = true;
  bool like1 = true;
  bool like2 = true;
  bool like3 = true;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    element = list[_random.nextInt(list.length)];
    myFocusNode = FocusNode();
  }

  @override
  void dispose() {
    myFocusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    Offset distance = isPressed
        ? Offset(MediaQuery.of(context).size.height * 0.01,
            MediaQuery.of(context).size.height * 0.01)
        : Offset(MediaQuery.of(context).size.height * 0.03,
            MediaQuery.of(context).size.height * 0.03);
    double blur = isPressed ? 5 : 30;

    return !Constant.quizMode
        ? const MyHomePage()
        : theme.ThemeSwitchingArea(
            child: cupertino.GestureDetector(
            onTap: () {
              cupertino.FocusScope.of(context).unfocus();
            },
            child: Scaffold(
              body: SafeArea(
                child: cupertino.Center(
                  child: ListView.builder(
                      shrinkWrap: true,
                      itemCount: 1,
                      itemBuilder: (context, index) {
                        final answ = element.answer[index];
                        final ques = element.question[index];
                        return cupertino.Center(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              SizedBox(
                                height: contador < 3
                                    ? MediaQuery.of(context).size.height * 0.1
                                    : MediaQuery.of(context).size.height * 0.05,
                              ),
                              contador < 3
                                  ? cupertino.Column(
                                      children: [
                                        cupertino.Padding(
                                          padding: EdgeInsets.only(
                                              left: MediaQuery.of(context)
                                                      .size
                                                      .width *
                                                  0.1,
                                              right: MediaQuery.of(context)
                                                      .size
                                                      .width *
                                                  0.1),
                                          child: cupertino.Center(
                                            child: TextField(
                                              focusNode: myFocusNode,
                                              enabled:
                                                  contador > 2 ? false : true,
                                              key: formKey,
                                              style: TextStyle(
                                                color: Constant.isDarkMode
                                                    ? cupertino.Color.fromARGB(
                                                            255, 179, 29, 29)
                                                        .withOpacity(0.7)
                                                    : cupertino.Color.fromARGB(
                                                        255, 109, 4, 4),
                                              ),
                                              controller: controller,

                                              // onChanged: onSearchTextChanged,
                                              textAlign: TextAlign.left,
                                              onSubmitted: (value) async {
                                                print(result);
                                                if (value != \"\") {
                                                  String answer = answ
                                                      .toString()
                                                      .toLowerCase();

                                                  result = controller.text
                                                      .toString()
                                                      .toLowerCase()
                                                      .similarityTo(answer);
                                                  if (result.toDouble() > 0.5) {
                                                    quizScore++;
                                                    if (quizScore >
                                                        Constant.score) {
                                                      Constant.score =
                                                          quizScore;
                                                      await DataPreferences
                                                          .setScore(
                                                              Constant.score);
                                                    }

                                                    setState(() {
                                                      contador = 0;
                                                      _random = Random();
                                                      element = list[
                                                          _random.nextInt(
                                                              list.length)];
                                                      correct = true;
                                                      controller.clear();
                                                      myFocusNode
                                                          .requestFocus();
                                                    });
                                                  } else {
                                                    setState(() {
                                                      correct = false;
                                                      contador++;
                                                      HapticFeedback
                                                          .heavyImpact();
                                                      if (contador == 1) {
                                                        like3 = false;
                                                      }
                                                      if (contador == 2) {
                                                        like2 = false;
                                                      }
                                                      if (contador == 3) {
                                                        like1 = false;
                                                      }
                                                    });
                                                  }
                                                }
                                              },
                                              decoration: InputDecoration(
                                                errorText: correct == false
                                                    ? AppLocalizations.of(
                                                            context)
                                                        .incorrect
                                                    : null,
                                                enabledBorder:
                                                    UnderlineInputBorder(
                                                  borderSide: BorderSide(
                                                    color: Constant.isDarkMode
                                                        ? cupertino.Color
                                                                .fromARGB(255,
                                                                    97, 55, 55)
                                                            .withOpacity(0.7)
                                                        : cupertino.Color
                                                            .fromARGB(
                                                                255, 77, 6, 6),
                                                  ),
                                                ),
                                                hintText:
                                                    AppLocalizations.of(context)
                                                        .answer,
                                                hintStyle: TextStyle(
                                                  fontSize:
                                                      MediaQuery.of(context)
                                                              .size
                                                              .height *
                                                          0.02,
                                                  fontWeight: FontWeight.normal,
                                                  color: Constant.isDarkMode
                                                      ? cupertino.Color
                                                              .fromARGB(255,
                                                                  151, 111, 111)
                                                          .withOpacity(0.7)
                                                      : cupertino.Color
                                                          .fromARGB(
                                                              255, 59, 31, 104),
                                                ),
                                                focusedBorder: InputBorder.none,
                                              ),
                                            ),
                                          ),
                                        ),
                                      ],
                                    )
                                  : cupertino.Center(),
                              theme.ThemeSwitcher(builder: (context) {
                                return InkWell(
                                  onTap: () {
                                    setState(() {
                                      Constant.bodyAnimation = true;
                                      Constant.quizMode = false;
                                    });
                                  },
                                  child:
                                      Text(AppLocalizations.of(context).returnn,
                                          style: GoogleFonts.alike(
                                            textStyle: Theme.of(context)
                                                .textTheme
                                                .displayMedium,
                                            fontSize: MediaQuery.of(context)
                                                    .size
                                                    .width *
                                                0.04,
                                            color: Constant.isDarkMode
                                                ? cupertino.Color.fromARGB(
                                                        255, 185, 51, 51)
                                                    .withOpacity(0.7)
                                                : cupertino.Color.fromARGB(
                                                    255, 158, 158, 158),
                                          )),
                                );
                              }),
                            ],
                          ),
                        );
                      }),
                ),
              ),
            ),
          ));
  }
}

    标签: flutter keyboard


    【解决方案1】:

    我认为这段代码使它失去了对文本字段的关注,这就是键盘立即关闭的原因

    onTap: () {
                  cupertino.FocusScope.of(context).unfocus();
                },
    

    【讨论】:

    • 但是,我还认为,即使我删除了这些行,代码也不会像我预期的那样工作。
    • 这里的主题切换区是什么?
    • 这是代码的一个片段(我只放这个片段,因为它在这里我有问题)。完整的代码有一个开关。无论如何,即使有完整的代码或片段,问题仍然存在。
    • 我认为单击文本字段时可能正在构建屏幕,请您提供完整代码
    • 抱歉,这是唯一正常工作的部分
    【解决方案2】:

    我终于解决了我的问题,改变:

    final formKey = GlobalKey();
      FocusNode myFocusNode;
    

    到静态最终,如您在此处看到的;

      static final formKey = GlobalKey();
      static final myFocusNode = FocusNode();
    

    并且工作没有任何问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-21
      • 2018-12-21
      • 2021-03-24
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 2020-02-09
      相关资源
      最近更新 更多