如果我使用 ConnectionState.waiting,每次我尝试向 TextField 输入一些文本时,屏幕都会自行重建

Screen rebuilds itself every time I try to enter some text to TextField if I use ConnectionState.waiting

我想使用 firestore 构建一个实时更改的配置文件屏幕。 每当打开个人资料屏幕时,我都会在很短的时间内收到此错误:

The following _CastError was thrown building StreamBuilder<DocumentSnapshot>(dirty, dependencies: [_LocalizationsScope-[GlobalKey#f10b3], _InheritedTheme], state: _StreamBuilderBaseState<DocumentSnapshot, AsyncSnapshot<DocumentSnapshot>>#47356):
Null check operator used on a null value

The relevant error-causing widget was: 
  StreamBuilder<DocumentSnapshot> file:///C:/Users/batuh/AndroidStudioProjects/flutter_appp/lib/screens/profile.dart:40:13
When the exception was thrown, this was the stack: 
#0      _ProfileState.build.<anonymous closure> (package:flutter_appp/screens/profile.dart:107:42)
#1      StreamBuilder.build (package:flutter/src/widgets/async.dart:545:81)
#2      _StreamBuilderBaseState.build (package:flutter/src/widgets/async.dart:124:48)
#3      StatefulElement.build (package:flutter/src/widgets/framework.dart:4612:27)
#4      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4495:15)

但在那一刻之后,它获取数据并运行良好。我知道我需要使用下面的代码来防止这种情况,就像 Flutter 文档所说的那样。

if (snapshot.connectionState == ConnectionState.waiting) {
        return Center(
          child: CircularProgressIndicator(),
        );
      }

但是每当我使用该代码时,每次我按下 TextField 时,配置文件页面都会自行重建,因此它不允许我输入任何文本。如果不使用上面的代码,一切正常,我可以在 TextFields 中输入一些文本,并且正在更新用户数据。我不知道该怎么办。我是否错误地使用了流生成器?我该怎么办?

这是我的 profile.dart 文件中 stful 小部件的脚手架:

Scaffold(
  appBar: AppBar(
    leading: IconButton(
      icon: Icon(FontAwesomeIcons.arrowLeft),
      onPressed: () => Navigator.pop(context),
    ),
    actions: [
      IconButton(
        icon: Icon(FontAwesomeIcons.cog),
        onPressed: () => Navigator.pushNamed(context, '/settings'),
      )
    ],
  ),
  body: StreamBuilder<DocumentSnapshot>(
    stream: users.doc(FirebaseAuth.instance.currentUser!.uid).snapshots(),
    builder:
        (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
      if (snapshot.hasError) {
        return Text("Something went wrong");
      }

      return Container(...);

固定版本:

if (snapshot.hasError) {
            return Text("Something went wrong");
          } else if(snapshot.hasData || snapshot.connectionState == ConnectionState.active) {
            return Container(...);
          } else {
            return Center(
              child: CircularProgressIndicator(),
            );
          }

您可以尝试去掉“!”在“数据”上,因为每次触发“TextField”时,它都会立即查找数据。 “!”在空安全中意味着它不能是空对象或空事物。尝试先删除它,因为我猜您的 Stream 生成器充当搜索推荐

你在哪里定义你的TextEditingController?如果它在 StatelessWidget 中,请尝试将其转换为 StatefulWidget。每当您刷新 StatlessWidget 的状态时,它都会重新实例化其字段(在您的情况下,您的 TextEditingController ...)。这种行为对于 StatefulWidget 是不正确的,因为状态被保留了。