Flutter Textfield Capitalize Each Word

1.5k Views Asked by At
class InputMdnWidget extends StatefulWidget {
  const InputMdnWidget({Key key}) : super(key: key);
  @override
  _InputMdnWidgetState createState() => _InputMdnWidgetState();
}

class _InputMdnWidgetState extends State<InputMdnWidget> {
  TextEditingController _controller;
  
  @override
  void initState() {

    super.initState();
    _controller = TextEditingController();
  }
  @override
  Widget build(BuildContext context) {
    return TextField(
      controller: _controller,
      textCapitalization: TextCapitalization.words       
    );
  }
}

i'm new to flutter, i have a textfield and using a controller, i want to make the text that the user typed into camel case, for example the user types "lala lala", the text in the textfield will change to "Lala Lala", is this possible and how?

I use textCapitalization: TextCapitalization.words doesn't work

2

There are 2 best solutions below

0
On BEST ANSWER

You can try using TextInputFormatters. These make input conform to particular patterns, and can be supplied to TextFields like so:

TextField(
  controller: _controller,
  inputFormatters: [MyInputFormatter()],       
);

If you want custom formatting, and I think you're wanting "title case," you can create your own TextInputFormatter by extending the class like this:

import 'package:flutter/services.dart';

class TitleCaseInputFormatter extends TextInputFormatter {
  String textToTitleCase(String text) {
    if (text.length > 1) {
      return text[0].toUpperCase() + text.substring(1);
      /*or text[0].toUpperCase() + text.substring(1).toLowerCase(), if you want absolute title case*/
    } else if (text.length == 1) {
      return text[0].toUpperCase();
    }

    return '';
  }

  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {
    String formattedText = newValue.text
        .split(' ')
        .map((element) => textToTitleCase(element))
        .toList()
        .join(' ');
    return TextEditingValue(
      text: formattedText,
      selection: newValue.selection,
    );
  }
}

Again, use it like this:

TextField(
  controller: _controller,
  inputFormatters: [TitleCaseInputFormatter()],       
);
4
On

This way you can handle on web also. also you can check this answer for format explanation.

place it somewhere

extension CapExtension on String {
  String get inCaps =>
      this.length > 0 ? '${this[0].toUpperCase()}${this.substring(1)}' : '';

  String get capitalizeFirstofEach => this
      .replaceAll(RegExp(' +'), ' ')
      .split(" ")
      .map((str) => str.inCaps)
      .join(" ");
}

and use it like text.capitalizeFirstofEach.

import 'package:flutter/material.dart';

class Expandeddd extends StatefulWidget {
  Expandeddd({Key? key}) : super(key: key);

  @override
  _ExpandedddState createState() => _ExpandedddState();
}


class _ExpandedddState extends State<Expandeddd> {
  final controller = TextEditingController();

  @override
  void initState() {
    super.initState();
    controller.addListener(() {
      final text = controller.text;

      /// dont set Text here
      controller.selection =
          TextSelection.fromPosition(TextPosition(offset: text.length));
    });
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        constraints: BoxConstraints(
          maxHeight: 812,
          minHeight: 300,
        ),
        child: Column(
          children: [
            TextField(
              controller: controller,
              textCapitalization: TextCapitalization.words,
              keyboardType: TextInputType.text,
              autocorrect: false,
              onChanged: (value) {
                controller.text = value.capitalizeFirstofEach;
              },
              style: TextStyle(
                fontSize: 30.0,
                color: Colors.black,
                fontWeight: FontWeight.bold,
              ),
            ),
          ],
        ),
      ),
    );
  }
}