How to add specific fixed value to TextField?

176

You can use the onChanged callback to process the value entered by the user. Once we have what is inside the text field, we can do our logic in there and set the value we want to the textController. But, once we programmatically set a value to the textController, the cursor goes to the zero position; so, we need to change that as well. Snippet below.

enter image description here

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Postfix Text Controller',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        brightness: Brightness.dark,
      ),
      home: const MyHomePage(),
    );
  }
}

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

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

class _MyHomePageState extends State<MyHomePage> {
  final TextEditingController _textController = TextEditingController();
  final String _userPostfix = "[user]";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: const Text("Postfix Text Controller"),
      ),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(15.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              TextFormField(
                controller: _textController,
                onChanged: (value) {
                  if (value == _userPostfix) {
                    _textController.text = "";
                    return;
                  }
                  value.endsWith(_userPostfix)
                      ? _textController.text = value
                      : _textController.text = value + _userPostfix;
                  _textController.selection = TextSelection.fromPosition(
                      TextPosition(
                          offset: _textController.text.length -
                              _userPostfix.length));
                },
                decoration: const InputDecoration(
                  labelText: "User",
                  border: OutlineInputBorder(),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
Share:
176
AZxBB
Author by

AZxBB

jnunior DevOps engineer

Updated on December 30, 2022

Comments

  • AZxBB
    AZxBB over 1 year

    I want to add fixed not editable text to TextField

    For example: when the user enter's Name after name there should be fixed text [user]

    the result should be: Alexandra[user]
    

    When user typing the name, fixed word [user] must be always there!

    I hope you got what I want any related topics links will be helpful!

    I tried similar Initial text but its editable by the user, mine should be fixed

    Controller: TextEditingController(text: "Initial Text here"),
    

    My TextField now:

    TextField(
          decoration: InputDecoration(
            labelText: ENTER_NAME,
            labelStyle: GoogleFonts.poppins(
                color: LIGHT_GREY_TEXT,
                fontWeight: FontWeight.w400
            ),
            border: UnderlineInputBorder(),
            focusedBorder: UnderlineInputBorder(
                borderSide: BorderSide(color: LIGHT_GREY_TEXT)
            ),
            errorText: isNameError ? ENTER_NAME : null,
          ),
          style: GoogleFonts.poppins(
              color: BLACK,
              fontWeight: FontWeight.w500
          ),
          onChanged: (val){
            setState(() {
              name = val;
              isNameError = false;
            });
          },
        ),
    
    • flutter_bee
      flutter_bee almost 3 years
      the only thing closest is hintText which displays the text when the user selected the field but haven't entered anything. e.g, hintText: 'Enter a search term',
    • AZxBB
      AZxBB almost 3 years
      @flutter_bee but (a) hintText disappears when the user starts typing (b) the value of hintText will not insert to Database. I need which satisfies both options