发生异常。 ArgumentError(无效参数:“ Future <dynamic>”的实例)Flutter Dart

时间:2020-05-17 16:35:12

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

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

DocumentReference ref =等待db.collection('mealList')。add({'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中,值字符串用蓝色下划线显示。

为什么会这样?

1 个答案:

答案 0 :(得分:0)

您提供的未来价值是无效的参数。

尝试关注。

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);
    }
  }