Skip to content
Related Articles

Related Articles

Flutter – Respecting the Softkeyboard Insets
  • Difficulty Level : Expert
  • Last Updated : 17 Jan, 2021

Flutter has made it simpler and easier to make a beautiful and interactive user interface. But there comes a problem faced by many flutter developers while working with soft keyboard inputs in the lower portion of the screen. The problem is whenever a user attempts to fill an input form (whose parent widget is a Card, Container, or something similar) in the lower part of the screen, the soft-keyboard tends to cover that form. The same problem will be replicated below and will show a simple solution to this problem. 

Problem: 

Here, in the app below you can see that whenever the user tries to fill the input form the soft keyboard covers the form and the user can’t move to another line without going back from the keyboard. 

Below is the code of the part which needs to be improved. It mainly contains the input form and some functions to handle the input. If we look at the widget tree of the input form we can see that the parent widget which composed the form is just a simple Card, which further contains two TextFields, a Container with date selection, and a RaisedButton.   

Dart



filter_none

edit
close

play_arrow

link
brightness_4
code

import 'package:flutter/material.dart';
import 'package:intl/intl.dart'
  
class NewTransaction extends StatefulWidget {
  final Function addTx;
  
  NewTransaction(this.addTx);
  
  @override
  _NewTransactionState createState() => _NewTransactionState();
}
  
class _NewTransactionState extends State<NewTransaction> {
  final _titleController = TextEditingController();
  final _amountController = TextEditingController();
  DateTime _selectedDate;
  
  void _submitData() {
    if (_amountController.text.isEmpty) {
      return;
    }
    final enteredTitle = _titleController.text;
    final enteredAmount = double.parse(_amountController.text);
  
    if (enteredTitle.isEmpty || enteredAmount <= 0 || _selectedDate == null) {
      return;
    }
  
    widget.addTx(
      enteredTitle,
      enteredAmount,
      _selectedDate,
    );
  
    Navigator.of(context).pop();
  }
  
  void _presentDatePicker() {
    showDatePicker(
      context: context,
      initialDate: DateTime.now(),
      firstDate: DateTime(2019),
      lastDate: DateTime(2022),
    ).then((pickedDate) {
      if (pickedDate == null) {
        return;
      }
      setState(() {
        _selectedDate = pickedDate;
      });
    });
    print('...');
  }
  
  @override
    
  // widget tree for the card starts hear
  // this is the element which appear on 
  // tap of the floating action button
  Widget build(BuildContext context) {
    return Card(
      elevation: 5,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.end,
        children: <Widget>[
          TextField(
            decoration: InputDecoration(labelText: 'Title'),
            controller: _titleController,
            onSubmitted: (_) => _submitData(),),
            
          //TetFiled
          TextField(
            decoration: InputDecoration(labelText: 'Amount'),
            controller: _amountController,
            keyboardType: TextInputType.number,
            onSubmitted: (_) => _submitData(),),
          Container(
            height: 70,
            child: Row(
              children: <Widget>[
                Expanded(
                  child: Text(
                    _selectedDate == null
                        ? 'No Date Chosen!'
                        : 'Picked Date: ${DateFormat.yMd().format(_selectedDate)}',
                  ),//Text
                ),//Expand
                FlatButton(
                  textColor: Theme.of(context).primaryColor,
                  child: Text(
                    'Choose Date',
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                    ),//TextStyle
                  ),//Text
                  onPressed: _presentDatePicker,
                ),//FlatButton
              ],//<Widget>[]
            ),//Row
          ),//Container
          RaisedButton(
            child: Text('Add Transaction'),
            color: Theme.of(context).primaryColor,
            textColor: Theme.of(context).textTheme.button.color,
            onPressed: _submitData,
          ),//RaisedButton
        ],//<Widget>[]
      ),//Column
    );//Card
  }
}

chevron_right


Solution: 

The solution that we want to achieve is whenever a user taps on the TextFiled and the keyboard comes out the input form should also move up with a height equivalent to the keyboard’s and the form should be scrollable for easy access. This can be achieved in the following steps:

  • Replacing the EdgeInsets.all with EdgeInsets.only in the padding of the Card widget. This will give us control over the individual padding.
  • In the bottom argument of the padding, we will use MediaQuery  (MediaQuery.of(context).viewInsets.bottom) to know the height of the keyboard and add it to the bottom padding. This way we whenever the keyboard will appear the form will move up with the height equivalent to that of the keyboard.
  • At last, we will wrap the entire input form with SingleChildScrollView, to make it scrollable. It will make switching to the next input field easier.

Dart

filter_none

edit
close

play_arrow

link
brightness_4
code

// Snippet of the Input form widget tree
return SingleChildScrollView(
  
      // change 3
      child: Card(
        elevation: 5,
        child: Container(
          padding: EdgeInsets.only(
  
            // change 1
              top: 10,
              bottom: MediaQuery.of(context).viewInsets.bottom + 10,
  
              // chage 2
              left: 10,
              right: 10),

chevron_right


This is how the input form will behave after the correction. The input form moves up in accordance with the height of the soft-keyboard, which makes all the fields visible. And in addition to that, the form is also scrollable now.

My Personal Notes arrow_drop_up
Recommended Articles
Page :