我想制作一个简单的应用程序,其中有Task类,该类显示在主页的Card类中。我有floatActionButton,通过它可以在AlertDialog中添加新任务,但是存在问题。当我想添加新任务时,会收到此消息 。
My HomePage class looks like this:
class _HomeState extends State<Home> {
List<Task> tasks = [
Task(title: "Task4",text: "text of task 4"),
Task(title: "Task5",text: "text of task 5"),
Task(title: "Task6",text: "text of task 6"),
];
var myController = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.blueGrey[100],
appBar: AppBar(
backgroundColor: Colors.blueGrey[500],
title: Text("Task Manager"),
centerTitle: true,
),
body: SingleChildScrollView(
child: Column(
children: tasks.map((task) => TaskCard(
task: task,
delete: (){
setState(() {
tasks.remove(task);
});
},
)).toList(),
),
),
floatingActionButton: FloatingActionButton(
onPressed: (){
return showDialog(
context: context,
builder: (BuildContext context){
return AlertDialog(
title: Text("New task"),
content: TextFormField(
controller: myController,
),
actions: <Widget>[
FlatButton(
child: Text("Submit"),
onPressed: (){
setState(() {
Task t = new Task();
t.title = myController.text;
tasks.add(t);
});
Navigator.of(context).pop();
},
)
],
);
}
);
},
child: Icon(Icons.add),
backgroundColor: Colors.blueGrey[500],
),
);
}
}
当然,我有Task.dart和TaskCard.dart。
任务类:
class Task {
String title;
String text;
Task({this.text, this.title});
}
TaskCard类:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'Task.dart';
class TaskCard extends StatelessWidget{
final Task task;
final Function delete;
TaskCard({this.task, this.delete});
@override
Widget build(BuildContext context){
return Card(
margin: EdgeInsets.fromLTRB(10.0,10.0,10.0,5.0),
color: Colors.blueGrey[200],
child: Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Text(
task.title,
style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold),
),
SizedBox(height: 10.0,),
Text(
task.text,
style: TextStyle(fontSize: 13.0),
),
SizedBox(height: 10.0,),
FlatButton.icon(
onPressed: delete,
label: Text("Done"),
icon: Icon(Icons.done),
color: Colors.blueGrey[300],
)
],
),
),
);
}
}
答案 0 :(得分:0)
问题似乎是因为您要设置新的Task
的{{1}}。
title
..但未设置新的t.title = myController.text;
的{{1}}属性。
尝试将Task
更改为此,然后查看问题是否仍然存在。
text