我甚至不能打印一个可以为null的值



基本上问题很清楚:这是我的代码:

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class AddTaskScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
late String newTaskTitle;
return Container(
color: Color(0xFF757575),
child: Container(
padding: EdgeInsets.all(20),
decoration: BoxDecoration(
color: Colors.limeAccent[400],
borderRadius: BorderRadius.only(
topLeft: Radius.circular(60),
topRight: Radius.circular(60),
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
'Add Task',
textAlign: TextAlign.center,
style: TextStyle(fontSize: 30, color: Colors.brown[900]),
),
SizedBox(
height: 12,
),
TextField(
onChanged: (newText) {
newTaskTitle = newText;
},
autocorrect: false,
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Colors.brown[800]!,
width: 2,
),
borderRadius: BorderRadius.circular(30),
),
hintText: 'Type Your Task ...',
labelStyle: TextStyle(
color: Colors.green[900],
),
helperStyle: TextStyle(
color: Colors.brown[900],
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(60),
borderSide: BorderSide(
color: Colors.brown[900]!,
width: 2,
),
),
),
),
SizedBox(
height: 12,
),
ElevatedButton(
onPressed: () {
// Provider.of<TaskData>(context, listen: false)
//     .addTask(newTaskTitle);
// Navigator.pop(context);
print(newTaskTitle);
// Provider.of<TaskData>(context, listen: false)
//     .addTask(newTaskTitle);
// Navigator.pop(context);
},
child: Text(
'Add',
style: TextStyle(color: Colors.brown[900]),
),
style: ButtonStyle(
backgroundColor: MaterialStateColor.resolveWith(
(states) => Colors.lightGreen),
elevation: MaterialStateProperty.resolveWith((states) => 6),
shadowColor:
MaterialStateColor.resolveWith((states) => Colors.green),
minimumSize: MaterialStateProperty.resolveWith(
(states) => Size.square(40.67)),
),
),
],
),
),
);
}
}

请帮帮我。。。在这个阶段,我只想打印用户在控制台的文本字段中输入的值。。。但它给了我一个错误:LateInitializationError:本地"newTaskTitle"尚未初始化。我还把它改成了一个有状态的小部件,以检查它是否能与setstate一起工作,但它没有。。我还让它可以为null,就像这样=>一串newTaskTitle;当然,它做了很多改变,但最终传递了null值。。。文本字段的onChange回调没有将用户输入的新值分配给我创建的变量,这是一个问题。。。我该如何解决这个问题?

更改

late String newTaskTitle;

ValueNotifier<String> newTaskTitle  = ValueNotifier("");

并将ElevatedButton放入ValueListenableBuilder中像这个

ValueListenableBuilder<String>(
listenable : newTaskTitle,
builder : (ctx,taskt,_){
return ElevatedButton(
onPressed : taskt.isEmpty ? null : (){
// put you logic
}
.....
);
}
);

change-onChanged of textField like this

onChanged: (newText) {
newTaskTitle.value = newText;
},

最新更新