使用 TextEditingController 设置初始值后,在 TextField 中编辑值

Anu*_*Izu 2 flutter texteditingcontroller

我将一些用户信息从第一个屏幕传递到第二个屏幕,在第二个屏幕上,我尝试在文本字段内编辑该信息。我的第二个屏幕的代码如下。

class EditProfile extends StatefulWidget {
  String profName;
  String profOcc;
  EditProfile({Key? key, required this.profName, required this.profOcc,}): super(key: key);

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

class _EditProfileState extends State<EditProfile> {

  @override
  Widget build(BuildContext context) {
    var nameController = TextEditingController()..text = widget.profName;
    var occController = TextEditingController()..text = widget.profOcc;

    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).scaffoldBackgroundColor,
        elevation: 1,
        leading: IconButton(
          icon: Icon(
            Icons.arrow_back,
            color: Color(0xFF6f6bdb),
          ),
          onPressed: (){
            Navigator.pop(context);
          },
          ),
    ),
    body: Container(
      padding: EdgeInsets.fromLTRB(30.0, 30.0, 30.0, 0.0),
      child: GestureDetector(
        onTap: () {FocusScope.of(context).unfocus();},
        child: ListView(
          children: [
            Text(
              "Edit Profile",
            ),
            SizedBox(height: 20.0),
            createInputField("NAME", nameController),
            createInputField("OCCUPATION", occController),
            SizedBox(height: 25.0),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                ElevatedButton(
                  onPressed: () async {
                    //// Update the values when pressed
                  },
                  style: ElevatedButton.styleFrom(
                    primary: Color(0xFF6f6bdb), // background
                    padding: EdgeInsets.symmetric(horizontal: 50),
                  ),
                  child: Text(
                    "UPDATE",
                  )
                ),
              ],
            )
          ],
        ),
      ),
    ),
    );
  }

  TextField createInputField(String labelText, TextEditingController controller) {
    return TextField(
            controller: controller,
            decoration: InputDecoration(
              isDense: true,
              labelText: "$labelText:",
              floatingLabelBehavior: FloatingLabelBehavior.always,
              hintStyle: TextStyle(
                fontSize: 16, fontWeight: FontWeight.w700,
                color: Colors.black,
              )
            ),
          );
  }
Run Code Online (Sandbox Code Playgroud)

我的问题是,由于我正在初始化 Widget 内的文本编辑控制器,因此当我编辑 TextField 中的值然后使字段散焦时,TextField 内的值将恢复为初始值。我的问题是,有没有办法在小部件外部初始化文本编辑控制器,并仍然使用我从第一个屏幕获取的值设置初始值?widget.profName在 Widget 之外不起作用。非常感谢对此的任何帮助。

Icy*_*her 8

您可以通过在 init 字段中设置其值,在构建方法之外创建 TextEditingController。就像这样,

class SecondPage extends StatefulWidget {
  final String myString;
  const SecondPage({Key? key, required this.myString}) : super(key: key);

  @override
  State<SecondPage> createState() => _SecondPageState();
}

class _SecondPageState extends State<SecondPage> {


late final TextEditingController controller;
  @override
  void initState() {
    super.initState();
    controller = TextEditingController(text: widget.myString);
  }
  
  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }
Run Code Online (Sandbox Code Playgroud)

late您还可以做的另一种方法是,如果您分配给变量,则在初始化字段之外分配值

class SecondPage extends StatefulWidget {
  final String myString;
  const SecondPage({Key? key, required this.myString}) : super(key: key);

  @override
  State<SecondPage> createState() => _SecondPageState();
}

class _SecondPageState extends State<SecondPage> {


late final TextEditingController controller = TextEditingController(text: widget.myString);

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }
Run Code Online (Sandbox Code Playgroud)

请记住在停止使用 textController 后将其丢弃。链接: https: //api.flutter.dev/flutter/widgets/TextEditingController-class.html