如何配置Flutter TextField以接受所有文本输入?

sirbozc5  于 2023-03-31  发布在  Flutter
关注(0)|答案(1)|浏览(118)

我的Flutter应用屏幕上正好有一个TextField。我希望我的Flutter应用既能在桌面上运行,也能在移动的端运行。
每当应用程序处于活动状态时,我希望所有的文本输入都进入TextField。当用户点击TextField之外的区域时,我仍然希望TextField获得所有的键盘输入。
实现这一目标的最佳途径是什么?

llycmphe

llycmphe1#

如果你的意思是不关闭键盘点击外面这里是解决方案:
编辑:

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  bool _keyboardVisible = false;
  var focusNode = FocusNode();

  @override
  Widget build(BuildContext context) {
    focusNode.addListener(() {
      print("hasFocus ${focusNode.hasFocus}");
    });
    return MaterialApp(
      home: Scaffold(
        body: SafeArea(
          child: Stack(
            children: [
              GestureDetector(
                onTap: () {
                  print('hello');
                 // Hide the keyboard when the user taps outside the TextField
                  if (_keyboardVisible) {
                    SystemChannels.textInput.invokeMethod('TextInput.hide');
                    _keyboardVisible = false;
                  }
                  print("hasFocus ${focusNode.hasFocus}");
                },
                child: const Center(
                  child: Text('Tap outside the TextField'),
                ),
              ),
              Positioned(
                bottom: 16,
                left: 16,
                right: 16,
                child: RawKeyboardListener(
                  focusNode: focusNode,
                  onKey: (event) {
                    // Show the keyboard when the user starts typing
                    if (!_keyboardVisible) {
                      SystemChannels.textInput.invokeMethod('TextInput.show');
                      _keyboardVisible = true;
                    }
                  },
                  child: const TextField(
                    decoration: InputDecoration(
                      border: OutlineInputBorder(),
                      hintText: 'Enter text',
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

我点击外部,但键盘不会隐藏,直到我点击完成。
快乐编码...

相关问题