参数类型“Widget”不能赋值给参数类型“String”?

The argument type ‘Widget’ can’t be assigned to the parameter type ‘String’?

如何使用我的自定义小部件注释?不幸的是,我无法使用 AddNoteScreen 中的完整代码。

当我从我正在使用的 class 中更改一些东西时,我得到了这个错误。下面我粘贴了讲师代码,其中包含我的自定义小部件。我将在下面评论导致我出现此错误的其他更改。

自定义小部件到最基本的部分:

class Notes extends StatelessWidget {

TextEditingController notesController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return TextField(
      controller: notesController,  
    );
  }
}
class AddNoteScreen extends StatefulWidget {

  User user;
 AddNoteScreen({
     required this.user,
   });

  @override
  State<AddNoteScreen> createState() => _AddNoteScreenState();
  }

class _AddNoteScreenState extends State<AddNoteScreen> {

  TextEditingController titleController = TextEditingController();
  TextEditingController notesController = TextEditingController();
  
  bool loading = false;

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

 @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor:Color (0xFF162242),
        elevation: 0,
      ),

      body: GestureDetector(
        onTap: () {
      FocusScope.of(context).unfocus();
      new TextEditingController().clear();
    },
        child: SingleChildScrollView(
          child: Padding(
            padding: EdgeInsets.all(20),
            child: Column(children: [
              
              Text("Title", style: TextStyle(
                color: Colors.white, 
              ), 
              ),
              SizedBox(
                height: 15,
              ),
              Container(
                height: 60,
                color: Colors.white,
                child: TextField(
                  style: TextStyle(
                    color: Color(0xFF192A4F),
                  ),
                  controller: titleController,
                ),
              ),


              Notes(), // My Custom Widget
            
    
              SizedBox(height: 50,),
              loading ? Center (child: CircularProgressIndicator(),) : Container(
                height: 50,
                
                width: MediaQuery.of(context).size.width,
                child: ElevatedButton(
                  
                  onPressed: ()async{
      
                  if (
                    titleController.text == "" || notesController.text == "") // HERE
                    {
                      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("All fields are required")));
      
                    } else {
                      setState(() {
                        loading = true;
                      });
      
                      await FirestoreService().insertNote(titleController.text, notesController.text, widget.user.uid); // HERE
      
                      setState(() {
                        loading = false;
                      });
                      Navigator.pop(context);
                    }
                }, child: Text("Add Note"),  
        ),),
        ]),),
        ),
      ),
      );
       }
      }

^ 上面我把 notesController.text == "" 改成了 Notes == "" 然后 notesController.text 改成了 Notes()

class FirestoreService{

  FirebaseFirestore firestore = FirebaseFirestore.instance;

  Future insertNote(String title, String notes, String userId)async{
    try{
      await firestore.collection('notes').add({
        "title":title,
        "notes":notes,
        "userId": userId
      });
    } catch (e) {}
  }
}

^ 上面我将 String 更改为 Widget 用于注释

class NoteModel {
  String id;
  String title;
  String notes;
  String userId;

  NoteModel({
    required this.id,
    required this.title,
    required this.notes,
    required this.userId
  });

  factory NoteModel.fromJson(DocumentSnapshot snapshot){
    return NoteModel(
      id: snapshot.id,
      title: snapshot['title'], 
      notes: snapshot['notes'],
      userId: snapshot['userId']
      );  
  }
}

^ 上面我将 String 更改为 Widget 用于注释

class HomeScreen extends StatefulWidget {

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  final user = FirebaseAuth.instance.currentUser!;

FirebaseFirestore firestore = FirebaseFirestore.instance;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Notes'),
        centerTitle: true,
        backgroundColor: Color (0xFF162242),
        actions: [
          TextButton(onPressed: () => FirebaseAuth.instance.signOut(), child: Text("Sign Out", style: TextStyle(color: Colors.white),),),
        ],
      ),
      body: StreamBuilder(
        stream: FirebaseFirestore.instance.collection("notes").where('userId', isEqualTo: user.uid).snapshots(),
        builder: (context, AsyncSnapshot snapshot){
          if (snapshot.hasData){
            if(snapshot.data.docs.length > 0){
              return ListView.builder(
                itemCount: snapshot.data.docs.length,
                itemBuilder: (context,index) {
                  NoteModel note = NoteModel.fromJson(snapshot.data.docs[index]);
                  return Card(
                    margin: EdgeInsets.only(top: 16, left: 10, right: 10, bottom: 16),
                    child: Column(
                        children: [
                          ListTile(
                           title: Center(child: Text(note.title, style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold),
                           ),
                           ),
                              onTap: () {
                          Navigator.of(context).push(MaterialPageRoute(builder: (context) => EditNoteScreen(),));},
                            ),

                          
                            ListTile(title: Center(child: 
                            Container(
                              height: 300,
                              child: 
                             Text(note.notes),),), // HERE
                            ),


                    ]),
                  );
                }
              );

            }else Center(child: Text("No notes available", style: TextStyle(color: Colors.white),),);

          }
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                CircularProgressIndicator(),
              ],
            ),
          );
        }),

      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Navigator.of(context).push(MaterialPageRoute(builder: (context) => AddNoteScreen(user: user)));
        },
        backgroundColor: Color (0xFF162242),
        child: Icon(Icons.add),
      ),
    );
  }
}

^ Text(note.notes) 是我得到错误的地方。

我真的不知道我在做什么,但这样的事情可以吗?完全不同的答案也可以!

抱歉,代码太多了。任何帮助表示赞赏。 还有 link 到 class 如果有人感兴趣 https://skl.sh/3wxeMVF

假设

根据代码和注释,我猜实际的 class NoteModelNotes 看起来像这样:

class NoteModel {
  Notes  notes;
  ... 
}

class Notes extends StatelessWidget { 
  TextEditingController notesController = TextEditingController();
  ...
}

问题

这解释了错误消息 The argument type ‘Widget’ can’t be assigned to the parameter type ‘String’?:

Text(note.notes) 期望 note.notes 是一个字符串。而您将 note.notes 更改为小部件 Notes.

解决方案 1

小部件 Text() 需要字符串,而不是其他小部件。因此, 将 notes 改回字符串:

class NoteModel {
  String notes;
  ... 
}

围绕此 NoteModel 构建其余代码,不要更改它。

解决方案 2

如果你想使用

class NoteModel {
  Notes notes;
  ... 
}

然后文本小部件将被称为这样的名称:

Text(note.notes.notesController.text)

但是,不推荐这样做,因为 NoteModel 是一种数据模型。数据模型永远不应该包含小部件。 Widget 用于显示数据,而不是用于保存数据。数据模型和 Widget 具有不同的功能。将它们分开。

Firebase

请注意,不能在 Firebase 中存储整个小部件(如 Notes),只能存储字符串、数字等。

(请始终post 您的当前代码,而不是与问题间接相关的代码。否则,人们会发现很难发现问题.)