How can I configure a Flutter TextField to take all text input?

118 views Asked by At

I have precisely one TextField on the screen of my Flutter app. I want my Flutter app to both work on the desktop and on mobile.

Whenever the app is active I want all text input to go into the TextField. When the user clicks on the area outside of the TextField I still want the TextField to get all keyboard input.

What's the best way to achieve this?

1

There are 1 answers

8
Amirali Eric Janani On

if you mean not closing the keyboard by clicking out side here is the solution:

EDIT:

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',
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

enter image description here

I'm clicking outside but the keyboard won't be hide until I click on Done.

happy coding...