Listview 如何将元素从另一个类添加到已经存在的列表中?

Listview 如何将元素从另一个类添加到已经存在的列表中?,listview,inheritance,flutter,dart,Listview,Inheritance,Flutter,Dart,我想用flatter制作一个待办事项列表应用程序,但是我在保存文本输入到我显示的另一个类中已经创建的列表时遇到了问题 我曾尝试在另一个类中使用setter创建一个对象,但由于我使用的是有状态小部件,因此无法工作,特别是因为我在脚手架主体上使用列表视图来显示列表项 这是我的列表视图类 进口“包装:颤振/材料.省道”; 导入“todo.dart”; 类TodoListS扩展了StatefulWidget{ @凌驾 TodoList createState=>TodoList; } 类TodoList

我想用flatter制作一个待办事项列表应用程序,但是我在保存文本输入到我显示的另一个类中已经创建的列表时遇到了问题

我曾尝试在另一个类中使用setter创建一个对象,但由于我使用的是有状态小部件,因此无法工作,特别是因为我在脚手架主体上使用列表视图来显示列表项

这是我的列表视图类

进口“包装:颤振/材料.省道”; 导入“todo.dart”; 类TodoListS扩展了StatefulWidget{ @凌驾 TodoList createState=>TodoList; } 类TodoList扩展了状态{ List todos=[Todotitle:'Checktheicon',Todotitle:'help me'; void settodo todo { todos.addtodo; } @凌驾 小部件构建上下文上下文{ 返回myListViewcontext,todos; } } 小部件myListViewBuildContext上下文,列出待办事项{ //支持数据 返回ListView.builder itemCount:todos.length, itemBuilder:上下文、索引{ 返回列表块 标题:Texttodos[索引]。标题, 前导:Icontodos[index]。图标, ; }, ; } 这是我显示列表的地方

@凌驾 小部件构建上下文上下文{ 归还新脚手架 appBar:新的appBar 背景颜色:Colors.pink[100],标题:新文本“待办事项列表”, 正文:托多利斯特, 浮动操作按钮:浮动操作按钮 子项:IconIcons.add,onPressed:=>\u displayDialogcontext, ; } 这是我想要获取文本输入并保存它的地方

_displayDialogBuildContext上下文{ 返回显示对话框 上下文:上下文, 生成器:上下文{ 返回警报对话框 标题:文本“插入您的待办事项”, 内容:TextField 控制器:_textFieldController, 装饰:输入装饰提示文字:即洗碗, , 行动:[ 新扁平按钮 子项:新文本“取消”, 按下按钮:{ Navigator.ofcontext.pop; }, , 新扁平按钮 子项:新文本“添加”, 按下按钮:{ var todo=new Todotitle:_textFieldController.value.text; todol.settododo; Navigator.ofcontext.pop; }, ], ; }; }
所以现在,没有保存任何内容,唯一显示的是我以前创建的todo,我的文本输入需要添加到列表中以便显示。

要在另一个类中调用函数,可以使用GlobalKey

步骤1:定义最终的GlobalKey _key=GlobalKey; 步骤2:在按下时使用_key.currentState.setToDoToDotTitle:_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),
      );
    },
  );
}
完整工作演示


我想你只是在更新列表后错过了一次对setState的调用。尝试添加todol.setState{};在todol.settododo之后;您好,这正是我所需要的,尽管我不知道dispose用于什么方法。