How to Limit Characters of TextField in Flutter

TextField is where user gives input in flutter made apps. Most of the times, we may want to limit the number of characters. In this flutter tutorial, let’s check how to limit characters of TextField.

I hope you already know how to add a TextField widget in flutter, otherwise please go through my blog post here. Limiting the maximum number of characters in TextField is pretty easy. All you need to do is to make use of maxLength property and maxLengthEnforced property of TextField as given below.

TextField(
          controller: myController,
          maxLength: 5,
          maxLengthEnforced: true,
        ),

The addition characters typed are ignored. By the way it will show an error when the user exceeds the limit.

Following is the complete example.

import 'package:flutter/material.dart';

void main() => runApp(App());

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Max Length Example',
      home: MyInput(),
    );
  }
}

// Define a custom Form widget.
class MyInput extends StatefulWidget {
  @override
  _MyInputState createState() => _MyInputState();
}

// Define a corresponding State class.
// This class holds the data related to the Form.
class _MyInputState extends State<MyInput> {
  // 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 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,
          maxLengthEnforced: true,
        ),
      ),
      ),   
    );
  }
}

Following is the output of this tutorial.

I hope this flutter tutorial will be helpful for you.

Leave a Comment

Your email address will not be published. Required fields are marked *