如何在没有 TextField 的情况下打开键盘

问题描述 投票:0回答:2

在没有文本字段或聚焦小部件的情况下打开键盘

flutter dart
2个回答
0
投票

显示键盘

SystemChannels.textInput.invokeMethod("TextInput.show");

隐藏键盘

SystemChannels.textInput.invokeMethod("TextInput.hide");

0
投票

要在不使用

TextField
的情况下在Flutter中打开键盘,您可以使用
FocusNode
类并调用其
requestFocus()
方法来请求将焦点放在隐藏的
TextField
上。这是一个让您入门的示例代码片段:

import 'package:flutter/material.dart';

class KeyboardScreen extends StatefulWidget {
  @override
  _KeyboardScreenState createState() => _KeyboardScreenState();
}

class _KeyboardScreenState extends State<KeyboardScreen> {
  final _focusNode = FocusNode();

  @override
  void initState() {
    super.initState();
    // Set a delay before requesting focus to ensure that the widget has loaded.
    Future.delayed(Duration(milliseconds: 100)).then((_) => _focusNode.requestFocus());
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: TextField(
          focusNode: _focusNode,
          enableInteractiveSelection: false,
          showCursor: false,
          autofocus: true,
          decoration: InputDecoration(
            border: InputBorder.none,
            contentPadding: EdgeInsets.zero,
          ),
        ),
      ),
    );
  }
}

在这个例子中,我们通过将它的

TextField
border
属性分别设置为
contentPadding
InputBorder.none
来创建一个隐藏的
EdgeInsets.zero
小部件。我们还使用
enableInteractiveSelection
showCursor
属性禁用交互式选择和光标可见性。

要打开键盘,我们使用

FocusNode
并在小部件的
requestFocus()
方法中调用它的
initState()
方法。我们还在小部件的
FocusNode
方法中处理
dispose()
以防止任何内存泄漏。

您可以自定义此代码以满足您的特定要求。例如,您可以更改请求焦点之前的延迟时间、

TextField
装饰等等。

© www.soinside.com 2019 - 2024. All rights reserved.