【问题标题】:Flutter: keyboard disappears immediately when editing my text fieldsFlutter:编辑我的文本字段时键盘立即消失
【发布时间】:2018-12-21 13:45:37
【问题描述】:

我正在尝试使用颤振构建应用程序前端,这是我第一次遇到这样的错误:无法编辑我的 textformfield 因为我将表单元素放在列表视图中!当键盘出现在字段中输入一些文本时,它会在一秒钟内消失!我需要一个即时的解决方案:(

import 'package:flutter/material.dart';
import'package:dubai274_app/mobile_verif.dart';
import 'EnsureVisible.dart';
class SignUp extends StatefulWidget{
  static String tag = 'Sign_up-page';
  SignUp_Page createState() => SignUp_Page();

}
class SignUp_Page extends State<SignUp>{
  


  List<DropdownMenuItem<String>> _Dropdownmenuitems;
  String _statusSel;
  List<DropdownMenuItem<String>> _getDropdownmenuitem(){

    List<DropdownMenuItem<String>> items=new List();
    items.add(new DropdownMenuItem(value:'Emirates',child: new Text('United Arab Emirates')));
    items.add(new DropdownMenuItem(value:'Tun',child: new Text('Tunisia')));
    return items;
  }
  void changeddropdowselecteditem(String selecteditem){
    setState(() {
_statusSel=selecteditem;
    });
  }
   @override
  void initState() {
    // TODO: implement initState
    //listViewController=new ScrollController().addListener(_scrollListener);
    _Dropdownmenuitems=_getDropdownmenuitem();
    _statusSel=_Dropdownmenuitems[0].value;
  }
@override
  Widget build(BuildContext context) {
  final scaffoldKey = GlobalKey<ScaffoldState>();
  final formKey = GlobalKey<FormState>();
  final TextEditingController _controller = new TextEditingController();
  
final first_value=TextFormField(autofocus: false,
  validator: (val) =>
  val.length < 6 ? 'First name required' : null,
  decoration: InputDecoration(
    labelText: 'First Name',
    hintText: 'First Name',
    contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),


  ),);

final family_value=TextFormField(autofocus: false,
  decoration: InputDecoration(
    labelText: 'Last Name',
    hintText: 'Last Name',
    contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),


  ),);

final Nationality=new DropdownButton(items: _Dropdownmenuitems, value:_statusSel,onChanged: changeddropdowselecteditem);

final email_value=TextFormField(keyboardType: TextInputType.emailAddress,
  autofocus: false,
  decoration: InputDecoration(
    labelText: 'Email',
    hintText: 'Email',
    contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),

  ),);

final password=Column(children: <Widget>[ TextFormField(autofocus: false,

  obscureText: true,
  decoration: InputDecoration(
    labelText: 'Password',
    hintText: 'Password',
    contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),)), Text('Min 8 characters with at least one special character')]);
  void _performsignup() {

    final snackbar = SnackBar(
      content: Text('Email: $email, password: $password'),
    );

    scaffoldKey.currentState.showSnackBar(snackbar);
  }
  void _submit() {
    final form = formKey.currentState;

    if (form.validate()) {
      form.save();
      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => MobileVerif()),
      );

      _performsignup();
    }
  }
final forward_signedin=FloatingActionButton(tooltip: 'Go forward',
  child: Icon(Icons.arrow_forward,color: Colors.white,size: 38.4,),


  onPressed: (){_submit();},);

return MaterialApp(
      title: 'Sign_Up_Page',
      home: Scaffold(
        appBar: AppBar(
          elevation: 0.0,
      backgroundColor: Colors.transparent,
      title: const Text('Sign Up',style: TextStyle(color: Colors.blueAccent, fontSize: 25.0,fontWeight: FontWeight.bold),textAlign: TextAlign.center,),
  centerTitle: true,
  leading: IconButton(
  tooltip: 'Previous choice',
  icon: const Icon(Icons.arrow_back_ios),
    onPressed: () { Navigator.pop(context);},
    color: Colors.black,
    iconSize: 20.0,
  ),
  ),
        body: new Container(
          decoration: new BoxDecoration(
          image: new DecorationImage(
            image: new AssetImage("assets/background.png"),
            fit: BoxFit.cover,
          ),
        ),
        child: new Form( key: formKey,
            child: new Padding( padding: new EdgeInsets.all(40.0), child: ListView(
      children: <Widget>[

       first_value,
       family_value,
       Nationality,
       email_value,
       password,
       new ListTile( title:forward_signedin,)],
)) )

        ),


        ),

      );


  }
}

