如何将列表对象从一个类传递到另一个类

时间:2019-08-29 05:25:37

标签: flutter dart

我正在开发一个简单的Todolist应用。我创建了一个数据库,用于将数据存储在文件“ to_do_item.dart”下。文件“ database_helper.dart”是我存储所有CRUD函数的位置。

打开应用程序后,用户将看到在文件“ todo_list.dart”下创建的屏幕,其中已添加的任务将在列表视图中显示。当用户单击操作按钮时,它将把它们发送到“ input_screen.dart”,其中有一个文本字段可输入任务。用户单击屏幕键盘上的“完成”后,数据将保存在一个名为“ Itemlist”的列表中(“ input_screen”的第49行)。

我想将此列表发送到“ todo_list.dart”并在可滚动的列表视图中显示它们,但我不确定要使用哪种方法。目前,我只想添加并显示该项目。

尝试使用getters,但无法将其用于另一个类,并尝试搜索flutter上其他todolist应用的制作方式,但它们在同一类上使用AlertDialog;我想从一个屏幕(InputScreen类)上获取输入,并在另一个屏幕(TodoList类)上显示它。

“ todo_list.dart”下的代码-

services.AddSingleton<AntiForgery>();
services.AddHttpContextAccessor();

“ input_screen.dart”下的代码

      Container(
              color: Colors.white,
              alignment: Alignment.topLeft,
              margin: const EdgeInsets.all(20),
              child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    SizedBox(height: 110,),
                    Text( "tasks for today",),
                    SizedBox(height: 20,),

                    //Todo: display listview on below column 

//                   Column(
//                     children: <Widget>[
//                       new Flexible(child: ListView.builder(
itemBuilder:(_,intindex){
//                       return ListTile(
////                         title: _itema,
//                       );
//                       }
//                       )
//                       )
//                     ],
//                   ),

                    SizedBox(height: 320,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: <Widget>[
                        FloatingActionButton(
                          onPressed: (){
                            Navigator.push(context, MaterialPageRoute(builder: (context) => InputScreen()));
                          },
                          heroTag: "btn2",
                          child: Icon(Icons.add, color: Colors.white,), backgroundColor: Colors.black87,),
                      ],
                    )
                  ]
              ),
            ),

“ to_do_item.dart”下的代码-

    class InputScreen extends StatefulWidget {
  @override
  _InputScreenState createState() => _InputScreenState();
}

class _InputScreenState extends State<InputScreen> {


  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _readList();

  }    

  void _handleSubmitted(String text) async{
    taskcontroller.clear();
    TodoItem obj = new TodoItem(text, DateTime.now().toIso8601String());
    int SavedItemId = await db.saveItem(obj);
    print("item saved id: $SavedItemId");
    print("$text");
    TodoItem addedItem = await db.getItem(SavedItemId);
    setState(() {
      Itemlist.insert(0, addedItem);
    });
  }

  _readList() async{
    List items = await db.getItems();
    items.forEach((item) {
      TodoItem todoItem = TodoItem.map(items);
      print("db it4ems: ${todoItem.itemName.toString()}");
    });
  }    

  var db = new DatabaseHelper();    

  final List<TodoItem> Itemlist= <TodoItem>[];
  TextEditingController taskcontroller = new TextEditingController();
  @override
  Widget build(BuildContext context) {
    SystemChrome.setEnabledSystemUIOverlays([]);
    return Scaffold(
      resizeToAvoidBottomPadding: false,
      backgroundColor: Colors.white,
      body: SingleChildScrollView(

        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
//       crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Container(
              color: Colors.white,
              alignment: Alignment.topLeft,
              margin: const EdgeInsets.all(20),
              child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    SizedBox(height: 110,),
                    Text("tasks for today:",),
                    SizedBox(height: 10,),

                    //Todo: remove sized box below and display tasks there
                    TextField(
                      autofocus: true,
                      onEditingComplete: (){Navigator.pop(context);},
                      maxLength: 10,
                      onSubmitted: (NewValue){ _handleSubmitted(NewValue);},
                      controller: taskcontroller,
                      decoration: InputDecoration(
                        labelText: "enter tasks here"
                      ),
                      style: TextStyle(height: 1.2, fontSize: 20, color: Colors.black87),

                    )
                  ]
              ),
            ),
          ],
        ),
      ),
    );
  }
}

“ database_helper.dart”下的代码-

    import 'package:flutter/material.dart';

class TodoItem extends StatelessWidget {
  String _itemName;
  String _dateCreated;
  int _id;    

  TodoItem(this._itemName, this._dateCreated);

  TodoItem.map(dynamic obj) {
    this._itemName = obj["itemName"];
    this._dateCreated = obj["dateCreated"];
    this._id = obj["id"];
  }

  String get itemName => _itemName;
  String get dateCreated => _dateCreated;
  int get id => _id;

  Map<String, dynamic> toMap() {
    var map = new Map<String, dynamic>();
    map["itemName"] = _itemName;
    map["dateCreated"] = _dateCreated;

    if (_id != null) {
      map["id"] = _id;
    }

    return map;
  }

  TodoItem.fromMap(Map<String, dynamic> map) {
    this._itemName = map["itemName"];
    this._dateCreated = map["dateCreated"];
    this._id = map["id"];    
  }    

