【问题标题】:Flutter, prevent the keyboard from showing once the time is enteredFlutter,防止输入时间后键盘显示
【发布时间】:2020-12-03 16:52:44
【问题描述】:

我想阻止键盘在输入时间后显示,我该怎么做?

更新

我尝试使用FocusScope.of(context).unfocus();,它适用于第一次尝试,但不适用于第二次。这有点奇怪。看看这个。

第一个有效,第二个无效,但第三个有效,还注意到键盘出现比 TimePicker 显示更早。 (对不起我的英语不好)

这是代码;


  TextEditingController _startTime = TextEditingController();

  Widget _createTimePicker(String text, TextEditingController controller) {
    return Container(
      margin: EdgeInsets.symmetric(vertical: 10),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(
            text,
            style: TextStyle(fontWeight: FontWeight.bold, fontSize: 15),
          ),
          SizedBox(
            height: 10,
          ),
          TextFormField(
            validator: (String value) {
              if (value.isEmpty) {
                return 'Es necesario especificar una hora.';
              }
            },
            controller: controller,
            decoration: InputDecoration(
                border: InputBorder.none,
                fillColor: Color(0xfff3f3f4),
                filled: true),
            onTap: () {
              Navigator.of(context).push(
                showPicker(
                  context: context,
                  value: _time,
                  onChange: onTimeChanged,
                  is24HrFormat: true,
                ),               
              );
              FocusScope.of(context).unfocus();
            },
          )
        ],
      ),
    );
  }

  TimeOfDay _time = TimeOfDay.now().replacing(minute: 30);

  void onTimeChanged(TimeOfDay newTime) {
    setState(() {
      _time = newTime;
      _startTime.text = _time.format(context);
    });
  }



【问题讨论】:

  • 这是设计使然。注意滑块不会改变分钟?如果您希望能够更改分钟,则需要那里的键盘。
  • 我可以通过点击来更改分钟
  • 向我们展示您的代码。

标签: flutter


【解决方案1】:

您可以在下面复制粘贴运行 2 个完整代码
解决方案 1:快速修复当前代码
您可以使用Future.delayedFocusManager.instance.primaryFocus.unfocus

onTap: () async {
            Navigator.of(context).push(
              showPicker(
                context: context,
                value: _time,
                onChange: onTimeChanged,
                is24HrFormat: true,
              ),
            );
            await Future.delayed(Duration(milliseconds: 50), () {
              FocusManager.instance.primaryFocus.unfocus();
            });
          })

解决方案 2:假设您不需要一直显示键盘
您可以使用GestureDetector wrap TextFormField 并将enable 设置为false

GestureDetector(
            onTap: () async {
              Navigator.of(context).push(
                showPicker(
                  context: context,
                  value: _time,
                  onChange: onTimeChanged,
                  is24HrFormat: true,
                ),
              );
            },
            child: TextFormField(
              enabled: false,

工作演示 1

工作演示 2

完整代码 1

import 'package:day_night_time_picker/lib/daynight_timepicker.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  TextEditingController _startTime = TextEditingController();
  final _formKey = GlobalKey<FormState>();

  Widget _createTimePicker(String text, TextEditingController controller) {
    return Container(
      margin: EdgeInsets.symmetric(vertical: 10),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(
            text,
            style: TextStyle(fontWeight: FontWeight.bold, fontSize: 15),
          ),
          SizedBox(
            height: 10,
          ),
          TextFormField(
              //enabled: false,
              validator: (String value) {
                if (value.isEmpty) {
                  return 'Please enter some text';
                }
                return null;
              },
              controller: controller,
              decoration: InputDecoration(
                  errorStyle: TextStyle(color: Colors.red),
                  border: InputBorder.none,
                  fillColor: Color(0xfff3f3f4),
                  filled: true),
              onTap: () async {
                Navigator.of(context).push(
                  showPicker(
                    context: context,
                    value: _time,
                    onChange: onTimeChanged,
                    is24HrFormat: true,
                  ),
                );
                await Future.delayed(Duration(milliseconds: 200), () {
                  FocusManager.instance.primaryFocus.unfocus();
                });
              })
        ],
      ),
    );
  }

  TimeOfDay _time = TimeOfDay.now().replacing(minute: 30);

  void onTimeChanged(TimeOfDay newTime) {
    setState(() {
      _time = newTime;
      _startTime.text = _time.format(context);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Form(
          key: _formKey,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              _createTimePicker("", _startTime),
              ElevatedButton(
                onPressed: () {
                  if (_formKey.currentState.validate()) {}
                },
                child: Text('Submit'),
              )
            ],
          ),
        ),
      ),
    );
  }
}

完整代码2

import 'package:day_night_time_picker/lib/daynight_timepicker.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  TextEditingController _startTime = TextEditingController();
  final _formKey = GlobalKey<FormState>();

  Widget _createTimePicker(String text, TextEditingController controller) {
    return Container(
      margin: EdgeInsets.symmetric(vertical: 10),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(
            text,
            style: TextStyle(fontWeight: FontWeight.bold, fontSize: 15),
          ),
          SizedBox(
            height: 10,
          ),
          GestureDetector(
            onTap: () async {
              Navigator.of(context).push(
                showPicker(
                  context: context,
                  value: _time,
                  onChange: onTimeChanged,
                  is24HrFormat: true,
                ),
              );
            },
            child: TextFormField(
              enabled: false,
              validator: (String value) {
                if (value.isEmpty) {
                  return 'Please enter some text';
                }
                return null;
              },
              controller: controller,
              decoration: InputDecoration(
                  errorStyle: TextStyle(color: Colors.red),
                  border: InputBorder.none,
                  fillColor: Color(0xfff3f3f4),
                  filled: true),
            ),
          )
        ],
      ),
    );
  }

  TimeOfDay _time = TimeOfDay.now().replacing(minute: 30);

  void onTimeChanged(TimeOfDay newTime) {
    setState(() {
      _time = newTime;
      _startTime.text = _time.format(context);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Form(
          key: _formKey,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              _createTimePicker("", _startTime),
              ElevatedButton(
                onPressed: () {
                  if (_formKey.currentState.validate()) {}
                },
                child: Text('Submit'),
              )
            ],
          ),
        ),
      ),
    );
  }
}

【讨论】:

    【解决方案2】:

    关于时间选择关闭键盘的回调函数 FocusScope.of(context).unfocus();

    【讨论】:

    • 第一次尝试有效,第二次无效,我更新了帖子,提供了更多详细信息,感谢您的回复!
    【解决方案3】:

    如果此字段只能通过时间选择器编辑,您可以通过设置其属性将文本字段设为只读

    readOnly: true
    

    如果字段可以通过键盘编辑,则可以等待对话结果,然后调用

    FocusScope.of(context).requestFocus(new FocusNode());
    

    【讨论】:

      【解决方案4】:

      在为 TextInput 设置时间或确认时间选择后,调用此 FocusScope.of(context).unfocus() 函数。

        // update your function
        void onTimeChanged(TimeOfDay newTime) {
          FocusScope.of(context).unfocus();
          ...
        }
      

      和,

        TextFormField(
            readOnly: true,
            ...
        )
      

      【讨论】:

      • 第一次尝试有效,第二次无效,我更新了帖子,提供了更多详细信息,感谢您的回复!
      • 我试过了,但我似乎仍然遇到同样的问题
      • 由于我将enabled 设置为false 我现在无法使用onTap() 函数
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-17
      • 2020-04-22
      • 1970-01-01
      相关资源
      最近更新 更多