引发了另一个异常:NoSuchMethodError:在null上调用了setter“ wastedate =”

时间:2020-03-09 02:46:03

标签: firebase flutter dart

我在表单上收到以下错误,我正在尝试将表单页面提交到Firebase数据库。错误是“引发了另一个异常:NoSuchMethodError:在null上调用了setter'wastedate ='。”我认为它必须与_saveWaste函数有关,因为打印显示为“调用了saveWaste”,而不是“已保存表单”。

import 'dart:io';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:async';
import 'package:wasteagram/model/waste.dart';
import 'package:path/path.dart' as path;
import 'package:uuid/uuid.dart';

class CameraScreen extends StatefulWidget {

  final bool isUpdating; 

  CameraScreen({@required this.isUpdating}); 

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

class _CameraScreenState extends State<CameraScreen> {

  final GlobalKey<FormState> _formKey = GlobalKey<FormState>(); 
  Waste _currentWaste; 

  Widget _buildDateField() {
    return Form(
      key: _formKey, 
      child: TextFormField(
        decoration: InputDecoration(labelText: 'Date'),
        keyboardType: TextInputType.text,
        style: TextStyle(fontSize: 20), 
        validator: (String value) {
          if(value.isEmpty){
            return 'Date required'; 
          }
          if(value.length < 3 || value.length > 20) {
            return 'Name must be more than 3 or less than 20'; 
          }
          return null;
        },

        onSaved: (String value) {
          _currentWaste.wastedate = value; 
        },
      ),
    );
  }

  Widget _buildWasteNumber() {
    return Form(

          child: TextFormField(
        decoration: InputDecoration(labelText: 'Number'),
        keyboardType: TextInputType.number,
        style: TextStyle(fontSize: 20), 
        validator: (value) {
          if(value.isEmpty){
            return 'Number required'; 
          }
          return null;
        },

        onSaved: (String value) {
          String wasteNum = _currentWaste.wastenumber.toString();
          wasteNum = value; 
        },
      ),
    );
  }

  _saveWaste(context) {

    print("saveWaste Called"); 
    if(!_formKey.currentState.validate()) {
      return "FALSE"; 
    }

    _formKey.currentState.save(); 

    print("form saved");

    uploadItems(_currentWaste, widget.isUpdating, image);  


    print("date ${_currentWaste.wastedate}"); 
    print("number ${_currentWaste.wastenumber.toString()}");
    print("_imageFile ${image.toString()}");
  }

  File image; 

  void getImage() async {
    image = await ImagePicker.pickImage(source: ImageSource.gallery); 
    setState( () {}); 
  }

  @override 
  Widget build(BuildContext context) {
    if (image == null) {
      return Scaffold(
      appBar: AppBar(
        title: Text('Wasteagram')
      ), 
      body: Center(
          child: RaisedButton(
            child: Text('Select Photo'),
            onPressed: () {
              getImage(); 
            },
          ),
        ),
      ); 
    } else {
      return Scaffold(
        appBar: AppBar(
          title: Text('Wasteagram')
          ), 
          body: Column(
            mainAxisAlignment: MainAxisAlignment.center,
              children: [
            Image.file(image),
            SizedBox(height: 40), 
            RaisedButton(
              child: Text('Select Photo'),
              onPressed: () {
                getImage(); 
              }
            ), 
            _buildDateField(),
            _buildWasteNumber(),
              ],
            ),
          floatingActionButton: FloatingActionButton(
            onPressed: () => _saveWaste(context),
            child: Icon(Icons.save),
            foregroundColor: Colors.white,
          ),

        ); 
    }
  }
}

uploadItems(Waste waste, bool isUpdating, File localFile) async {
  if (localFile != null) {
    print("uploading image"); 

    var fileExtension = path.extension(localFile.path); 
    print(fileExtension); 

    var uuid = Uuid().v4(); 

    final StorageReference firebaseStorageRef = 
      FirebaseStorage.instance.ref().child('/$uuid$fileExtension'); 

      await firebaseStorageRef.putFile(localFile).onComplete.catchError(
        (onError){
          print(onError); 
          return false; 
        }
      ); 

      String url = await firebaseStorageRef.getDownloadURL(); 
      print("download url: $url"); 
      _uploadWaste(waste, isUpdating, imageUrl: url); 
  } else {
    print("skipping image upload"); 
    _uploadWaste(waste, isUpdating); 

  }
}

_uploadWaste(Waste waste, bool isUpdating, {String imageUrl}) async {
  CollectionReference wasteRef = Firestore.instance.collection('todolist'); 

  if(imageUrl != null) {
    waste.image = imageUrl; 
  }

  if(isUpdating) {

    waste.updatedAt = Timestamp.now(); 

    await wasteRef.document(waste.id).updateData(waste.toMap()); 
  print("updated waste with id: ${waste.id}"); 
  } else {

    DocumentReference documentRef = await wasteRef.add(waste.toMap()); 

    waste.id = documentRef.documentID; 

    print("uploaded waste successfully: ${waste.toString()}"); 

    await documentRef.setData(waste.toMap(), merge: true); 
  }


}

1 个答案:

答案 0 :(得分:0)

您必须初始化_currentWaste,它是null
请从

更改
Waste _currentWaste; 

收件人

Waste _currentWaste = Waste();