  @override
  Widget build(BuildContext context) {
    return new Container(
      margin: const EdgeInsets.all(8.0),
      child: new Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          new Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Text(_itemName, )
            ],
          ),
        ],
      ),
    );
  }
}

1 个答案:

答案 0 :(得分:0)

这可能是this

的副本

尽管如此,我希望这会有所帮助

class FrontPage extends StatefulWidget {
  @override
  _FrontPageState createState() => _FrontPageState();
}

class _FrontPageState extends State<FrontPage> {

//  Activity currentActivity;
  var recentActivities = <Widget>[];//<Widget>[Activity("Skiing", "assets/activity_logos/Squat.png").getSummary(),Activity("Skiing", "assets/activity_logos/Squat.png").getSummary(),Activity("Skiing", "assets/activity_logos/Squat.png").getSummary(),Activity("Skiing", "assets/activity_logos/Squat.png").getSummary(),Activity("Skiing", "assets/activity_logos/Squat.png").getSummary(),Activity("Skiing", "assets/activity_logos/Squat.png").getSummary()];
  var upcomingActivities = <Widget>[];//<Widget>[Activity("Jog", "assets/activity_logos/Squat.png", status: ActivityStatus.completed,).getSummary()];

  List<String> tasks = ["previous1", "previous2"];

  @override
  Widget build(BuildContext context) {
    return  Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text('Home'),
        actions: <Widget>[
          GestureDetector(
            child: Align(child:Text("+", style: TextStyle(fontSize: 40)), alignment: Alignment.centerLeft, widthFactor: 2,),
            onTap: () => Navigator.pushNamed(context, '/activity/new'),
          )
        ],
      ),
      body: Container(
        color: Colors.white,
        alignment: Alignment.topLeft,
        margin: const EdgeInsets.all(20),
        child: Stack(
            alignment: Alignment.bottomRight,
            children: <Widget>[
              Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    SizedBox(height: 110,),
                    Text( "tasks for today",),
                    SizedBox(height: 20,),
                    Expanded(child: ListView.builder(
                        itemCount: tasks.length,
                        itemBuilder: (BuildContext context, int index) {
                          return Text(tasks[index]);
                        })),
                  ]),
                  FloatingActionButton(
                    onPressed: () async {
                      final result = await Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => InputScreen(),
                          ));
                      setState(() {
                        tasks.add(result);
                      });
                    },
                    heroTag: "btn2",
                    child: Icon(Icons.add, color: Colors.white,), backgroundColor: Colors.black87,),
            ]),
      ),
    );
  }
}

class InputScreen extends StatefulWidget {
  @override
  _InputScreenState createState() => _InputScreenState();
}

class _InputScreenState extends State<InputScreen> {

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
//    _readList();

  }

//  final List<TodoItem> Itemlist= <TodoItem>[];
  TextEditingController taskcontroller = new TextEditingController();
  @override
  Widget build(BuildContext context) {
    SystemChrome.setEnabledSystemUIOverlays([]);
    return Scaffold(
      resizeToAvoidBottomPadding: false,
      backgroundColor: Colors.white,
      body: SingleChildScrollView(

        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
//       crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Container(
              color: Colors.white,
              alignment: Alignment.topLeft,
              margin: const EdgeInsets.all(20),
              child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    SizedBox(height: 110,),
                    Text("tasks for today:",),
                    SizedBox(height: 10,),

                    //Todo: remove sized box below and display tasks there
                    TextField(
                      autofocus: true,
                      onEditingComplete: () {
                        String textToSendBack = taskcontroller.text;
                        Navigator.pop(context, textToSendBack );
                      },
                      maxLength: 10,
                      onSubmitted: (NewValue){  },
                      controller: taskcontroller,
                      decoration: InputDecoration(
                          labelText: "enter tasks here"
                      ),
                      style: TextStyle(height: 1.2, fontSize: 20, color: Colors.black87),

                    )
                  ]
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class TodoItem extends StatelessWidget {
  String _itemName;
  String _dateCreated;
  int _id;


  TodoItem(this._itemName, this._dateCreated);

  TodoItem.map(dynamic obj) {
    this._itemName = obj["itemName"];
    this._dateCreated = obj["dateCreated"];
    this._id = obj["id"];
  }

  String get itemName => _itemName;
  String get dateCreated => _dateCreated;
  int get id => _id;

  Map<String, dynamic> toMap() {
    var map = new Map<String, dynamic>();
    map["itemName"] = _itemName;
    map["dateCreated"] = _dateCreated;

    if (_id != null) {
      map["id"] = _id;
    }

    return map;
  }

  TodoItem.fromMap(Map<String, dynamic> map) {
    this._itemName = map["itemName"];
    this._dateCreated = map["dateCreated"];
    this._id = map["id"];

  }


  @override
  Widget build(BuildContext context) {
    return new Container(
      margin: const EdgeInsets.all(8.0),
      child: new Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          new Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Text(_itemName, )
            ],
          ),
        ],
      ),
    );
  }
}

主要更改包括

在输入页面上:

TextField(
   autofocus: true,
   onEditingComplete: () {
       String textToSendBack = taskcontroller.text;
       Navigator.pop(context, textToSendBack );
   }

在首页上:

 FloatingActionButton(
      onPressed: () async {
        final result = await Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => InputScreen(),
            ));
        setState(() {
          tasks.add(result);
        });
      },

一些小部件布局,我将数据保存在一个任务数组中,但是您可以根据需要进行更改。