将数据上传到Firebase数据库

时间:2020-07-20 12:56:11

标签: flutter firebase-realtime-database upload

在尝试将数据上传到Firebase实时数据库时出现错误。 按下保存按钮填充表单数据后。调用uploadPic函数,将文本从文本字段上传到Firebase,错误消息出现在Android Studio的控制台上。

该错误的屏幕截图位于下面的链接中。

下面还会提到代码, uploadPic函数位于第72行

代码:

import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:image_picker/image_picker.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:udharibook/Screens/dashboard.dart';

class UserProfile extends StatefulWidget {
  @override
  _UserProfileState createState() => _UserProfileState();
}

class _UserProfileState extends State<UserProfile> {
  var _formKey = GlobalKey<FormState>();
  TextEditingController nameController;
  TextEditingController phoneController;
  TextEditingController emailController;
  TextEditingController addressController;
  var profileImage =
      'https://firebasestorage.googleapis.com/v0/b/udhari-book.appspot.com/o/DefaultImage.png?alt=media&token=06bddd3e-7f11-476b-a982-dfb21096f9c7';
  File _image;
  String fileName;
  static var userId;
  FirebaseAuth _auth = FirebaseAuth.instance;
  DatabaseReference DBRef =
      FirebaseDatabase.instance.reference().child('Users');

  void initState() {
    super.initState();
    _auth.currentUser().then((curUser) {


        userId = curUser.uid;
        print('Current user id:' + userId);
        DBRef.child(curUser.uid).once().then((DataSnapshot user) {
          if (user != null) {
            setState(() {
            //Provide the initial value of the user in the text field
              phoneController = TextEditingController(text: curUser.phoneNumber);
            profileImage = user.value['ProfileImage'];
            nameController = TextEditingController(text: user.value['Name']);
            emailController = TextEditingController(text: user.value['Email']);
            addressController =TextEditingController(text: user.value['Address']);
            });
          }

      });
    });
  }

