dart 为什么在Flutter中,当我转到另一个页面时,TextField中的文本消失了?

jv2fixgn  于 2022-12-25  发布在  Flutter
关注(0)|答案(1)|浏览(267)

我在TextField中输入文本。当我单击按钮转到另一页并返回时,TextField中的文本消失。有人遇到过这个问题吗?可以给我一些建议吗?
我的代码:

Column(
  children: [
    ListTile(
      onTap: () async {
        Navigator.of(context).push(MaterialPageRoute(builder: (context) => …)); // In fact, I used go_router, just replaced it with the Navigator that everyone should know
      },
      leading: const Icon(Icons.location_pin, color: Colors.black),
      title: Text("Location"),
    ),
    ListTile(
      leading: const Icon(Icons.message, color: Colors.black),
      title: TextFormField(
        controller: messageController,
        decoration: InputDecoration(
          border: InputBorder.none,
          hintText: "Message",
        ),
      ),
    ),
  ],
),

如果您需要更多信息,请随时发表评论。
为什么在Flutter中,当我进入另一个页面时,TextField中的文本消失了?我将感激任何帮助。提前感谢!

dxxyhpgq

dxxyhpgq1#

这是因为您在导航到此页面时创建了TextEditingController,因此它将使用空文本创建。
因此,您可以使控制器全局化,而不是在StatefulWidget内部。

import 'package:flutter/material.dart';

class SearchScrean extends StatefulWidget {
  const SearchScrean({super.key});

  @override
  State<SearchScrean> createState() => _SearchScreanState();
}

class _SearchScreanState extends State<SearchScrean> {
  // you probably initialize the controller here or in initState.
  TextEditingController messageController = TextEditingController(); 
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(children: [
        TextFormField(
          controller: messageController,
          decoration: InputDecoration(
            border: InputBorder.none,
            hintText: "Message",
          ),
        ),
      ]),
    );
  }
}

看评论。
您必须像这样在外部初始化它,或者使用状态管理包,例如blocprovider

import 'package:flutter/material.dart';

// initialize it here or in another global file
TextEditingController messageController = TextEditingController(); 

class SearchScrean extends StatefulWidget {
  const SearchScrean({super.key});

  @override
  State<SearchScrean> createState() => _SearchScreanState();
}

class _SearchScreanState extends State<SearchScrean> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(children: [
        TextFormField(
          controller: messageController,
          decoration: InputDecoration(
            border: InputBorder.none,
            hintText: "Message",
          ),
        ),
      ]),
    );
  }
}

当你不再需要它的时候就用messageController.dispose()处理掉它

相关问题