问题描述
我想向 TextField 添加固定的不可编辑文本
例如:当用户在姓名后输入姓名时,应该有固定文本[user]
the result should be: Alexandra[user]
当用户输入姓名时,固定词 [user]
必须始终存在!
我尝试了类似的初始文本,但用户可以对其进行编辑,我的应该已修复
Controller: TextEditingController(text: "Initial Text here"),
我现在的 TextField:
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;
});
},
解决方法
您可以使用 onChanged 回调来处理用户输入的值。一旦我们有了文本字段中的内容,我们就可以在其中执行我们的逻辑并将我们想要的值设置为 textController。但是,一旦我们以编程方式为 textController 设置了一个值,光标就会移到零位置;所以,我们也需要改变它。下面的片段。
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(),],);
}
}