listview - 如何将元素添加到另一个类中已经存在的列表中?
问题描述
我想用颤振制作一个待办事项列表应用程序,但是我无法将文本输入保存到已经在我显示的另一个类中创建的列表中。
我曾尝试使用 setter 在另一个类中创建一个对象,但由于我使用的是有状态小部件,因此这不起作用,特别是因为我在脚手架主体上使用 Lists() (列表视图)来显示列表项
这是我的列表视图类
import 'package:flutter/material.dart';
import 'todo.dart';
class TodoListS extends StatefulWidget {
@override
TodoList createState() => TodoList();
}
class TodoList extends State<TodoListS> {
List<Todo> todos = [Todo(title:'Checktheicon'), Todo(title: 'help me')];
void setTodo(Todo todo)
{
todos.add(todo);
}
@override
Widget build(BuildContext context) {
return myListView(context,todos );
}
}
Widget myListView(BuildContext context, List<Todo> todos) {
// backing data
return ListView.builder(
itemCount: todos.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(todos[index].title),
leading: Icon(todos[index].icons),
);
},
);
}
这是我显示列表的地方
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
backgroundColor: Colors.pink[100], title: new Text('Todo List')),
body: TodoListS(),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add), onPressed: () => _displayDialog(context)),
);
}
这是我想要获取文本输入并保存它的地方
_displayDialog(BuildContext context) {
return showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text('Insert Your to do'),
content: TextField(
controller: _textFieldController,
decoration: InputDecoration(hintText: "ie. Wash dishes"),
),
actions: <Widget>[
new FlatButton(
child: new Text('CANCEL'),
onPressed: () {
Navigator.of(context).pop();
},
),
new FlatButton(
child: new Text('ADD'),
onPressed: () {
var todo = new Todo(title: _textFieldController.value.text);
todol.setTodo(todo);
Navigator.of(context).pop();
},
)
],
);
});
}
所以现在,什么都没有保存,唯一显示的是我之前创建的待办事项,我的文本输入需要添加到列表中才能显示。
解决方案
要调用另一个类中的函数,您可以使用 GlobalKey
第 1 步:定义final GlobalKey<TodoList> _key = GlobalKey();
第 2 步:在 onPressed 中使用 _key.currentState.setTodo(Todo(title: _textFieldController.text));
第 3 步:将密钥添加到类
class TodoListS extends StatefulWidget {
TodoListS({Key key}) : super(key: key);
第 4 步:TodoListS 传递密钥
body: TodoListS(
key: _key,
),
完整的工作代码
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final _textFieldController = TextEditingController();
final GlobalKey<TodoList> _key = GlobalKey();
@override
void dispose() {
// Clean up the controller when the widget is removed from the
// widget tree.
_textFieldController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar:
AppBar(backgroundColor: Colors.pink[100], title: Text('Todo List')),
body: TodoListS(
key: _key,
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add), onPressed: () => _displayDialog(context)),
);
}
_displayDialog(BuildContext context) {
return showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text('Insert Your to do'),
content: TextField(
controller: _textFieldController,
decoration: InputDecoration(hintText: "ie. Wash dishes"),
),
actions: <Widget>[
FlatButton(
child: Text('CANCEL'),
onPressed: () {
Navigator.of(context).pop();
},
),
FlatButton(
child: Text('ADD'),
onPressed: () {
/*var todo = Todo(title: _textFieldController.value.text);
todol.setTodo(todo);*/
_key.currentState
.setTodo(Todo(title: _textFieldController.text));
setState(() {
});
Navigator.of(context).pop();
},
)
],
);
});
}
}
class Todo {
String title;
Todo({
this.title,
});
factory Todo.fromJson(Map<String, dynamic> json) => Todo(
title: json["title"] == null ? null : json["title"],
);
Map<String, dynamic> toJson() => {
"title": title == null ? null : title,
};
}
class TodoListS extends StatefulWidget {
TodoListS({Key key}) : super(key: key);
@override
TodoList createState() => TodoList();
}
class TodoList extends State<TodoListS> {
List<Todo> todos = [Todo(title: 'Checktheicon'), Todo(title: 'help me')];
void setTodo(Todo todo) {
todos.add(todo);
}
@override
Widget build(BuildContext context) {
return myListView(context, todos);
}
}
Widget myListView(BuildContext context, List<Todo> todos) {
// backing data
return ListView.builder(
itemCount: todos.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(todos[index].title),
//leading: Icon(todos[index].icons),
);
},
);
}
完整的工作演示
推荐阅读
- assembly - 在 64 位机器上 QWORD 的大小是多少?
- c# - 如何在 mvc 中使用 ajax 将数据加载到数据表中
- r - 绘制具有公共 x 轴的多个折线图时,如何分别为点着色?
- python-3.x - Python脚本返回函数未定义错误
- c# - 当玩家与障碍物碰撞时如何使相机抖动?
- php - 如何从 php 会话中获取 mysql user_id?
- css - 如何在点击时使用 Vue 来切换/停用活动的 html 类?
- c - fork()子执行命令奇怪地输出
- c# - 如何使用 int 检查 MySQL 数据库中是否存在某些内容,或者是否有任何替代方法?
- django - 在内联表单集的表单中,我可以自定义 can_delete 生成的字段吗?