Home > Software engineering >  Change color of text after reaching certain number limit?
Change color of text after reaching certain number limit?

Time:11-27

I need to make a textfield that only accepts up to 100 (as string) maximum, if they type 101 or more it should turn red, can you do this in flutter with or without an outside package?

I have no idea where to even start, is the first time i do something this kind.

CodePudding user response:

You can use this custom widget, remember I set the limit to 5 for test:

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

  @override
  State<CustomInput> createState() => _CustomInputState();
}

class _CustomInputState extends State<CustomInput> {
  Color textColor = Colors.black;
  int limit = 5;
  @override
  Widget build(BuildContext context) {
    return TextField(
      decoration: InputDecoration(hintText: 'some text'),
      onChanged: (value) {
        if (value.length > limit && textColor == Colors.black) {
          setState(() {
            textColor = Colors.red;
          });
        } else if (value.length <= limit && textColor == Colors.red) {
          setState(() {
            textColor = Colors.black;
          });
        }
      },
      style: TextStyle(
        color: textColor,
      ),
    );
  }
}

and use it like this:

Scaffold(
  key: _key,
  backgroundColor: Colors.white,
  appBar: AppBar(),
  body: Column(
    children: [
      SizedBox(
        height: 10,
      ),
      CustomInput(),
    ],
  ),
)

enter image description here

CodePudding user response:

To change the text color on the TextField if it exceeds 100 characters, you can do the following:

Every TextField has a style property that accepts a TextStyle(). Simply set the color to red if the controller exceeds 100 characters.

Here's a complete runnable example:

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: Scaffold(
        body: CustomTextField(),
      ),
    );
  }
}

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

  @override
  State<CustomTextField> createState() => _CustomTextFieldState();
}

class _CustomTextFieldState extends State<CustomTextField> {
  final TextEditingController _controller = TextEditingController();

  @override
  Widget build(BuildContext context) {

    return TextField(
      maxLength: 100,
      decoration: const InputDecoration(
        border: OutlineInputBorder(),
        labelText: 'Enter your text',
      ),
      onChanged: (text) {
        setState(() {
          // update the text color
          _controller.text = text;
        });
      },
      style: TextStyle(
        color: (_controller.text.length > 100) ? Colors.red : Colors.black,
      ),
    );
  }
}
  • Related