繁体   English   中英

Flutter 中的保存方法以及如何将数据保存到 Firestore?

[英]Save method in Flutter and how to save data to Firestore?

我想知道在 flutter 表单中调用 save 方法时表单数据存储在哪里。 我想将该数据保存在 map 中并将这些数据写入 Firestore,我应该怎么做,或者有没有其他方法可以将这些数据存储在 Firestore 中? 这是我的 flutter 表格的代码:

class _MyCustomFormState extends State<MyCustomForm> {
  final formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    var ht = MediaQuery.of(context).size.height;
    var wd = MediaQuery.of(context).size.width;
    return Container(
      margin: EdgeInsets.all(wd / 20),
      child: Form(
        key: formKey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Padding(
              padding: EdgeInsets.fromLTRB(0, 0, 0, ht / 70),
              child: Text(
                "Subject",
                style:
                    TextStyle(fontSize: ht / 30, fontWeight: FontWeight.w500),
              ),
            ),
            TextFormField(
              decoration: InputDecoration(
                border: OutlineInputBorder(),
                hintText: 'Type Subject name here',
              )                 
            ),
            Padding(
              padding: EdgeInsets.fromLTRB(0, ht / 50, 0, ht / 70),
              child: Text(
                "Class Link",
                style:
                    TextStyle(fontSize: ht / 30, fontWeight: FontWeight.w500),
              ),
            ),
            TextFormField(
              decoration: InputDecoration(
                border: OutlineInputBorder(), // UnderlineInputBorder(),
                hintText: 'Paste class link here',
              ),
              
            ),
            SizedBox(
              height: ht / 50,
            ),
            Center(
                child: Text(
              "Timing",
              style: TextStyle(fontSize: ht / 30, fontWeight: FontWeight.w500),
            )),
            Row(mainAxisAlignment: MainAxisAlignment.center, children: [
              BasicTimeField(), // This widget will let you choose two timings
              SizedBox(
                width: wd / 9,
                child: Center(
                  child: Text(
                    "to",
                    style: TextStyle(
                        fontSize: ht / 40, fontWeight: FontWeight.w400),
                  ),
                ),
              ),
              BasicTimeField() // This widget will let you choose two timings
            ]),
            SizedBox(
              height: ht / 40,
            ),
            Center(
                child: Text(
              "Select days of week",
              style: TextStyle(fontSize: ht / 30, fontWeight: FontWeight.w500),
            )),
            DayPicker(), //This widget will let you choose days of the week
            SizedBox(
              height: ht / 20,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                ElevatedButton(
                  child: Text('Add'),
                  onPressed: () {
                    formKey.currentState?.save();
                  },
                ),
                const SizedBox(
                  width: 50,
                ),
                ElevatedButton(
                  child: Text('Reset'),
                  onPressed: () {
                    formKey.currentState?.reset();
                  },
                ),
              ],
            )
          ],
        ),
      ),
    );
  }
}

这是我用来让用户选择时间的 BasicTimeField 小部件:

class BasicTimeField extends StatelessWidget {
  final format = DateFormat.Hm();
  @override
  Widget build(BuildContext context) {
    var wd = MediaQuery.of(context).size.width;
    return SizedBox(
      width: wd / 4,
      child: DateTimeField(
        format: format,
        decoration: InputDecoration(border: UnderlineInputBorder()),
        onShowPicker: (context, currentValue) async {
          final TimeOfDay? time = await showTimePicker(
            context: context,
            initialTime: TimeOfDay.fromDateTime(currentValue ?? DateTime.now()),
          );
          return time == null ? null : DateTimeField.convert(time);
        },
      ),
    );
  }
}

这是我的 DayPicker 小部件,它允许用户选择一周中的哪几天:

class DayPicker extends StatefulWidget {
  @override
  _DayPickerState createState() => _DayPickerState();
}

class _DayPickerState extends State<DayPicker> {
  final values2 = List.filled(7, false);

  @override
  Widget build(BuildContext context) {
    var ht = MediaQuery.of(context).size.height;
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        SizedBox(
          height: ht / 40,
        ),
        Text(
          'Selected Day(s): ${valuesToEnglishDays(values2, true)}',
          style: TextStyle(fontSize: ht / 40, fontStyle: FontStyle.italic),
        ),
        WeekdaySelector(
          onChanged: (v) {
            setState(() {
              values2[v % 7] = !values2[v % 7];
            });
          },
          values: values2,
          selectedFillColor: Colors.amber,
          selectedColor: Colors.black,
          selectedShape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(5),
          ),
          shape: RoundedRectangleBorder(
            side: BorderSide(color: Colors.red.withOpacity(0.5)),
            borderRadius: BorderRadius.circular(25),
          ),
        ),
      ],
    );
  }
}

从上面的代码中,我生成了以下表格:

在此处输入图像描述

我应该在我的代码中进行哪些修改以将此数据存储在 Firestore 中(我已经在 Firebase 中创建了集合)。

我会有这样的结构:

包含用户的主要集合。 因此,每个用户都是一个文档,并使用用户 ID 来创建该文档。

然后是用户文档中的一个集合,其中包含该用户类。

并且该集合中的类在每个文档上都有一个自动 ID,因此您可以稍后在需要更新时在该文档中引用它

像这样构造数据

`FirebaseFirestore.instance
.collection('users')
.doc('the users id')
.collection('classes')
.doc()
.add({
    'subject': 'A subject',
    'classLink': 'the link',
    'startHour': Your picked date as Timestamp,
    'endHour': Your picked date as Timestamp,
    'weekDays':{'mon': true, 'tue': false ... ... ...},`

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM