55

I'm new to flutter. I've added a form with a text field and when I clicked the textfield and keyboard comes, the textfield goes up.

This is my code :

Widget build(BuildContext context) {

MediaQueryData mediaQuery = MediaQuery.of(context);
return new Scaffold(
  body:  new Container(
      color: Colors.purple,
      constraints: new BoxConstraints.expand(),
      padding: EdgeInsets.only(top: 10.0,left: 10.0,right: 10.0, bottom: mediaQuery.viewInsets.bottom, ),
      child: SingleChildScrollView(
        child: Container(
            child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  SizedBox(height: 12.0),
                  Text(
                    'What is your Business Name?',
                    style: TextStyle(fontSize: 24.0),
                  ),
                  AppForm(),
                ],
              ),
            padding: EdgeInsets.only(left: 10.0,right: 10.0, bottom: mediaQuery.viewInsets.bottom),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.all(Radius.circular(30.0)),
              color: Colors.white,
                ),
              )
          )
      ),
    );
  }

This is the result without opening the keyboard: Image without keyboard

This is the image after opening the keyboard: Image after opening the keyboard


Here is my flutter doctor output.

Doctor summary (to see all details, run flutter doctor -v): [√] Flutter 
(Channel beta, v0.5.1, on Microsoft Windows [Version 10.0.17134.165], locale 
en-US) [√] Android toolchain - develop for Android devices (Android SDK 
28.0.0) [√] Android Studio (version 3.1) [!] VS Code, 64-bit edition (version 
1.25.1) [!] Connected devices ! No devices available ! Doctor found issues in 
2 categories.

any idea how to fix this?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Nirodya Gamage
  • 684
  • 1
  • 8
  • 13
  • Do you have the latest version of flutter? What does `flutter doctor` say? – Bostrot Jul 14 '18 at 08:25
  • Here is my flutter doctor output. Doctor summary (to see all details, run flutter doctor -v): [√] Flutter (Channel beta, v0.5.1, on Microsoft Windows [Version 10.0.17134.165], locale en-US) [√] Android toolchain - develop for Android devices (Android SDK 28.0.0) [√] Android Studio (version 3.1) [!] VS Code, 64-bit edition (version 1.25.1) [!] Connected devices ! No devices available ! Doctor found issues in 2 categories. – Nirodya Gamage Jul 14 '18 at 12:51
  • I'd recommend you to go to the channel flutter master `flutter channel master` which is currently at `v5.7` and also clean your project with `flutter clean` and `Invalidate caches and restart` – Bostrot Jul 14 '18 at 13:05
  • Seen this ?? https://www.didierboelens.com/2018/04/hint-4-ensure-a-textfield-or-textformfield-is-visible-in-the-viewport-when-has-the-focus/ – TheAshwaniK Dec 17 '19 at 10:27

22 Answers22

44
Scaffold(
    resizeToAvoidBottomInset: true,
    // ...
    appBar: AppBar(
      // ...
    ),
)

Fixed problem textfield was hidden by keyboard

Pedro Luz
  • 2,694
  • 4
  • 44
  • 54
