Unable to save the data from the textfields forms in the firebase

不羁岁月 提交于 2020-07-28 04:59:33

问题


I was trying to send an email and save the user input data to the firebase from the flutter application.

My code does: I have created the application which is capable to send email but I have got stuck to save those text fields data in the firebase. I have implemented the cloud firestore in the code but I am getting quite a few errors.

My code:

import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter_email_sender/flutter_email_sender.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Home(),
    );
  }
}

class Home extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _HomeState();
  }
}

class _HomeState extends State<Home> {
  var _emailFormKey = GlobalKey<FormState>();
  TextEditingController emailController = new TextEditingController();
  TextEditingController nameController = new TextEditingController();
  TextEditingController numberController = new TextEditingController();

  @override
  Widget build(BuildContext context) {
// TODO: implement build
    return Scaffold(
      resizeToAvoidBottomPadding: false,
      appBar: AppBar(
        title: Text("Email sending App"),
      ),
      body: Form(
        key: _emailFormKey,
        child: Column(
          children: <Widget>[
            Container(
              margin: EdgeInsets.only(top: 50.0, left: 15.0, right: 15.0),
              child: TextFormField(
                controller: emailController,
                validator: (value) {
                  if (value.isEmpty) {
                    return "please enter emailid";
                  }
                },
                decoration: InputDecoration(
                    labelText: "Enter email id",
                    border: OutlineInputBorder(
                        borderSide: BorderSide(
                      color: Colors.red,
                      width: 2.0,
                    ))),
              ),
            ),
            Container(
              margin: EdgeInsets.only(top: 15.0, left: 15.0, right: 15.0),
              child: TextFormField(
                controller: numberController,
                validator: (value) {
                  if (value.isEmpty) {
                    return "please enter number";
                  }
                },
                decoration: InputDecoration(
                    labelText: "Enter number",
                    border: OutlineInputBorder(
                        borderSide: BorderSide(
                      color: Colors.red,
                      width: 2.0,
                    ))),
              ),
            ),
            Container(
              margin: EdgeInsets.only(top: 15.0, left: 15.0, right: 15.0),
              child: TextFormField(
                controller: nameController,
                validator: (value) {
                  if (value.isEmpty) {
                    return "please Enter name";
                  }
                },
                decoration: InputDecoration(
                    labelText: "Enter name",
                    border: OutlineInputBorder(
                        borderSide: BorderSide(
                      color: Colors.red,
                      width: 2.0,
                    ))),
              ),
            ),
            Container(
              margin: EdgeInsets.only(top: 15.0),
              child: RaisedButton(
                  child: Text("Send"),
                  onPressed: () {
                    if (_emailFormKey.currentState.validate()) {
                      sendMessage();
                      //function to send data in the firebase
                      sendToServer();
                    }
                  }),
            )
          ],
        ),
      ),
    );
  }

  void sendMessage() {
    var PhoneNumber;
    String Name;
    String Emailid;
    Email email;
    setState(() {
      Emailid = emailController.text;
      Name = nameController.text;
      PhoneNumber = numberController.text;
      String messageBody = '$Name \n $PhoneNumber \n $Emailid';
      if (Name.isNotEmpty && Emailid.isNotEmpty && PhoneNumber.isNotEmpty) {
        email = Email(
          body: messageBody,
          subject: 'Email subject',
          recipients: ['onlineproductsking1@gmail.com'],
        );
        send(email);
        sendToServer() {
          if (_emailFormKey.currentState.validate()) {
            //No error in validator
            _emailFormKey.currentState.save();
            Firestore.instance.runTransaction((Transaction transaction) async {
              CollectionReference reference =
                  Firestore.instance.collection('contact');

              await reference.add({
                "Name": "$Name",
                "Phone Number": "$PhoneNumber",
                "Email Id": "$Emailid"
              });
            });
            // } else {
            //   // validation error
            //   setState(() {
            //           // _validate = true;
            //         });
            // }

          }
        }
      }
    });
    debugPrint('name -> $Name, number -> $PhoneNumber, emailid -> $Emailid');
  }

  void send(Email email) async {
    await FlutterEmailSender.send(email);
  }
}

Error Message:

Compiler message:
       ^
lib/contact_form.dart:107:23: Error: The method 'sendToServer' isn't defined for the class '_HomeState'.
 - '_HomeState' is from 'package:pdf/contact_form.dart' ('lib/contact_form.dart').
Try correcting the name to the name of an existing method, or defining a method named 'sendToServer'.
                      sendToServer();
                      ^^^^^^^^^^^^
lib/contact_form.dart:138:48: Error: 'Transaction' isn't a type.
            Firestore.instance.runTransaction((Transaction transaction) async {
                                               ^^^^^^^^^^^
lib/contact_form.dart:139:15: Error: 'CollectionReference' isn't a type.
              CollectionReference reference =
              ^^^^^^^^^^^^^^^^^^^
lib/contact_form.dart:138:13: Error: The getter 'Firestore' isn't defined for the class '_HomeState'.
 - '_HomeState' is from 'package:pdf/contact_form.dart' ('lib/contact_form.dart').
Try correcting the name to the name of an existing getter, or defining a getter or field named 'Firestore'.
            Firestore.instance.runTransaction((Transaction transaction) async {
            ^^^^^^^^^
lib/contact_form.dart:140:19: Error: The getter 'Firestore' isn't defined for the class '_HomeState'.
 - '_HomeState' is from 'package:pdf/contact_form.dart' ('lib/contact_form.dart').
Try correcting the name to the name of an existing getter, or defining a getter or field named 'Firestore'.
                  Firestore.instance.collection('books');
              ^^^^^^^^^

Restarted application in 10,491ms.

Please help me resolve this issue and mentioned where was I going wrong.


回答1:


setState takes a voidCallback that have no arguments and doesn't return a data:

https://api.flutter.dev/flutter/widgets/State/setState.html

Basically:

setState(() {
                           
});

Basically () is the no arguments of the callback and { //... } is the code inside the callback. In your case inside the callback, you are adding an implemenation of the method sendToServer() and you cant do that..

sendToServer() is an instance method and it should be outside sendMessage() or setState:

  void sendMessage() {
    var PhoneNumber;
    String Name;
    String Emailid;
    Email email;
    setState(() {
      Emailid = emailController.text;
      Name = nameController.text;
      PhoneNumber = numberController.text;
      String messageBody = '$Name \n $PhoneNumber \n $Emailid';
      if (Name.isNotEmpty && Emailid.isNotEmpty && PhoneNumber.isNotEmpty) {
        email = Email(
          body: messageBody,
          subject: 'Email subject',
          recipients: ['onlineproductsking1@gmail.com'],
        );
        send(email);
      }
    });
    debugPrint('name -> $Name, number -> $PhoneNumber, emailid -> $Emailid');
  }

        sendToServer() {
          if (_emailFormKey.currentState.validate()) {
            //No error in validator
            _emailFormKey.currentState.save();
            Firestore.instance.runTransaction((Transaction transaction) async {
              CollectionReference reference =
                  Firestore.instance.collection('contact');

              await reference.add({
                "Name": "$Name",
                "Phone Number": "$PhoneNumber",
                "Email Id": "$Emailid"
              });
            });
          }
        }

Regarding the other errors, in your pubspec.yaml file add the following dependency:

  cloud_firestore: ^0.13.7


来源:https://stackoverflow.com/questions/63102887/unable-to-save-the-data-from-the-textfields-forms-in-the-firebase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!