【问题讨论】:

  • 如果你不分享你迄今为止尝试过的东西,我们就无法知道问题所在
  • @Farah,你找到解决方案了吗?

标签: listview keyboard flutter


【解决方案1】:

如果您的 TextField 位于 Dismissible() 小部件中,那么这会导致问题!

【讨论】:

    【解决方案2】:

    在我自己的例子中,我将这个 key: ValueKey&lt;int&gt;(math.Random().nextInt(5)), 作为 TextFormField 的祖先小部件的键。我删除了它,错误不再出现。 所以我的调试建议是检查小部件树中的所有小部件,它们的键参数传递了任何值..

    【讨论】:

      【解决方案3】:

      您应该定义所有这些:

        final scaffoldKey = GlobalKey<ScaffoldState>();
        final formKey = GlobalKey<FormState>();
        final TextEditingController _controller = new TextEditingController();
      

      作为 SignUp_Page 的字段不在构建函数中。

      【讨论】:

        【解决方案4】:

        我遇到了同样的问题,正如@apc 所说,只需将密钥设为静态或在iniState()... 中初始化它

        如果您使用无状态小部件,请将其设为静态

        static final GlobalKey&lt;FormState&gt; _key = GlobalKey&lt;FormState&gt;();

        【讨论】:

        • 这解决了我的问题,谢谢
        【解决方案5】:

        如果您使用的是StatelessWidget,请将其转换为StatefulWidget。确保键是状态的属性,而不是小部件的。发生这种情况是因为每次重建都会一遍又一遍地重新创建表单密钥。要保留密钥,它应该是状态的一部分。

        【讨论】:

          【解决方案6】:

          我将在此处发布我的答案,即使它与问题与 OP 不完全相同。

          我在网上到处搜索键盘出现和消失的问题,
          1. 这是我发现的唯一一个描述键盘出现消失问题的 SO 问题,并且
          2. 其他解决方案,比如@apc's answer 和这个github answer 都集中在formKeystatic 和/或GlobalKey,这绝对不是我问题的原因(不变我的表单和/或其字段的键或重新创建的键对问题没有任何影响)。

          我的具体问题涉及带有多个Future 方法的class AuthService with ChangeNotifier
          经过几天尝试不同的方法后,我发现唯一可以避免键盘出现和立即消失的方法是使用AuthService()在我的应用程序的顶层,runApp()

          void main() => runApp(
            ChangeNotifierProvider<AuthService>(
              child: TheWidgetThatIsMyAppAndHasAllBusinessLogicInIt(),
              builder: (BuildContext context) {
                return AuthService();
              },
            ),
          );
          

          (在代码中的任何其他位置添加 ChangeNotifierProvider 都会导致键盘消失问题)

          然后我不得不对如何在此基础上构建我的逻辑进行创造性的思考——因为我只真正关心应用程序的某些部分中的 AuthService,但我对 Flutter 非常陌生,这一切都是很好的学习。

          我不知道为什么会这样,我很想了解更多信息,但我知道我还没有详细说明我的情况.....
          但我已经花了几天时间解决这个问题,我需要把我的答案放在这里,希望能帮助别人。

          【讨论】:

          • builder 现已弃用。请改用create
          • 当TextField是VisibilityDetector的后代时,在TextController.addListener()或TextField的onChanged()方法中调用setState()也可能导致问题。
          【解决方案7】:

          您的构建函数中有以下代码:

          final formKey = GlobalKey<FormState>();
          

          这就是问题所在。您必须使其静止或移动到 initState()

          【讨论】:

          • 我遇到了类似的问题。基本上,我有一个我想重用的表单,所以我创建了一个单独的小部件。然后从我使用该小部件的任何地方,我将 GlobalKey 传递给小部件。一种形式可以正常工作,另一种形式会表现出键盘关闭行为。但是,密钥的创建不在 build 方法中。按照您的建议创建静态密钥似乎可以修复它,但不知道为什么......
          • 有人愿意解释为什么在不将其声明为静态时会发生这种情况吗?
          • 将 GlobalKey 放入构建函数时会发生这种情况
          • Static 使它与班级的活动无关 @Moralde-Sama。谁能进一步推动这个解释?
          猜你喜欢
          • 2023-01-14
          • 1970-01-01
          • 1970-01-01
          • 2012-02-24
          • 2012-12-07
          • 2015-08-27
          • 2022-08-10
          • 2023-03-22
          • 1970-01-01
          相关资源
          最近更新 更多