  @override
  Widget build(BuildContext context) {
    Future getImage() async {
      var image = await ImagePicker.pickImage(source: ImageSource.gallery);
      _image = image;
      fileName = phoneController.text;
      StorageReference firebaseStorageRef =
      FirebaseStorage.instance.ref().child('Images/$fileName');
      StorageUploadTask uploadTask = firebaseStorageRef.putFile(_image);
      StorageTaskSnapshot imgSnapshot = await uploadTask.onComplete;
      if (imgSnapshot.error == null) {
        profileImage = await imgSnapshot.ref.getDownloadURL();
        }
      setState(() {
        print('Image uploaded successfully');
      });
    }

    Future uploadPic(BuildContext context) async {

        print('The user name is: '+nameController.text);
        DBRef.child(userId).set({
          'User Id': userId,
         'Name': nameController.text,
          'Mobile': fileName,
          'Email':emailController.text,
          'Address': addressController.text,
          'ProfileImage': profileImage,
        });
        setState(() {
          print('Data uploaded Successfully');
          //DashboardPage(userName: nameController.text,imgUrl: imgUrl,);
        });
      }


    return Scaffold(
      appBar: AppBar(
        title: Text('User Profile'),
        backgroundColor: Color.fromRGBO(162, 42, 43, 1.0),
      ),
      body: Builder(
        builder: (context) => SingleChildScrollView(
          child: Form(
            key: _formKey,
            child: Column(
              children: <Widget>[
                SizedBox(
                  height: 10.0,
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    //Profile Image widget
                    Align(
                      alignment: Alignment.center,
                      child: CircleAvatar(
                        radius: 70,
                        backgroundColor: Colors.white,
                        child: ClipOval(
                          child: SizedBox(
                            height: 120.0,
                            width: 120.0,
                            child: _image != null
                                ? Image.file(_image, fit: BoxFit.fill)
                                : Image.network(
                                    profileImage,
                                    fit: BoxFit.fitWidth,
                                  ),
                          ),
                        ),
                      ),
                    ),
                    //Camera Icon Widget
                    Padding(
                      padding: EdgeInsets.only(),
                      child: IconButton(
                          icon: Icon(Icons.camera_alt),
                          onPressed: () {
                            getImage();
                          }),
                    )
                  ],
                ),

               //Name TextField
                Padding(
                  padding: EdgeInsets.only(top: 20.0, left: 10.0, right: 10.0),
                  child: TextFormField(
                    controller: nameController,
                    validator: (input) {
                      if (input.isEmpty) return 'Please enter Name';
                    },
                    decoration: InputDecoration(
                        contentPadding: new EdgeInsets.symmetric(vertical: 5.0,horizontal: 20.0),
                        labelText: 'Full Name',
                        labelStyle:
                            TextStyle(fontFamily: 'Exo2', color: Colors.grey),
                        border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(5.0)),
                        focusedBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(5.0),
                            borderSide: BorderSide(
                                color: Color.fromRGBO(162, 42, 43, 1.0)))),
                  ),
                ),


                //Mobile Text Field
                Padding(
                    padding:
                        EdgeInsets.only(top: 15.0, left: 10.0, right: 10.0),
                    child: SizedBox(
                      height: 40.0,
                      child: TextField(
                        controller: phoneController,
                        enabled: false,
                        keyboardType: TextInputType.phone,
                        decoration: InputDecoration(
                            contentPadding: new EdgeInsets.symmetric(vertical: 5.0,horizontal: 20.0),
                            labelText: 'Mobile Number',
                            labelStyle: TextStyle(
                                fontFamily: 'Exo2', color: Colors.grey),
                            border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(5.0)),
                            focusedBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(5.0),
                                borderSide: BorderSide(
                                    color: Color.fromRGBO(162, 42, 43, 1.0)))),
                      ),
                    )),


                //Email Text Field
                Padding(
                  padding: EdgeInsets.only(top: 15.0, left: 10.0, right: 10.0),
                  child: TextFormField(
                    controller: emailController,
                    validator: (input) {
                      if (input.isNotEmpty && input.contains('@') == false)
                        return 'Please enter correct Email Id';
                      else if (input.isEmpty) return 'Please enter Email Id';
                    },
                    keyboardType: TextInputType.emailAddress,
                    decoration: InputDecoration(
                        contentPadding: new EdgeInsets.symmetric(vertical: 5.0,horizontal: 20.0),
                        labelText: 'Email Id',
                        labelStyle:
                            TextStyle(fontFamily: 'Exo2', color: Colors.grey),
                        border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(5.0)),
                        focusedBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(5.0),
                            borderSide: BorderSide(
                                color: Color.fromRGBO(162, 42, 43, 1.0)))),
                  ),
                ),
                //Address Text Field
                Padding(
                  padding: EdgeInsets.only(
                      top: 15.0, left: 10.0, right: 10.0, bottom: 30.0),
                  child: TextFormField(
                    maxLines: 3,
                    maxLengthEnforced: true,
                    controller: addressController,
                    keyboardType: TextInputType.emailAddress,
                    decoration: InputDecoration(
                        labelText: 'Address (Optional)',
                        labelStyle:
                            TextStyle(fontFamily: 'Exo2', color: Colors.grey),
                        border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(5.0)),
                        focusedBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(5.0),
                            borderSide: BorderSide(
                                color: Color.fromRGBO(162, 42, 43, 1.0)))),
                  ),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: <Widget>[

                    //Save Button
                    SizedBox(
                        width: 130.0,
                        height: 50.0,
                        child: RaisedButton(
                          color: Color.fromRGBO(162, 42, 43, 1.0),
                          shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(18.0)),
                          onPressed: () {
                            if (_formKey.currentState.validate()) {
                              uploadPic(context);
                            } else
                              setState(() {});
                          },
                          elevation: 4.0,
                          splashColor: Colors.blueGrey,
                          child: Text(
                            'Save',
                            style: TextStyle(
                                color: Colors.white,
                                fontSize: 22.0,
                                fontFamily: 'Exo2'),
                          ),
                        )),

                    //Cancel Button
                    SizedBox(
                        width: 130.0,
                        height: 50.0,
                        child: RaisedButton(
                          color: Color.fromRGBO(162, 42, 43, 1.0),
                          shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(18.0)),
                          onPressed: () {
                            Navigator.of(context).pop();
                          },
                          elevation: 4.0,
                          splashColor: Colors.blueGrey,
                          child: Text(
                            'Cancel',
                            style: TextStyle(
                                color: Colors.white,
                                fontSize: 22.0,
                                fontFamily: 'Exo2'),
                          ),
                        ))
                  ],
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}

1 个答案:

答案 0 :(得分:0)

替换此:

TextEditingController nameController;
TextEditingController phoneController;
TextEditingController emailController;
TextEditingController addressController;

与此:

TextEditingController nameController = TextEditingController();
TextEditingController phoneController = TextEditingController();
TextEditingController emailController = TextEditingController();
TextEditingController addressController = TextEditingController();

并替换掉

onPressed: () {
if (_formKey.currentState.validate()) {
uploadPic(context);
}
else
setState(() {});
},

与此:

OnPressed: () {
setState(() {
if (_formKey.currentState.validate()) {
uploadPic(context);
} //else
});

                      },