Flutter在按钮点击时创建类的新实例并更新值

时间:2020-08-25 14:40:57

标签: flutter dart

我正在为用户创建一项功能,使其能够将场合(标题和日期)添加到Flutter中的列表中。我已经设置了功能,但是我一直在努力了解如何首先在按下“添加按钮”后,然后在输入标题文本值以及从中选择日期时创建DateToRemember类的新实例。 datepicker,使用这些值更新该实例。然后,用户将可以单击“提交”按钮并更新其列表。

这是我要记住模特的日期:

  class DateToRemember {
  String title;
  DateTime date;

  DateToRemember(this.title, this.date);
}

和datestoremember页面代码:

class DatesToRemember extends StatefulWidget {
  @override
  _DatesToRememberState createState() => _DatesToRememberState();
}

class _DatesToRememberState extends State<DatesToRemember> {
  TextEditingController _titleController = new TextEditingController();

  DateTime startDate = DateTime.now();

  DateTime pickedDate = DateTime.now();

  DateFormat formatter = DateFormat('dd/MM/yyyy');

  _DatesToRememberState();

  Future displayDatePicker(BuildContext context) async {
    final DateTime picked = await showDatePicker(
        context: context,
        initialDate: startDate,
        firstDate: startDate,
        lastDate: DateTime(DateTime.now().year + 100));
    if (picked != null)
      setState(() {
        pickedDate = picked;
        print(DateFormat('dd/MM/yyyy').format(pickedDate).toString());
      });

  }

  final List<DateToRemember> occasions = [
    DateToRemember("Occasion 1", DateTime.now()),
    DateToRemember("Occasion 2", DateTime.now()),
    DateToRemember("Occasion 3", DateTime.now()),
  ];

  String input;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        resizeToAvoidBottomInset: false,
        appBar: AppBar(
          leading: GestureDetector(
              onTap: () => Navigator.pop(context),
              child: Icon(Icons.arrow_back)),
          title: Text('Dates to Remember'),
        ),
        backgroundColor: Colors.white,
        body: Center(
          child: Column(children: [
            SizedBox(
              height: 10.0,
            ),
            Container(
              width: MediaQuery.of(context).size.width * 0.8,
              child: Text(
                "It can be difficult to ",
                style: TextStyle(fontFamily: FontNameDefault),
              ),
            ),
            SizedBox(
              height: 50.0,
            ),
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: Align(
                alignment: Alignment.centerRight,
                child: FloatingActionButton(
                    backgroundColor: kPrimaryColor,
                    child: Icon(Icons.add),
                    onPressed: () {
                      // CREATE NEW INSTANCE OF DATETOREMEMBER CLASS
                      showDialog(
                          context: context,
                          builder: (BuildContext context) {
                            return AlertDialog(
                              title: Text('Add occasion'),
                              content: Container(
                                height: 150.0,
                                child: Column(
                                  children: [
                                    TextField(
                                      decoration: InputDecoration(
                                          hintText: 'Occasion Title'),
                                      //UPDATE TITLE IN CLASS WITH INPUT
                                      //
                                    ),
                                    TextField(
                                      decoration: InputDecoration(
                                          hintText: 'Pick Date'),
                                      onTap: () async {
                                        await displayDatePicker(context);
                                        //SELECT DATE AND UPDATE INSTANCE OF CLASS
                                      },
                                    ),
                                    FlatButton(
                                      child: Text('Submit'),
                                      onPressed: () {
                                        //Navigator.of(context).pop();
                                      },
                                    ),
                                  ],
                                ),
                              ),
                            );
                          });
                    }),
              ),
            ),
            Container(
              height: MediaQuery.of(context).size.height * 0.6,
              width: MediaQuery.of(context).size.width * 0.9,
              decoration:
                  BoxDecoration(border: Border.all(color: Colors.black26)),
              child: occasions.isEmpty
                  ? Center(
                      child: Text(
                      'Add an occasion',
                      style: TextStyle(color: Colors.black),
                    ))
                  : ListView.builder(
                      itemCount: occasions.length,
                      itemBuilder: (BuildContext context, int index) {
                        return Dismissible(
                          direction: DismissDirection.endToStart,
                          onDismissed: (direction) {
                            occasions.removeAt(index);
                            Scaffold.of(context).showSnackBar(new SnackBar(
                              content: Text('Occasion Removed'),
                              duration: Duration(seconds: 5),
                            ));
                          },
                          key: UniqueKey(),
                          child: Card(
                            elevation: 8.0,
                            margin: EdgeInsets.all(8),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(8),
                            ),
                            child: ListTile(
                              title: Text(occasions[index].title),
                              subtitle: Text(DateFormat('dd/MM/yyyy')
                                  .format(occasions[index].date)
                                  .toString()),
                              trailing: IconButton(
                                icon: Icon(
                                  Icons.delete,
                                  color: Colors.red,
                                ),
                                onPressed: () {
                                  setState(() {
                                    occasions.removeAt(index);
                                    Scaffold.of(context)
                                        .showSnackBar(new SnackBar(
                                      content: Text('Occasion Removed'),
                                      duration: Duration(seconds: 5),
                                    ));
                                  });
                                },
                              ),
                            ),
                          ),
                        );
                      }),
            )
          ]),
        ));
  }
}

我仍然是个扑朔迷离的新手,所以不能完全确定我要问的是实现我想要的最好方法,因此也欢迎新想法。谢谢。

0 个答案:

没有答案