一尘不染

无法从Firebase中的文本字段表单保存数据

flutter

我试图发送电子邮件,并将用户输入数据从flutter应用程序保存到firebase。

我的代码可以:我已经创建了能够发送电子邮件的应用程序,但是我被困在Firebase中保存这些文本字段数据。我已经在代码中实现了Cloud
Firestore,但出现了很多错误。

我的代码:

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

错误信息:

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');
              ^^^^^^^^^

在10,491毫秒内重新启动应用程序。

请帮助我解决此问题,并提及我在哪里出错。


阅读 312

收藏
2020-08-13

共1个答案

一尘不染

setState 接受一个没有参数且不返回数据的voidCallback:

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

基本上:

setState(() {

});

基本上()是回调的no参数,是回调{ //... }内部的代码。就您在回调中的情况而言,您要添加方法的实现,sendToServer()而您不能这样做。

sendToServer()是实例方法,它应该在sendMessage()或之外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"
              });
            });
          }
        }

关于其他错误,请在pubspec.yaml文件中添加以下依赖项:

  cloud_firestore: ^0.13.7
2020-08-13