TextField 输入不会打印到控制台?
TextField input won't print to console?
我正在尝试在我的 AddNoteScreen 中使用自定义 TextField 小部件。我不知道为什么它不打印 TextField 输入或如何让它工作。我以为拥有 TextEditingController 就足够了。我是新手。抱歉 post 这么多代码,我不知道该怎么解释。
这是我的自定义小部件:
class MyWidget extends StatefulWidget {
final Widget textFields;
MyWidget(
{required this.textFields});
@override
State<MyWidget> createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
TextEditingController notesController = TextEditingController();
List<TextField> textFields = [];
@override
void initState() {
super.initState();
textFields.add(_buildTextField());
}
@override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.only(left: 10, right: 10),
decoration: BoxDecoration(
borderRadius: BorderRadius.all(
Radius.circular(10),
),
color: Colors.white,
),
height: 300,
alignment: Alignment.centerLeft,
child: ListView(
children: textFields,
),
);
}
TextField _buildTextField() {
return TextField(
style: TextStyle(
color: Colors.black,
fontSize: 18,
),
decoration: InputDecoration(
prefix: Icon(
Icons.circle,
size: 10,
color: Colors.black,
),
prefixIconConstraints: BoxConstraints(
minWidth: 20,
minHeight: 10,
maxHeight: 10,
maxWidth: 20,
),
),
autofocus: true,
onSubmitted: (_) {
setState(() {
textFields.add(_buildTextField());
notesController.text + ' ';
});
}
);
}
}
我的添加笔记屏幕:
class AddNoteScreen extends StatefulWidget {
User user;
AddNoteScreen({
required this.user,
});
@override
State<AddNoteScreen> createState() => _AddNoteScreenState();
}
class _AddNoteScreenState extends State<AddNoteScreen> {
TextEditingController notesController = TextEditingController();
FirebaseFirestore firestore = FirebaseFirestore.instance;
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();
notesController.text = '';
},
child: SingleChildScrollView(
child: Padding(
padding: EdgeInsets.all(20),
child: Column(children: [
Container(
padding: EdgeInsets.only(left: 10, right: 10),
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(10),),
color: Colors.white,
),
child: MyWidget(
textFields: TextField(
style: TextStyle (color: Color(0xFF192A4F),fontSize: 18,),
textCapitalization: TextCapitalization.sentences,
controller: notesController,
decoration: InputDecoration(
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.transparent),
),
),
),
),
),
SizedBox(height: 50,),
loading ? Center (child: CircularProgressIndicator(),) : Container(
height: 50,
width: MediaQuery.of(context).size.width,
child: ElevatedButton(
onPressed: ()async{
if (
notesController.text.isEmpty)
{
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("All feilds are required")));
} else {
setState(() {
loading = true;
});
await FirestoreService().insertNote(notesController.text,
widget.user.uid);
CollectionReference notes = firestore.collection('notes');
QuerySnapshot allResults = await notes.get();
allResults.docs.forEach((DocumentSnapshot result) {
print(result.data());
});
setState(() {
loading = false;
});
Navigator.pop(context);
}
}, child: Text("Add Note", style: TextStyle(
fontSize: 25,
fontWeight: FontWeight.bold,
),
),style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Color (0xFF162242)),
shape: MaterialStateProperty.all<RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
),
),
//color:Color (0xFF162242)
//ElevatedButton.styleFrom(primary: Color (0xFF162242),),
),
),
]),),
),
),
);
我的 FirestoreService 页面:
class FirestoreService{
FirebaseFirestore firestore = FirebaseFirestore.instance;
Future insertNote(String notes, String userId)async{
try{
await firestore.collection('notes').add({
"notes":notes,
"userId":userId
});
} catch(e){
}
}
}
还有我的 NoteModel 屏幕:
class NoteModelEdit {
String id;
String notes;
String userId;
NoteModelEdit({
required this.id,
required this.notes,
required this.userId
});
factory NoteModelEdit.fromJson(DocumentSnapshot snapshot){
return NoteModelEdit(
id: snapshot.id,
notes: snapshot['notes'],
userId: snapshot['userId']
);
}
}
感谢任何帮助!
我相信你正在存储一个空笔记,这就是数据库结果为空的原因。
这一行:
if (notesController.text.isNotEmpty) // show error message
应该变成这样:
if (notesController.text.isEmpty) // show error message
此外,这也应该改变:
// This does nothing:
new TextEditingController().clear();
// To clear the controller:
notesController.text = '';
更新
如下更改代码以测试是否有问题
被写入数据库。一旦成功,请弄清楚如何正确使用 MyWidget,因为其中也存在问题。
// OLD CODE
child: MyWidget(
textFields: TextField(
style: TextStyle (color: Color(0xFF192A4F),fontSize: 18,),
textCapitalization: TextCapitalization.sentences,
controller: notesController,
decoration: InputDecoration(
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.transparent),
),
),
),
),
// NEW CODE
child: TextField(
style: TextStyle (color: Color(0xFF192A4F),fontSize: 18,),
textCapitalization: TextCapitalization.sentences,
controller: notesController,
decoration: InputDecoration(
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.transparent),
),
),
),
我建议始终只更改一小部分代码,并确保您的代码在每个小步骤中都能正常工作。不要一次做太多的改变。
我正在尝试在我的 AddNoteScreen 中使用自定义 TextField 小部件。我不知道为什么它不打印 TextField 输入或如何让它工作。我以为拥有 TextEditingController 就足够了。我是新手。抱歉 post 这么多代码,我不知道该怎么解释。
这是我的自定义小部件:
class MyWidget extends StatefulWidget {
final Widget textFields;
MyWidget(
{required this.textFields});
@override
State<MyWidget> createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
TextEditingController notesController = TextEditingController();
List<TextField> textFields = [];
@override
void initState() {
super.initState();
textFields.add(_buildTextField());
}
@override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.only(left: 10, right: 10),
decoration: BoxDecoration(
borderRadius: BorderRadius.all(
Radius.circular(10),
),
color: Colors.white,
),
height: 300,
alignment: Alignment.centerLeft,
child: ListView(
children: textFields,
),
);
}
TextField _buildTextField() {
return TextField(
style: TextStyle(
color: Colors.black,
fontSize: 18,
),
decoration: InputDecoration(
prefix: Icon(
Icons.circle,
size: 10,
color: Colors.black,
),
prefixIconConstraints: BoxConstraints(
minWidth: 20,
minHeight: 10,
maxHeight: 10,
maxWidth: 20,
),
),
autofocus: true,
onSubmitted: (_) {
setState(() {
textFields.add(_buildTextField());
notesController.text + ' ';
});
}
);
}
}
我的添加笔记屏幕:
class AddNoteScreen extends StatefulWidget {
User user;
AddNoteScreen({
required this.user,
});
@override
State<AddNoteScreen> createState() => _AddNoteScreenState();
}
class _AddNoteScreenState extends State<AddNoteScreen> {
TextEditingController notesController = TextEditingController();
FirebaseFirestore firestore = FirebaseFirestore.instance;
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();
notesController.text = '';
},
child: SingleChildScrollView(
child: Padding(
padding: EdgeInsets.all(20),
child: Column(children: [
Container(
padding: EdgeInsets.only(left: 10, right: 10),
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(10),),
color: Colors.white,
),
child: MyWidget(
textFields: TextField(
style: TextStyle (color: Color(0xFF192A4F),fontSize: 18,),
textCapitalization: TextCapitalization.sentences,
controller: notesController,
decoration: InputDecoration(
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.transparent),
),
),
),
),
),
SizedBox(height: 50,),
loading ? Center (child: CircularProgressIndicator(),) : Container(
height: 50,
width: MediaQuery.of(context).size.width,
child: ElevatedButton(
onPressed: ()async{
if (
notesController.text.isEmpty)
{
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("All feilds are required")));
} else {
setState(() {
loading = true;
});
await FirestoreService().insertNote(notesController.text,
widget.user.uid);
CollectionReference notes = firestore.collection('notes');
QuerySnapshot allResults = await notes.get();
allResults.docs.forEach((DocumentSnapshot result) {
print(result.data());
});
setState(() {
loading = false;
});
Navigator.pop(context);
}
}, child: Text("Add Note", style: TextStyle(
fontSize: 25,
fontWeight: FontWeight.bold,
),
),style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Color (0xFF162242)),
shape: MaterialStateProperty.all<RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
),
),
//color:Color (0xFF162242)
//ElevatedButton.styleFrom(primary: Color (0xFF162242),),
),
),
]),),
),
),
);
我的 FirestoreService 页面:
class FirestoreService{
FirebaseFirestore firestore = FirebaseFirestore.instance;
Future insertNote(String notes, String userId)async{
try{
await firestore.collection('notes').add({
"notes":notes,
"userId":userId
});
} catch(e){
}
}
}
还有我的 NoteModel 屏幕:
class NoteModelEdit {
String id;
String notes;
String userId;
NoteModelEdit({
required this.id,
required this.notes,
required this.userId
});
factory NoteModelEdit.fromJson(DocumentSnapshot snapshot){
return NoteModelEdit(
id: snapshot.id,
notes: snapshot['notes'],
userId: snapshot['userId']
);
}
}
感谢任何帮助!
我相信你正在存储一个空笔记,这就是数据库结果为空的原因。
这一行:
if (notesController.text.isNotEmpty) // show error message
应该变成这样:
if (notesController.text.isEmpty) // show error message
此外,这也应该改变:
// This does nothing:
new TextEditingController().clear();
// To clear the controller:
notesController.text = '';
更新
如下更改代码以测试是否有问题 被写入数据库。一旦成功,请弄清楚如何正确使用 MyWidget,因为其中也存在问题。
// OLD CODE
child: MyWidget(
textFields: TextField(
style: TextStyle (color: Color(0xFF192A4F),fontSize: 18,),
textCapitalization: TextCapitalization.sentences,
controller: notesController,
decoration: InputDecoration(
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.transparent),
),
),
),
),
// NEW CODE
child: TextField(
style: TextStyle (color: Color(0xFF192A4F),fontSize: 18,),
textCapitalization: TextCapitalization.sentences,
controller: notesController,
decoration: InputDecoration(
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.transparent),
),
),
),
我建议始终只更改一小部分代码,并确保您的代码在每个小步骤中都能正常工作。不要一次做太多的改变。