我有一个ConsumerWidget,我用它来观察供应商的状态.一切都在工作,除了TextEditingControllers.每当我在文本字段中键入内容并单击手机键盘上的完成按钮时,文本字段又会变空.我认为这是由于该部件的状态.所以我的问题是,如何在ConsumerWidget里面使用TextEditingController,它没有createState方法?

这是我的代码.提前感谢:


class MainPage extends ConsumerWidget {
  const MainPage({super.key});

  @override
  Widget build(BuildContext context, ref) {
    // provider
    final roomListData = ref.watch(roomDataProvider);

    final roomService = RoomService();

    final roomIDController = TextEditingController();
    final roomPasswordController = TextEditingController();

    // UI screen size
    final size = MediaQuery.of(context).size;

    double deviceWidth = size.width;
    double deviceHeight = size.height;

    return Scaffold(
        backgroundColor: bluePrimary,
        body: SingleChildScrollView(
          child: roomListData.when(
              data: (data) {
                List<RoomModelResponse> roomList =
                    data.map((room) => room).toList();
                return SafeArea(
                    child: Container(
                  padding:
                      const EdgeInsets.symmetric(horizontal: 36, vertical: 16),
                  child: Column(
                      //crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            IconButton(
                              iconSize: deviceWidth * 0.09,
                              icon: const Icon(Icons.person_outline,
                                  color: orangePrimary),
                              onPressed: () {
                                Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                        builder: (context) =>
                                            const DetailedProfilePage()));
                              },
                            ),
                            IconButton(
                              icon: const Icon(
                                Icons.add,
                                color: orangePrimary,
                              ),
                              iconSize: deviceWidth * 0.09,
                              onPressed: () {
                                Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                      builder: (context) =>
                                          const CreateRoomScreen()),
                                );
                              },
                            )
                          ],
                        ),
                      
                        SizedBox(height: deviceHeight * 0.04),
                        Align(
                          alignment: Alignment.centerLeft,
                          child: Text("Join room",
                              style: TextStyle(
                                fontFamily: 'Chalet',
                                fontSize: deviceWidth * 0.05,
                                color: whitePrimary,
                                fontWeight: FontWeight.w100,
                              )),
                        ),
                        SizedBox(height: deviceHeight * 0.008),

                        // room ID textField
                        SizedBox(
                          width: MediaQuery.of(context).size.width * 0.85,
                          child: TextField(
                            controller: roomIDController,
                            decoration: InputDecoration(
                                filled: true,
                                fillColor: whitePrimary,
                                border: OutlineInputBorder(
                                    borderRadius: BorderRadius.circular(12),
                                    borderSide: BorderSide.none),
                                hintText: 'Enter room ID to join it',
                                hintStyle: const TextStyle(
                                    color: Color.fromARGB(255, 174, 173, 173))),
                          ),
                        ),

                        SizedBox(height: deviceHeight * 0.01),

                        // room password textField
                        SizedBox(
                          width: MediaQuery.of(context).size.width * 0.85,
                          child: TextField(
                            obscureText: true,
                            controller: roomPasswordController,
                            decoration: InputDecoration(
                                filled: true,
                                fillColor: whitePrimary,
                                border: OutlineInputBorder(
                                    borderRadius: BorderRadius.circular(12),
                                    borderSide: BorderSide.none),
                                hintText:
                                    'Leave blank if the room has no password',
                                hintStyle: const TextStyle(
                                    color: Color.fromARGB(255, 174, 173, 173))),
                          ),
                        ),

...

推荐答案

您也可以使用钩子(flutter_hooks包)和HookConsumerWidget.那么您的代码将会更短.您还需要一个套餐hooks_riverpod:

class MainPage extends HookConsumerWidget {
  const MainPage({super.key});

  @override
  Widget build(BuildContext context, ref) {

    final roomListData = ref.watch(roomDataProvider);

    final roomIDController = useTextEditingController();
    final roomPasswordController = useTextEditingController();

    return Scaffold(...);
  }
}

Hooks负责对象本身的生命周期,因此您不必通过dispose方法手动处理它们.

左:

Flutter相关问答推荐

如何增加容器高度?

当MyChangeNotifier更改时如何计算函数,而无需在构建方法中进行不必要的调用- Flutter

使用自定义控制器将项插入到ListView中时行为不正确

在保持标高=1的情况下更改AppBar立面 colored颜色 /遮罩

如何将 colored颜色 阴影作为默认容器 colored颜色 应用于自定义窗口小工具?

Flutter API请求BadState响应

如何使用flutter_local_notification包处理通知操作?

将列表<;Events>;从Flutter 应用程序中的函数传回EventLoader属性时出错

Flutter GestureDetector单击问题-堆叠外面的按钮不可点击

如何在 Flutter 中以背景 colored颜色 制作圆圈的一部分

无法在 Flutter 项目中安装最新版本的 image_picker

添加appBar时绘制的线条发生偏移 Flu

在Flutter中为容器实现线性渐变背景动画

Firestore 使用 Flutter 以奇怪的格式保存数据

我对 Flutter Apk 有疑问

如何将行推到列的底部

是否有可能减少代码的编写,例如:ref.read(countProvider.notifier) - 在构建方法中?

如何在 Flutter 中滚动时为多个小部件设置动画

通过点击缩略图加载全屏图像

如何在屏幕按钮中排列 row() (我想在按钮中放置屏幕导航图标)