Flutter 断言失败:'initialValue == null || controller == null':不正确

Flutter Failed assertion: 'initialValue == null || controller == null': is not true

我正在尝试将在 firestore 中输入的数据提取到我的 TextFormField 中,以便将其作为配置文件更新部分,但在这样做时我遇到了这个错误 Failed assertion: line 150 pos 15: 'initialValue == null || controller == null': is not true. 我不熟悉它,任何人都可以指导我在哪里犯了错误我该如何解决?这也是我制作配置文件更新部分的正确方法。用户将首先输入数据,默认情况下它是空的,当用户再次返回此屏幕时,应该向用户显示之前保存的数据,这正是我想要的。

这是我的代码:

 final TextEditingController _peopletohangoutwithController =
      TextEditingController();// Controller 

// 其余代码

 FutureBuilder<DocumentSnapshot>(
            future: FirebaseFirestore.instance
                .collection("userpreferences")
                .doc(FirebaseAuth.instance.currentUser!.uid)
                .get(),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.done) {
                print(snapshot.hasData);
                print(snapshot.data!["peopletohangoutwith"]);
              }
              return Column(
                children: [
                  const SizedBox(
                    height: 50,
                  ),
                  Row(
                    children: [
                      Align(
                        alignment: Alignment.topLeft,
                        child: DelayedDisplay(
                            delay: const Duration(seconds: 1),
                            child: Padding(
                              padding: const EdgeInsets.only(left: 10),
                              child: IconButton(
                                icon: const Icon(
                                  Icons.arrow_back_ios,
                                  color: Colors.white,
                                ),
                                onPressed: () {
                                  Navigator.of(context).pop();
                                },
                              ),
                            )),
                      ),
                      const Align(
                        alignment: Alignment.topCenter,
                        child: DelayedDisplay(
                          delay: Duration(seconds: 1),
                          child: Text(
                            "Hang out with",
                            style: TextStyle(
                                fontSize: 26,
                                color: Colors.white,
                                fontFamily: "ProductSans",
                                fontWeight: FontWeight.bold),
                          ),
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(
                    height: 50,
                  ),
                  const DelayedDisplay(
                    delay: Duration(seconds: 2),
                    child: Center(
                      child: Padding(
                        padding: EdgeInsets.only(left: 10, right: 10),
                        child: Text(
                          "What type of people you want to hang out with",
                          style: TextStyle(
                              fontSize: 20,
                              color: Colors.white,
                              fontFamily: "ProductSans",
                              fontWeight: FontWeight.bold),
                        ),
                      ),
                    ),
                  ),
                  const SizedBox(
                    height: 50,
                  ),
                  DelayedDisplay(
                    delay: const Duration(seconds: 2),
                    child: Padding(
                      padding: const EdgeInsets.only(left: 30, right: 30),
                      child: TextFormField(
                          initialValue: snapshot.data!["peopletohangoutwith"],
                          controller: _peopletohangoutwithController,
                          maxLines: 10,
                          decoration: InputDecoration(
                            hintText: "Write in as detail as possible",
                            fillColor: Colors.white,
                            filled: true,
                            focusedBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(0),
                              borderSide: const BorderSide(
                                color: Colors.white,
                              ),
                            ),
                            enabledBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(0),
                              borderSide: const BorderSide(
                                color: Colors.white,
                                width: 2.0,
                              ),
                            ),
                          )),
                    ),
                  ),
                  const SizedBox(
                    height: 100,
                  ),
                  DelayedDisplay(
                    delay: const Duration(seconds: 2),
                    child: Center(
                      child: FloatingActionButton.extended(
                        label: const Text('Save'),
                        backgroundColor: const Color(0xFF2A3B6A),
                        icon: const Icon(
                          Icons.save_as_outlined,
                          size: 24.0,
                        ),
                        onPressed: () async {
                          if (_peopletohangoutwithController.text.isEmpty) {
                            Get.snackbar(
                              "Error",
                              "Please explain your preference",
                              colorText: Colors.white,
                            );
                          } else {
                            FirebaseFirestore.instance
                                .collection("userpreferences")
                                .doc(FirebaseAuth.instance.currentUser!.uid)
                                .set({
                              "peopletohangoutwith":
                                  _peopletohangoutwithController.text,
                            });
                          }
                        },
                      ),
                    ),
                  ),
                ],
              );
            },
          ),

如何在进入编辑页面之前获取用户数据。将数据传递给构造函数中的页面,并在初始状态下将数据输入文本编辑控制器。

编辑:抱歉。不知道你是初学者

假设您从某个数据库(例如 Firebase)获取数据。确保你有一个用户模型。模型使数据更易于管理。 苏,

    class UserModel{
    String _userName;
    String _tikTok;

String get userName => _userName;
String get tiktok => _tikTok;

UserModel.fromSnapshot(DocumentSnapshot snapshot){
_userName = snapshot.data()["userName"];
_tikTok = snapshot.data()["tikTok"];
}
    }

此 userModel 可用于传播个人资料页面。例如,如果您使用 streamBuilder 从 firestore 获取数据,则构建器会像

(context, snapshot){
if(!snapshot.hasData}{
return LoadingWidget();
}else{
UserModel userModel = UserModel.fromSnapshot(snapshot.data);

return Scaffold(body: blah blah Text(userModel.userName) `and so forth`

我在那里忘记了我的括号,但你明白了。

通过constructors将userModel发送到下一个页面,并初始化initstate中的数据。 Coz init state 是页面加载时执行的第一个函数。甚至在它开始构建小部件之前。

这是编辑页面的代码。

class EditProfilePage extends StatefulWidget {
  final UserModel userModel;
  EditProfilePage({
    Key key,
    @required this.userModel,
  }) : super(key: key);

  @override
  State<EditProfilePage> createState() => _EditProfilePageState();
}

class _EditProfilePageState extends State<EditProfilePage> {
  TextEditingController nameController;
  TextEditingController tiktokAccountController;

  @override
  void initState() {
    super.initState();

    if (widget.userModel != null) {
      nameController = TextEditingController(
        text: widget.userModel.userName,
      );

      tiktokAccountController = TextEditingController(
        text: widget.userModel.tiktok,
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        TextField(
          controller: nameController,
          decoration: InputDecoration(
            hintText: "Username",
          ),
        ),
        SizedBox(
          height: 10,
        ),
        TextField(
          controller: tiktokAccountController,
          decoration: InputDecoration(
            hintText: "Tik Tok Username",
          ),
   

     ),
      ],
    );
  }
}

因此,当您从个人资料页面转到编辑页面时,您会调用 Navigator.of(context).push(EditBlahBlah(userModel: userModel,),)

其中 userModel 是您在个人资料页面上查看的 userModel。希望对您有所帮助。

只能使用 TextFormFieldinitialValuecontroller 之一。

使用 TextEditingController 初始值:

final controller = TextEditingController('the initial value');