songoku1610
  • 1,576
  • 1
  • 13
  • 17
  • Thanks for your answer! I saw many answers saying to set up this property as `false`, but actually is the value `true` that makes it work as desired. o/ – ebragaparah Aug 01 '22 at 21:24
  • Somehow i follow [this answer](https://stackoverflow.com/a/46551390/9039350) and its the false one that fix the problem.. – Muhammad Faisal Oct 19 '22 at 08:31
29

This answer is not specific the question above but may be useful to those who are still having issues with the keyboard covering the selected text field, no matter what they do. I got to this page while trying to resolve such an issue.

Prior to the problem I had been making some changes to try and improve my splash screen on app startup. As per someone's recommendation, I had included the following line in the <resources><style> section of the styles.xml file in the android/app/src/main/res/values folder

<item name="android:windowFullscreen">true</item>

This had the unexpected effect of stopping any fields scrolling up in the main app when the keyboard is displayed. This might be obvious to some, but it wasn't to me.

Hope this info helps someone.

GrahamD
  • 2,952
  • 3
  • 15
  • 26
  • This fixes this issue but brings other issues if you have a top banner. The status bar is displaying (that's one) and it does it on top of the banner – Dani Dec 12 '20 at 08:35
25

This was the case with me . You are definitely wrapping a scaffold inside another scaffold . there should be only one scaffold widget inside your flutter app i.e the main layout . Simple remove all the ancestor scaffolds you have and keep only one scaffold . dont wrap a scaffold into another scaffold .inspite of that you can wrap a scaffold inside a container .

Make sure in your main.dart file you are not doing this :-

✖✖

return Scaffold(
body : YourNewFileName(),
);

Inspite of the above code do this:- ✔✔

return YourNewFileName();
Aman Malhotra
  • 3,068
  • 2
  • 18
  • 28
  • @Nirodya Gamage can you post the main.dart file so that i can check where the error is ?? – Aman Malhotra Jul 14 '18 at 13:59
  • I'm so sorry you are correct! I found another Scaffold on a backdrop. I removed one and it works. Thanks so much! – Nirodya Gamage Jul 14 '18 at 15:07
  • great . Coz that same thing happened to me and this was how i solved it . – Aman Malhotra Jul 14 '18 at 16:48
  • I have scaffhold inside scaffhold. It requires for me to add Tabbarview. What is the solution for it. – Malavan May 15 '20 at 11:16
  • Tab bar can be added with a single Scaffold too @dominic_torreto. As of now having scaffold inside scaffold with give you some errors like this one. so u should change the structure with which u r designing your app . – Aman Malhotra May 15 '20 at 13:37
  • Yes. Changed the structure. Eventhough its not working. – Malavan May 15 '20 at 14:48
  • Same, I can see that there is only one `Scaffold` in widget tree from `Flutter DevTools` and the problem still exists. Btw I thought `Scaffold` can be present in every page, no? – Oleg Yablokov Sep 01 '22 at 15:04
20

You can simply wrap the widget you want to never be hidden by the keyboard inside a padding, like follow :

Padding(
         child: YourWidget()
         padding: EdgeInsets.only(
         bottom: MediaQuery.of(context).viewInsets.bottom)); 
ezzou
  • 2,348
  • 1
  • 15
  • 16
15

resizeToAvoidBottomPadding is Deprecated use instead resizeToAvoidBottomInset: true

Ashish
  • 6,791
  • 3
  • 26
  • 48
Ya Si
  • 819
  • 7
  • 12
  • 1
    This works awesome. Setting `resizeToAvoidBottomInset: true` for the Scaffold will adjust the view to be within the area above your keyboard with this. – poomulus Mar 25 '20 at 01:47
  • 1
    resizeToAvoidBottomInset is true by default. no need to add that one – MJ Montes Aug 20 '20 at 11:08
12
<item name="android:windowFullscreen">true</item>

Removing above line from

android/app/src/main/res/values/styles.xml

made my app fixed to input field auto scroll upwards to come in view able on keyboards opens

thanks @GrahamD

enter image description here

Javeed Ishaq
  • 6,024
  • 6
  • 41
  • 60
  • 3
    I had this issue, too. This line was added as a result of using the flutter_native_splash package. Don't think I would have ever found that. Thank you. – Michael T Aug 17 '20 at 15:03
  • Thanks for this. I had the same problem because of flutter_native_splash – cmd_prompter Sep 10 '20 at 12:45
  • This fixes this issue but brings other issues if you have a top banner. The status bar is displaying (that's one) and it does it on top of the banner – Dani Dec 12 '20 at 08:34
10

You should add SingleChildScroolView into your Scaffold and add reverse: true into your SingleChildScroolView

Scaffold(
body: SingleChildScrollView(
          reverse: true,
          child: Container()));
Timur Turbil
  • 1,145
  • 10
  • 13
9

If you use ScreenUtilInit package then maybe setting useInheritedMediaQuery: true in the constructor of ScreenUtilInit will help you. It helped me :)

Oleg Yablokov
  • 736
  • 8
  • 19
6

Just cut and paste your body code in this -

SingleChildScrollView(
        child: Stack(
          children: <Widget>[
              // your body code 
           ],
         ),
       ),

had the same issue got the answer here

The Billionaire Guy
  • 3,382
  • 28
  • 31
5

If you are using Scaffold than wrap the body with SingleChildScrollView

for Example like this:

...
return Scaffold(
body: SingleChildScrollView(
    child: Column(
      children: <Widget>[
        TextField(),
        TextField(),
        TextField(),
      ],
    ),
  ),
);
...

this was really a lifesaver for me. Now the scaffold will become scrollable.

SKJ
  • 237
  • 2
  • 11
3

resizeToAvoidBottomInset is true by default.

return Scaffold(
      resizeToAvoidBottomInset: false,
   );

I set it to false and it worked fine

Ravindra S. Patil
  • 11,757
  • 3
  • 13
  • 40
3

Consider using scroll padding on the Textfield

return Scaffold(
  appBar: AppBar(
    title: Text("Demo SoftKeyboard"),
  ),
  body: SingleChildScrollView(
    child: Column(
      children: [
          TextField(
            scrollPadding: EdgeInsets.only(bottom:40), // THIS SHOULD SOLVE YOUR PROBLEM
        ),                
      ],
    ),
  ),
);
  • It works when I use `MaterialApp` in my `main.dart`, but not when I use `MaterialApp.router` (or maybe there is another problem). Do you think you know why? – Oleg Yablokov Sep 01 '22 at 14:52
2

I also faced with this issue. This's my solution:

1/ Wrap the Column Widget (content of Dialog) inside the Padding Widget with property padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom,)

2/ Wrap all widgets above inside SingleChildScrollView

Below is full code for my Dialog:

Future<T?> showDialogLikeBorrowBook<T>(
 BuildContext context, {
 bool barrierDismissible = true,
 required String labelDialog,
 required String labelMainButton,
 required Widget contentDialog,
 required Function() onTap,
 }) async {
       return await showGeneralDialog(
       context: context,
       barrierLabel: "barrierLabel",
       barrierDismissible: barrierDismissible,
       barrierColor: Colors.black.withOpacity(0.4),
       transitionDuration: const Duration(milliseconds: 300),
       transitionBuilder: (_, anim1, __, child) {
              return ScaleTransition(
              scale: Tween<double>(
              begin: 0.0,
              end: 1.0,
              ).animate(
                  CurvedAnimation(
                  parent: anim1,
                  curve: Curves.fastOutSlowIn,
                  ),
                 ),
            child: child,
          );
         },
    pageBuilder: (_, __, ___) {
       return Material(
       type: MaterialType.transparency,
       child: Align(
       alignment: Alignment.center,
       child: Padding(
       padding: EdgeInsets.symmetric(horizontal: R.dimens.mediumSpacing1)
            .copyWith(
          top: MediaQuery.of(context).viewPadding.top, // This attribute used to make sure the Dialog widget always show below the AppBar/StatusBar 
                                                       //if the Dialog widget has size with height large more normal size when the keyboard be shown
        ),
         child: GestureDetector(
           onTap: () {
            FocusScope.of(context).requestFocus(FocusNode()); // Wrap Dialog widget inside Gesture Detector to every time the user tap outside the TextField widget but still inside scope of Dialog widget,
                                                              //the FocusNode of TextField will be unfocus 
          },
           child: Container(
             constraints: const BoxConstraints(maxWidth: double.infinity),
             decoration: BoxDecoration(
               borderRadius:
                   BorderRadius.all(Radius.circular(R.dimens.smallRadius)),
               color: Colors.white,
             ),
            padding: EdgeInsets.all(R.dimens.mediumSpacing),
              child: _ShowContentDialog(
               labelDialog: labelDialog,
               labelMainButton: labelMainButton,
               contentDialog: contentDialog,
               onTap: onTap,
               ),
             ),
           ),
         ),
       ),
     );
   },
 );
}

class _ShowContentDialog extends StatelessWidget {
 const _ShowContentDialog();

@override
Widget build(BuildContext context) {
 return SingleChildScrollView(
   physics: BouncingScrollPhysics(),
   child: Padding(
     padding: EdgeInsets.only(
       bottom: MediaQuery.of(context).viewInsets.bottom, // This attribute will auto scale size of Column widget when the keyboard showed
     ),
     child: Column(
       mainAxisSize: MainAxisSize.min,
       children: [
           _renderLabelDialog(),
           ... something widget,
           CustomTextField(
              labelTextField: "Ghi chú",
              hintText: "Nhập ghi chú",
              textInputType: TextInputType.text,
              maxLines: 4,
              textController: _editNoteController,
             ),
           _renderButton(context),
           ],
         ),
       ),
     );
   }
 }

Dialog without the keyboard

Dialog without the keyboard

Dialog with the keyboard when touch on the TextField widget

Dialog with the keyboard when touch on the TextField widget

Nghien Nghien
  • 189
  • 2
  • 6
1

Wrap the entire widget in a Scaffold, then all other widgets contained in a SingleChildScrollView.

0

The fix for me was similar to GrahamD's answer.

I was declaring my own theme using a parent that had .Fullscreen, for example:

<style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar.Fullscreen">
    <item name="android:windowBackground">@android:color/white</item>
</style>

I've raised an issue with the Flutter team because it should be possible to use a Fullscreen theme and have normal Chat app behaviour.

0

I resolved the above issue by adding a Stack() as the body of my Scaffold(), this allows the TextField() object to slide up above the soft keyboard. Initially I used SingleChildScrollView() for the body which resulted in the TextField() objects being obscured by the soft keyboard.

Solution that worked for me:

child: Scaffold(
          resizeToAvoidBottomInset: true,
          body: Stack(
            children: <Widget>[]
David Buck
  • 3,752
  • 35
  • 31
  • 35
Inchy
  • 9
  • 4
0

As per the flutter updates(2021), "resizeToAvoidBottomInset:true" gives a yellow-black strip error when keyboard appears.

This is how I fixed the above issue:

  1. Inside build() method, check if keyboard is open, bool keyboardIsOpen = MediaQuery.of(context).viewInsets.bottom != 0;
  2. Set resizeToAvoidBottomInset:true inside Scaffold
  3. Wrap your widget with a SizedBox() and set height like this: height: keyboardIsOpen ? MediaQuery.of(context).size.height * 0.2 : MediaQuery.of(context).size.width * 0.6,
0

In Flutter, to prevent from this problem - Flutter Keyboard makes TextField hidden – we can do an easy job. We have to Wrap the TextFields with SingleChildScrollView as a widget for body argument in Scaffold. Only use SingleChildScrollView in that place. If you did not do so, it would not work well. For instance:

Widget build(BuildContext context) {
return Scaffold(
  appBar: AppBar(
    title: Text("App"),
  ),
  body: SingleChildScrollView(
    child: Column(
      // mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        Container(
          width: double.infinity,
          child: Card(
            color: Colors.blue,
            elevation: 5,
            child: Text()
          ),
        ),
        TextField(),
        TextField(),

      ],

Also, there is another way do this. In the above code, you can replace Column with ListView Widget like the below code:

Widget build(BuildContext context) {
return Scaffold(
  appBar: AppBar(
    title: Text("App"),
  ),
  body: Container(
    height: 300,
    child: ListView(
      children: [
        Container(
          width: double.infinity,
          child: Card(
            color: Colors.blue,
            elevation: 5,
            child: Text(),
          ),
        ),
        TextField(),
        TextField(),

      ],

    
Ole Pannier
  • 3,208
  • 9
  • 22
  • 33
Mehdi
  • 1
  • 2
0

Here's a complete example which dynamically updates the padding:

before and after keyboard is shown

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

class KeyboardPaddingTest extends StatefulWidget {
  const KeyboardPaddingTest({Key? key}) : super(key: key);

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

class _KeyboardPaddingTestState extends State<KeyboardPaddingTest> {
  EdgeInsets _viewInsets = EdgeInsets.zero;
  SingletonFlutterWindow? window;
  final _textFieldController = TextEditingController();

  @override
  void initState() {
    super.initState();
    window = WidgetsBinding.instance?.window;
    window?.onMetricsChanged = () {
      setState(() {
        final window = this.window;
        if (window != null) {
          _viewInsets = EdgeInsets.fromWindowPadding(
            window.viewInsets,
            window.devicePixelRatio,
          ).add(EdgeInsets.fromWindowPadding(
            window.padding,
            window.devicePixelRatio,
          )) as EdgeInsets;
        }
      });
    };
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      height: double.infinity,
      color: Colors.greenAccent[100],
      alignment: Alignment.bottomCenter,
      child: Padding(
        padding: EdgeInsets.only(bottom: _viewInsets.bottom),
        child: Column(
          children: [
            Expanded(
              child: Center(
                child: Container(
                  width: 200.0,
                  color: Colors.lightBlueAccent[100],
                  child: TextField(
                    controller: _textFieldController,
                    decoration: const InputDecoration(
                      border: InputBorder.none,
                      hintText: 'Tap to show keyboard',
                    ),
                  ),
                ),
              ),
            ),
            const Text(
              'Testing Keyboard',
              style: TextStyle(
                fontSize: 24.0,
                fontWeight: FontWeight.bold,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
vovahost
  • 34,185
  • 17
  • 113
  • 116
0

Be careful to do not remove those two lines from AndroidManifest.xml

android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize"

I did this mistake, all my SingleChildScrollView were not working and the keyboard was hidding the textfield of all my form.

Chloé
  • 331
  • 1
  • 5
  • 14
0

If your content is scrollable but you are not using Scaffold like the other answers mentioned this is the solution I have used

SizedBox(height: (MediaQuery.of(context).viewInsets.bottom != 0) ? 200 : 16)

You can change the 200 and 16 value to some other convenient value as per your needs

SKT
  • 1,821
  • 1
  • 20
  • 32
-1

I had same problem i also used SingleChildScrollView but that doesn't solved my problem.

My problem was accruing in this code.

   Stack(
      childern:[
           SingleChildScrollView(),// In scollView i have textFeild when keyboard opens doneButton hide the textFeild.
           doneButtonWidget()//this button align with the bottom of the screen. 
   ]
)

To Solve the problem i follow this and it solved my problem.

    Column(
       childern:[
            Expaned(  
                child:SingleChildScrollView(),// In scollView i have textFeild when keyboard opens doneButton hide the textFeild.
               flex:1
              ),
              doneButtonWidget()//this button align with the bottom of the screen. 
             ]
          )
Dharman
  • 30,962
  • 25
  • 85
  • 135
Rahul sharma
  • 1,492
  • 12
  • 26