Home > other >  How to remove empty lines in TextField/TextFormField in Flutter?
How to remove empty lines in TextField/TextFormField in Flutter?

Time:12-29

is it possible to remove empty lines in TextField/TextFormField? After typing some input I type shift enter to create some new empty lines, and then my controller takes all these empty lines.

CodePudding user response:

Get the string from textfield. Let's call this string s and then just do s.trimRight() to automatically delete all empty spaces from the right side. Similarly you can do s.trimLeft() to delete empty spaces from the left.

CodePudding user response:

There are two places you would want to deny whitespaces.

1.While Input is entered.

TextFormField(
     validator: (value),
     inputFormatters: [
          FilteringTextInputFormatter.deny(new RegExp(r"\s\b|\b\s"))
        ],
     )

2.After Input is entered.

TextFormField(
      controller: _controller,
      ....
)

Use: _controller.trim() this will trim all the whitespace in the textformfield

CodePudding user response:

border: InputBorder.none, in decoration:const InputDecoration()

Try this code:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  final String title;

  const MyHomePage({
    Key? key,
    required this.title,
  }) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final TextEditingController _textController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
           TextFormField(
                controller: _textController,
                style: const TextStyle(
                  fontSize: 14,
                  fontFamily: 'Work_Sans',
                  fontWeight: FontWeight.w500,
                ),
                decoration:const InputDecoration(
                  hintText: 'Type Here',
                  border: InputBorder.none,
                  fillColor: Colors.white,
                  hintStyle:  TextStyle(
                    fontSize: 14,
                    color: Colors.grey,
                    fontFamily: 'Work_Sans',
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }
}

  • Related