firebase 发送到Firestore时DateTime变为空

ohtdti5x  于 2023-02-16  发布在  其他
关注(0)|答案(1)|浏览(112)

我创建了一个TextFormField来将DateTime发送到firestore集合,但是当我发送信息时,它在"datasaida"上得到一个空字段:

这是密码:

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

  @override
  State<AddSaida> createState() => _AddSaidaState();
}

class _AddSaidaState extends State<AddSaida> {
  
  String? valorsaida,nomesaida,datasaida;

  getSaidaValue(valorsaida){
    this.valorsaida=valorsaida;
  }
  getSaidaName(nomesaida){
    this.nomesaida=nomesaida;
  }
  getSaidaDate(datasaida){
    this.datasaida=datasaida;
  }

createData(){
    DocumentReference ds=FirebaseFirestore.instance.collection('addsaidas').doc(nomesaida);
    Map<String,dynamic> tasks={
       "valorsaida":valorsaida,
        "nomesaida":nomesaida,
        "datasaida":datasaida,
        "tipocategoria":categVal,
    };

    ds.set(tasks).whenComplete((){
      print("task updated");
    });

  }

var saidanamecontroller = TextEditingController();
var saidadatecontroller = TextEditingController();
var saidavaluecontroller = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
appBar: AppBar(
        backgroundColor: Color.fromARGB(255, 92, 172, 178),
        centerTitle: true,
        title: Text('Adicionar saída'),
        toolbarHeight: 90,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(40)
          ),        
        elevation: 15,
      ),
      body:
       SingleChildScrollView(
       child: Container(
        padding: const EdgeInsets.all(28),

        child: Column(
          children: [

        TextFormField(
          controller: saidanamecontroller,
          onChanged: (String nomesaida){
            getSaidaName(nomesaida);
          },
              autofocus: true,
              decoration: InputDecoration(
                contentPadding: EdgeInsets.fromLTRB(12, 0, 12, 0),
                hintText: "Nome da saída",
                hintStyle: TextStyle(color: Color.fromARGB(255, 138, 136, 136),
                fontSize: 18),
                prefixIcon: Icon(
                                Icons.label_important_outline,
                                color: Color.fromARGB(255, 92, 172, 178),
                                size: 30,
                                ),
                              labelText: "Nome da saída",
                              labelStyle: TextStyle(color: Color.fromARGB(255, 136, 136, 136), fontFamily: 'PathwayGothicOne', fontSize: 13),
),
                                

SizedBox(height: 20),

 TextFormField(
            controller: saidadatecontroller,
            onChanged: (datasaida){
              getSaidaName(datasaida);
            },
              autofocus: true,
              decoration: InputDecoration(
                contentPadding: EdgeInsets.fromLTRB(12, 0, 12, 0),
                hintStyle: TextStyle(color: Color.fromARGB(255, 138, 136, 136),
                fontSize: 18),
                prefixIcon: Icon(
                                Icons.calendar_month_outlined,
                                color: Color.fromARGB(255, 92, 172, 178),
                                size: 30,
                                ),
                              labelText: "Data da saída",
                              labelStyle: TextStyle(color: Color.fromARGB(255, 136, 136, 136), fontFamily: 'PathwayGothicOne', fontSize: 13),
                              enabledBorder: UnderlineInputBorder(
                                  borderSide: BorderSide(
                                    color: Color.fromARGB(153, 191, 190, 190),
                                  ),
                                ),
                                focusedBorder: UnderlineInputBorder(
                                  borderSide: BorderSide(
                                    color: Color.fromARGB(153, 191, 190, 190),
                                  ),
                                ),
                              ),
                            onTap: () async {
                              DateTime? pickeddate = await showDatePicker(
                                context: context, 
                                initialDate: DateTime.now(), 
                                firstDate: DateTime(2022), 
                                lastDate: DateTime(2036));

                                if (pickeddate != null) {
                                    saidadatecontroller.text = DateFormat('dd-MM-yyyy').format(pickeddate);
                                }
                            },

其他字段都工作正常,这是唯一一个得到一个空值。我曾试图将值转换为字符串,但我不能。
我不知道该怎么办,请帮帮我!

mutmk8jj

mutmk8jj1#

出现这种行为是因为datasaida在设置到firestore文档之前为null。
您仅在onChanged事件上设置datasaida,但也需要在onTap事件上设置它,以便它在所有日期选择器事件中不能为空,即使为空值,它也将具有“”字符串。
这里我在DateTime类型的单数TextFormField上进行了测试:

class AddSaida extends StatefulWidget {
  const AddSaida({Key? key}) : super(key: key);
  @override
  State<AddSaida> createState() => _AddSaidaState();
}

class _AddSaidaState extends State<AddSaida> {
  final _dateController = TextEditingController();
  String? datasaida;
  getSaidaName(datasaida) {
    this.datasaida = datasaida;
  }

  createData() {
    if (datasaida != null) {
      DocumentReference ds = FirebaseFirestore.instance
          .collection('addsaidas')
          .doc("cnFxQ8wRivY39EywI3TS"); //just a existing docId 
      Map<String, dynamic> tasks = {
        "datasaida": datasaida,
      };

      ds.set(tasks).whenComplete(() {
        print("task updated");
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          TextFormField(
            controller: _dateController,
            decoration: const InputDecoration(
              labelText: 'Date',
            ),
            onTap: () async {
              DateTime? pickedDate = await showDatePicker(
                context: context,
                initialDate: DateTime.now(),
                firstDate: DateTime(2022),
                lastDate: DateTime(2036),
              );
              if (pickedDate != null) {
                _dateController.text =
                    DateFormat('dd-MM-yyyy').format(pickedDate);
                getSaidaName(DateFormat('dd-MM-yyyy').format(pickedDate)); // ⇐ Notice
              }
            },
            onChanged: (value) {
              getSaidaName(value);
            },
          ),
          ElevatedButton(
            onPressed: createData,
            child: const Text('Save Date'),
          ),
        ],
      ),
    );
  }
}

相关问题