Trim() input value of any TextField in a Form by default in flutter app Trim() input value of any TextField in a Form by default in flutter app dart dart

Trim() input value of any TextField in a Form by default in flutter app


just add

inputFormatters: [WhitelistingTextInputFormatter(RegExp(r'[a-zA-Z0-9]'))],

as property to TextInputFieldand user will not even able to type space or any other chars except whitelistedand you can remove also additional checks from validator

full example

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: Scaffold(        body: SafeArea(          child: Center(            child: TextFormField(              inputFormatters: [WhitelistingTextInputFormatter(RegExp(r'[a-zA-Z0-9]'))],              keyboardType: TextInputType.text,              decoration: new InputDecoration(                labelText: 'Enter your nickname',              ),              validator: (val) {                if (val.isEmpty == true) {                  return 'Nickname is required!';                }                return null;              },              onSaved: (val) {},            ),          ),        ),      ),    );  }}


Trim the text value on onChanged callback and assign it back to the controller.


As @Darish suggested, here is the sample code for it.

A caveat though, need to select at the end of text if trimmed. This will only work if spaces in between are disallowed.

class _MyHomePageState extends State<MyHomePage> {  final alphaNumericText = RegExp(r'^[a-zA-Z0-9]+$');  final textController = TextEditingController();  @override  void dispose() {    super.dispose();    textController?.dispose();  }  @override  Widget build(BuildContext context) {    return Scaffold(      body: Center(        child: TextFormField(          controller: textController,          keyboardType: TextInputType.text,          decoration: new InputDecoration(            labelText: 'Enter your nickname',          ),          onChanged: (val) {            final trimVal = val.trim();            if (val != trimVal)              setState(() {                textController.text = trimVal;                textController.selection = TextSelection.fromPosition(TextPosition(offset: trimVal.length));              });          },          validator: (val) {            if (val.isEmpty == true) {              return 'Nickname is required!';            }            if (alphaNumericText.hasMatch(val) == false) {              return 'Use alphanumeric characters only in nickname.';            }            return null;          },        ),      ),    );  }}