How to Set Max Length Limit on TextFiled in Flutter

In this example, we are going to show you how to set the maximum length limit of characters in TextField/TextFormFiled input in the Flutter app. See the example below:

TextField(
    maxLength: 5
),

//OR

TextFormField(
    maxLength: 5
)

Output:

TextField(
    maxLength: 5,
    maxLengthEnforcement: MaxLengthEnforcement.none,
)

Output:

 

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
     return MaterialApp(
        home: Home()
      );
  }
}

class Home extends  StatefulWidget {
  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
         backgroundColor: Colors.lightBlue[50],
         appBar: AppBar(
            title: Text("Set Max Length on TextField"),
            backgroundColor: Colors.redAccent
         ),
          body: Container(
             
             margin: EdgeInsets.all(30),
             alignment: Alignment.topCenter,
             child: Column(
                 children: [
                      TextField(
                         maxLength: 5,
                         maxLengthEnforcement: MaxLengthEnforcement.enforced,
                      ),

                      TextFormField(
                         maxLength: 5,
                         maxLengthEnforcement: MaxLengthEnforcement.none,
                      )
                 ],
             ),
          )
      );
  }
}

In this way, you can set the max length limit on TextField and TextFormField widget in Flutter app.

No any Comments on this Article


Please Wait...