【问题标题】:Exception has occurred. ArgumentError (Invalid argument: Instance of 'Future<dynamic>') Flutter Dart发生异常。 ArgumentError(无效参数:'Future<dynamic>' 的实例) Flutter Dart
【发布时间】:2020-09-03 09:39:59
【问题描述】:

我想将用户输入从 TextFormField 保存到 Cloud_Firestore。单击“保存”按钮时出现以下错误。 VSCode 指向“.add”。

DocumentReference ref = await db.collection('mealList').add({'Meal': meal, 'Date': _pickDate()});

在验证器上

运行此代码时出错

发生了异常。 ArgumentError(无效参数:'Future <.dynamic>' 的实例)

代码

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:mealapp/models/global.dart';
import 'package:mealapp/models/Widgets/custom_date_time_picker.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'dart:async';
import 'package:firebase_auth/firebase_auth.dart';


class WhatToEat extends StatefulWidget {

   final FirebaseUser user;

  WhatToEat({Key key, this.user }) : super(key: key);


  @override
  _WhatToEatState createState() => _WhatToEatState();
}

class _WhatToEatState extends State<WhatToEat> {

  TextEditingController mealController = new TextEditingController();

  String id;  
  final db = Firestore.instance;
  final _formKey = GlobalKey<FormState>();
  DateTime _selectedDate = DateTime.now();
  String meal;

  Color pickerColor = Color(0xff6633ff);
  Color currentColor = Color(0xff6633ff);


  Future _pickDate() async {
    DateTime datepick = await showDatePicker(
      context: context,
      initialDate: new DateTime.now(),
      firstDate: new DateTime.now().add(Duration(days: -365)),
      lastDate: new DateTime.now().add(Duration(days: 365)));
    if (datepick != null)
    setState(() {
      _selectedDate = datepick;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formKey,
      child: Padding(
      padding: const EdgeInsets.all(24.0),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Center(
              child: Text(
            "Add your new Meal",
            style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
          )),
          SizedBox(
            height: 24,
          ),
          TextFormField(
            decoration: InputDecoration(
            border: OutlineInputBorder(
              borderRadius: BorderRadius.all(Radius.circular(12))),
            labelText: 'Enter your Meal'),
            validator: (value) {
             if (value.isEmpty) {
              return 'Please enter some text';
              }
            },
            onSaved: (value) => meal = value,
           ),
           CustomDateTimePicker(
            icon: Icons.date_range,
            onPressed: _pickDate,
            value: new DateFormat("dd-MM-yyyy").format(_selectedDate),
            ),
        _actionButton(),
        ],
      ),
      ),
      );
  }

  Row _actionButton() {
    return Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          FlatButton(
            onPressed: (){
              Navigator.of(context).pop();
            },
            child: Text("Close"),
          ),
          FlatButton(
            onPressed: () async {
              saveToFirestore();
              Navigator.pop(context);
            },
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.all(Radius.circular(12))
              ),
            child: Text("Save"),
            color: redColor,
            textColor: Colors.white,
          ),
        ],
      );
  }

  void saveToFirestore() async {
    if (_formKey.currentState.validate()) {
      _formKey.currentState.save();
      DocumentReference ref = await db.collection('mealList').add({'Meal': meal, 'Date': _pickDate()});
      setState(() => id = ref.documentID);
      print(ref.documentID);
    }
  }
}

我该如何解决这个问题?

在验证器的 TextFormField 中,Value String 带有蓝色下划线。

为什么会这样?

【问题讨论】:

    标签: database firebase flutter dart google-cloud-firestore


    【解决方案1】:

    您提供的未来值作为无效的参数。

    尝试关注。

    void saveToFirestore() async {
        if (_formKey.currentState.validate()) {
          _formKey.currentState.save();
          await _pickDate();
          DocumentReference ref = await db.collection('mealList').add({'Meal': meal, 'Date': _selectedDate});
          setState(() => id = ref.documentID);
          print(ref.documentID);
        }
      }
    

    【讨论】:

    • 感谢您的快速评论。它帮助了我。云,请您再帮我解决一个问题。当我打开表格时,将显示一个日期。如果我输入膳食并点击保存而不选择日期,我会得到与上述相同的错误。我的问题:我怎样才能显示一个空的日期,选择一个日期后会在下面显示?
    猜你喜欢
    • 2019-02-27
    • 1970-01-01
    • 2019-09-08
    • 2021-09-22
    • 1970-01-01
    • 1970-01-01
    • 2018-11-24
    • 2020-08-31
    • 2019-11-21
    相关资源
    最近更新 更多