How to Limit Characters of TextField in Flutter
TextField is where the user gives input in Flutter-made apps. Most of the time, we may want to limit the number of characters. In this flutter tutorial, let’s check how to limit the 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.
See the code snippet given below.
TextField(
controller: _controller,
maxLength: 5,
onSubmitted: (String value) {
debugPrint(value);
},
),
The additional characters typed are ignored. The TextField also shows the number of typed characters as well as the maximum character limit.
The following will be the output.
Following is the complete example.
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Flutter TextField max limit'),
),
body: const MyStatefulWidget());
}
}
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({super.key});
@override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
late TextEditingController _controller;
@override
void initState() {
super.initState();
_controller = TextEditingController();
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Center(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Center(
child: Column(children: <Widget>[
TextField(
controller: _controller,
maxLength: 5,
onSubmitted: (String value) {
debugPrint(value);
},
),
]),
)));
}
}
I hope this Flutter tutorial on TextField maximum limit is helpful for you.