How to Limit Characters of TextField in Flutter

Last updated Oct 18, 2021


In this Flutter TextInput example series we will create how to limit characters of TextField in Flutter. While we fill any form there might be a scenario to limit the number of characters while we type the text in input fields, for example when we enter the mobile number there will be some certain limit based on country. To set the limit for the input field we will use maxLength: propery.

 

TextField(
  controller: myController,
  maxLength: 5,
  maxLengthEnforcement: MaxLengthEnforcement.enforced,
)

 

 

Let's create simple flutter example to limit the character for the TextInput field

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

class InputFieldLength extends StatefulWidget {
  @override
  _InputFieldLengthState createState() => _InputFieldLengthState();
}

// Define a corresponding State class.
// This class holds the data related to the Form.
class _InputFieldLengthState extends State {
  // Create a text controller and use it to retrieve the current value
  // of the TextField.
  final myController = TextEditingController();

  @override
  void dispose() {
    // Clean up the controller when the widget is disposed.
    myController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter max length tutorial'),
        ),
        body: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Center(child: TextField(
            controller: myController,
            maxLength: 5,
            maxLengthEnforcement: MaxLengthEnforcement.enforced,
          ),
          ),
        ),
      ),
    );
  }
}

 

 

output:

Flutter text limit to the inputfield

 

Conclusion: In this flutter tutorial series we covered how to set text limit to the inputfield in flutter.

 


Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

66 Views

Subscribe For Daily Updates

Flutter Questions
Android Questions