Cannot focus on TextField in new page after navigating in Flutter
Asked Answered
C

8

16

For some reason, I cannot focus on a TextField after on the next page after navigating. The keyboard would automatically dismiss when the TextField is selected. If I set autofocus: true on the TextField, then the keyboard will infinitely popup and immediately dismiss over and over again.

I encountered this when my app was a reasonable size but I was able to recreate this in a minimal example app.

I am using Dart 2.0.0-dev.55.0 with Flutter beta v0.3.2.

Code for main page:

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

void main() => runApp(new MyApp());

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

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;
  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('Helpful text.',),
            // ===== Where navigation happens =====
            RaisedButton(
              onPressed: () {
                Navigator.push(context, PageRouteBuilder(
                  pageBuilder: (_, __, ___) => SettingsPage()));
              },
              child: Text('Go to input page'),
            ),
          ],
        ),
      ),
    );
  }
}

Here is the code for the page with the TextField.

import 'package:flutter/material.dart';

class SettingsPage extends StatefulWidget {
  SettingsPage({Key key}) :
   super(key: key);

  @override
  _SettingsPage createState() => new _SettingsPage();
}


class _SettingsPage extends State<SettingsPage> {

  @override
  Widget build(BuildContext context) {
    final key = GlobalKey<ScaffoldState>();
    return Scaffold(
      key: key,
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: Text("Settings"),
      ),
      body: ListView(
        children: <Widget>[
          Text("Enter something"),
          // Can't focus on this widget
          TextField(),
        ],
      ),
    );
  }
}

I can focus fine on TextField on the main page if I put one there, but can't on the one in the Settings page. I assume it has something to do with the keyboard not taking priority over the popped up page? Or what is going on? How I can get the app to just focus on input fields on a navigated page?

Confined answered 25/5, 2018 at 19:9 Comment(3)
I guess the problem is that it is inside a ListView. Can you try to move it out. I run into this recently myself. I assume it's a bug, but might be missing knowledge on my side as well. github.com/flutter/flutter/issues/10498Circular
@GünterZöchbauer I changed the body to just body: TextField(), in the Settings page and I still cannot focus on it. Same thing happens if I change ListView into a Column. I'm going to look more into the issue you linked but so far looks like the bug is still is alive sadly.Confined
If it's not that, I don't know.Circular
C
9

So the problem comes from the fact that I am supplying the GlobalKey to the Scaffold. Removing the key solves the issue. Not exactly sure why but the issue is mostly explained in this Github issue.

I was using the key to have snackbar popup when showing an error message when validating the input but now I'm opting to just display the error message in a Text widget.

Confined answered 25/5, 2018 at 20:9 Comment(1)
The issue was that you created the global key inside the build method. Try moving the Global key initialisation outside the build method and everything works fine :)Equation
L
4

The code snippet essentially sets up a text input field with a unique key (_searchFormKey) so that its state can be accessed or manipulated later in the application. The key is useful, for instance, if you need to validate the input, reset the field, or perform other operations directly on this field programmatically

Example.

// Class private property
static final GlobalKey<FormFieldState<String>> _searchFormKey = GlobalKey<FormFieldState<String>>()

// Inside widget
TextFormField(
  key: _searchFormKey, // Use searchFormKey here like this
  decoration: InputDecoration(
    border: OutlineInputBorder(),
    labelText: 'Type here...',
  )
)
Linkous answered 7/11, 2019 at 11:7 Comment(3)
Why down vote? Using this solution your keyboard will be stable. On focus it will not pop in and pop out. Its working pretty well with stateful widgetLinkous
Could you maybe explain why this solution works?Selenaselenate
If you want your answers to be better (and get upvoted) you should explain in the answer why it works and/or what it fixes. Only writing a snippet of code will usually get downvoted. Your comment really improves your answer, though, so I recommend adding it there.Selenaselenate
A
3

in my case, autofocus:true doesn't work only on iOS simulator, but it will work in real device both for Android and iOS

Angell answered 21/5, 2021 at 23:20 Comment(0)
S
2

Was having a similar issue with global key. Was looking through a similar example in flutter's architecture redux example.

Using the key like so fixed it for me

static final GlobalKey<FormFieldState<String>> _orderFormKey = GlobalKey<FormFieldState<String>>();
Septavalent answered 25/6, 2018 at 21:28 Comment(1)
Please remove the "If anyone understands...". If you are interested in the cause of a certain behaviour don't post this in an answer as this is not a forum. Instead open a new question for it.Dardanelles
F
1

Just add autofocus as true, this will open keyboard when navigating to new screen

 TextField(
            autofocus: true,
          ),
Fiftieth answered 3/7, 2020 at 6:48 Comment(0)
L
0

I also had this issue with a focus node added to the textfield. Removing the focus node solved my issue.

Lemay answered 3/7, 2018 at 16:58 Comment(0)
N
0

Not sure what your issue is since I can't reproduce it any more. I just tried your code in Flutter Channel beta, 1.18.0-11.1.pre and everything worked as it should without modifying your original code.

It looks more as if it was Flutter's bug rather.

Ninnette answered 30/5, 2020 at 18:21 Comment(0)
B
0

I had the same issue. In my case I was accessing formKey.currentState!.validate() inside StatelessWidget. Problem solved When I move my formKey to GetX Controller.

Blacking answered 29/4 at 9:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.