Default TextField will obtain maximum number of character inside it. But in many cases developer wants to get only fixed number of character from TextField. Like there will be a restriction that user is not allow to enter more then 12 characters in the name or not more than 10 digits as phone number. We will use maxLength property of TextField to control character limit.
Flutter TextField Input Character Limit Fix
1. Creating a TextEditingController to store entered text in TextField.
final inputController = TextEditingController();
2. Defining border style for TextField on focus and without focus.
static const border = OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(12.0)),
borderSide: BorderSide(color: Colors.blueGrey, width: 1.8),
);
static const focusBorder = OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(8.0)),
borderSide: BorderSide(color: Colors.green, width: 1.8));
3. Defining maxLength on TextField to set input character limit.
TextField(
controller: inputController,
decoration: const InputDecoration(
hintText: 'Enter Name Here...',
enabledBorder: border,
focusedBorder: focusBorder),
maxLength: 12)
Source code for main.dart file:
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(home: Scaffold(body: Center(child: App())));
}
}
class App extends StatefulWidget {
const App({super.key});
@override
AppState createState() => AppState();
}
class AppState extends State < App > {
final inputController = TextEditingController();
static const border = OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(12.0)),
borderSide: BorderSide(color: Colors.blueGrey, width: 1.8),
);
static const focusBorder = OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(8.0)),
borderSide: BorderSide(color: Colors.green, width: 1.8));
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Center(
child: Column(children: < Widget > [
Container(
margin: const EdgeInsets.all(12),
child: TextField(
controller: inputController,
decoration: const InputDecoration(
hintText: 'Enter Name Here...',
enabledBorder: border,
focusedBorder: focusBorder),
maxLength: 12)),
]))));
}
}
Comments
Post a Comment