如何将元素添加到另一个类的现有列表中? [英] How to add element to an already existing list from another class?

查看:53
本文介绍了如何将元素添加到另一个类的现有列表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让一个待办事项列表应用变得扑朔迷离,但我在将文本输入保存到我在显示的另一个类中已经创建的列表中遇到了麻烦.

I want to make a todo-list app with flutter, but I'm having trouble saving the text input, to the list already created in another class that I display.

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

I have tried creating an object in the other class with a setter but since I'm using a stateful widget, that won't work, especially because I am using Lists() (a list view) on the body of the scaffold to display the list items

这是我的列表视图类

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)),
    );
  }

这是我要获取文本输入并保存的地方

This is where I want to get the text input and save it

_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();
                  },
                )
              ],
            );
          });
    }

现在,什么都不会保存,唯一要显示的是我先前创建的待办事项,需要将我的文本输入添加到列表中以便可以显示.

So right now , nothing is getting saved, the only thing being displayed are my previously created todo, the my text input need to be added to the list so that it can be displayed.

推荐答案

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

To call function in another class, you can use GlobalKey

步骤1:定义 final GlobalKey< TodoList>._key = GlobalKey();
步骤2:在onPressed中,使用 _key.currentState.setTodo(Todo(title:_textFieldController.text));
步骤3:向课程添加密钥

Step 1: define final GlobalKey<TodoList> _key = GlobalKey();
Step 2: In onPressed use _key.currentState.setTodo(Todo(title: _textFieldController.text));
Step 3: Add key to class

class TodoListS extends StatefulWidget {
  TodoListS({Key key}) : super(key: key);

第4步:TodoListS密码

Step 4: TodoListS pass key

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),
      );
    },
  );
}

完整的工作演示

这篇关于如何将元素添加到另一个类的现有列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