如何修复颤音中的文本输入形式

发布于 2025-01-24 05:11:09 字数 5198 浏览 0 评论 0原文

我有一个从网上获得的基本电子邮件联系表,我正在尝试发送示例电子邮件,但是某些原因我无法在提交的输入中输入任何文本。有什么建议或想法可能是什么?

每当删除_FormKey时,我都可以输入文本,但是我无法成功发送电子邮件。

任何建议或帮助都将不胜感激。

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:email_validator/email_validator.dart';

import 'package:http/http.dart' as http;



class EmailForm extends StatelessWidget {
  EmailForm({Key? key}) : super(key: key);

  final _formKey = GlobalKey<FormState>();
  final nameController = TextEditingController();
  final emailController = TextEditingController();
  final messageController = TextEditingController();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xfff5f5fd),
      body: Center(
        child: Container(
          height: 450,
          width: 400,
          margin: const EdgeInsets.symmetric(
            horizontal: 40,
            vertical: 20,
          ),
          padding: const EdgeInsets.symmetric(
            horizontal: 40,
            vertical: 20,
          ),
          decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(10),
              boxShadow: [
                BoxShadow(
                    offset: const Offset(0, 5),
                    blurRadius: 10,
                    spreadRadius: 1,
                    color: Colors.grey[300]!)
              ]),
          child: Form(
            key: _formKey,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                const Text('Contact Us',
                    style:
                        TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
                TextFormField(
                  controller: nameController,
                  decoration: const InputDecoration(hintText: 'Name'),
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return '*Required';
                    }
                    return null;
                  },
                ),
                TextFormField(
                  controller: emailController,
                  decoration: const InputDecoration(hintText: 'Email'),
                  validator: (email) {
                    if (email == null || email.isEmpty) {
                      return 'Required*';
                    } else if (!EmailValidator.validate(email)) {
                      return 'Please enter a valid Email';
                    }
                    return null;
                  },
                ),
                TextFormField(
                  controller: messageController,
                  decoration: const InputDecoration(hintText: 'Message'),
                  maxLines: 5,
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return '*Required';
                    }
                    return null;
                  },
                ),
                SizedBox(
                  height: 45,
                  width: 110,
                  child: TextButton(
                    style: TextButton.styleFrom(
                        primary: Colors.white,
                        backgroundColor: const Color(0xff151534),
                        shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(40))),
                    onPressed: () async {
                      if (_formKey.currentState!.validate()) {
                        final response = await sendEmail(
                            nameController.value.text,
                            emailController.value.text,
                            messageController.value.text);
                        ScaffoldMessenger.of(context).showSnackBar(
                          response == 200
                              ? const SnackBar(
                                  content: Text('Message Sent!'),
                                  backgroundColor: Colors.green)
                              : const SnackBar(
                                  content: Text('Failed to send message!'),
                                  backgroundColor: Colors.red),
                        );
                        nameController.clear();
                        emailController.clear();
                        messageController.clear();
                      }
                    },
                    child: const Text('Send', style: TextStyle(fontSize: 16)),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

Future sendEmail(String name, String email, String message) async {
  final url = Uri.parse('https://api.emailjs.com/api/v1.0/email/send');
  final response = await http.post(url,
      headers: {'Content-Type': 'application/json'},
      body: json.encode({
        'service_id': '',
        'template_id': '',
        'user_id': '',
        'template_params': {
          'from_name': name,
          'from_email': email,
          'message': message
        }
      }));
  return response.statusCode;
}

I have a basic email contact form that I got from online and I'm trying to send a sample email but some reason I can not enter any text in my input filed. Any suggestion or idea what it might be?

I can enter a text when ever I delete my _formKey but I can not send the email successfully anymore.

Any suggestion or help will be really appreciated.

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:email_validator/email_validator.dart';

import 'package:http/http.dart' as http;



class EmailForm extends StatelessWidget {
  EmailForm({Key? key}) : super(key: key);

  final _formKey = GlobalKey<FormState>();
  final nameController = TextEditingController();
  final emailController = TextEditingController();
  final messageController = TextEditingController();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xfff5f5fd),
      body: Center(
        child: Container(
          height: 450,
          width: 400,
          margin: const EdgeInsets.symmetric(
            horizontal: 40,
            vertical: 20,
          ),
          padding: const EdgeInsets.symmetric(
            horizontal: 40,
            vertical: 20,
          ),
          decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(10),
              boxShadow: [
                BoxShadow(
                    offset: const Offset(0, 5),
                    blurRadius: 10,
                    spreadRadius: 1,
                    color: Colors.grey[300]!)
              ]),
          child: Form(
            key: _formKey,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                const Text('Contact Us',
                    style:
                        TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
                TextFormField(
                  controller: nameController,
                  decoration: const InputDecoration(hintText: 'Name'),
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return '*Required';
                    }
                    return null;
                  },
                ),
                TextFormField(
                  controller: emailController,
                  decoration: const InputDecoration(hintText: 'Email'),
                  validator: (email) {
                    if (email == null || email.isEmpty) {
                      return 'Required*';
                    } else if (!EmailValidator.validate(email)) {
                      return 'Please enter a valid Email';
                    }
                    return null;
                  },
                ),
                TextFormField(
                  controller: messageController,
                  decoration: const InputDecoration(hintText: 'Message'),
                  maxLines: 5,
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return '*Required';
                    }
                    return null;
                  },
                ),
                SizedBox(
                  height: 45,
                  width: 110,
                  child: TextButton(
                    style: TextButton.styleFrom(
                        primary: Colors.white,
                        backgroundColor: const Color(0xff151534),
                        shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(40))),
                    onPressed: () async {
                      if (_formKey.currentState!.validate()) {
                        final response = await sendEmail(
                            nameController.value.text,
                            emailController.value.text,
                            messageController.value.text);
                        ScaffoldMessenger.of(context).showSnackBar(
                          response == 200
                              ? const SnackBar(
                                  content: Text('Message Sent!'),
                                  backgroundColor: Colors.green)
                              : const SnackBar(
                                  content: Text('Failed to send message!'),
                                  backgroundColor: Colors.red),
                        );
                        nameController.clear();
                        emailController.clear();
                        messageController.clear();
                      }
                    },
                    child: const Text('Send', style: TextStyle(fontSize: 16)),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

Future sendEmail(String name, String email, String message) async {
  final url = Uri.parse('https://api.emailjs.com/api/v1.0/email/send');
  final response = await http.post(url,
      headers: {'Content-Type': 'application/json'},
      body: json.encode({
        'service_id': '',
        'template_id': '',
        'user_id': '',
        'template_params': {
          'from_name': name,
          'from_email': email,
          'message': message
        }
      }));
  return response.statusCode;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

分开我的手 2025-01-31 05:11:09

当您使用表单窗口小部件时,您不一定需要使用控制器,您可以在TextFormField小部件中使用OnChange功能。

而不是定义像这样的textedingcontroller:

final nameController = TextEditingController();
final emailController = TextEditingController();

而是这样做:

var name = '';
var email = '';

而不是

TextFormField(
  controller: nameController,
  decoration: const InputDecoration(hintText: 'Name'),
  validator: (value) {
    if (value == null || value.isEmpty) {
      return '*Required';
    }
    return null;
  },
),

这样做:

TextFormField(
  decoration: const InputDecoration(hintText: 'Name'),
  validator: (value) {
    if (value == '') {
      return '*Required';
    }
    return null;
  },
  onChanged: (value) {
    name = value; //If it gives some null check error just add an exclamation like this - name = value!;
  }
),

现在,您只需要像使用任何普通变量一样在请求中传递这些变量。而不是使用namecontroller.text,而是只有名称(在开头创建的变量)就足够了。这应该使表格完美地工作。

如果您没有获得200个状态,那么问题也可能是您发送的数据与期望在服务器上接收的数据之间的区别。

为了找出根本原因,我建议您在各地添加打印语句,以查看哪些功能运行正常,哪些功能却没有。

打印来自服务器的错误语句可能有助于理解根部问题。因此,在返回状态代码之前先尝试一下

print(response.body); //Add this line for the output from the server
return response.statusCode;

,然后让我知道您在控制台中得到什么答复。

When you're using a Form Widget, you don't necessarily need to use controllers you can used the onchange function in your TextFormField Widget.

Instead of defining TextEditingControllers like this:

final nameController = TextEditingController();
final emailController = TextEditingController();

Do this instead:

var name = '';
var email = '';

Instead of

TextFormField(
  controller: nameController,
  decoration: const InputDecoration(hintText: 'Name'),
  validator: (value) {
    if (value == null || value.isEmpty) {
      return '*Required';
    }
    return null;
  },
),

Do this:

TextFormField(
  decoration: const InputDecoration(hintText: 'Name'),
  validator: (value) {
    if (value == '') {
      return '*Required';
    }
    return null;
  },
  onChanged: (value) {
    name = value; //If it gives some null check error just add an exclamation like this - name = value!;
  }
),

Now you just have to pass these variables in your request just like you use any normal variables. Instead of using nameController.text, just name (variable created in the beginning) is enough. This should make the form work perfectly.

If you are not getting 200 status then the problem could also be the difference between the data you're sending and the data that is expected to receive on the server.

To figure out the root cause, I would recommend you to add Print Statements everywhere to see which functions are running properly and which are not.

Printing the error statements coming from the server might help in understanding the root problem. So try this before returning statusCode

print(response.body); //Add this line for the output from the server
return response.statusCode;

And let me know what reply you get in the console.

不美如何 2025-01-31 05:11:09
Future sendEmail(String name, String email, String message) async {
    final url = Uri.parse('https://api.emailjs.com/api/v1.0/email/send%27);
    const serviceId = 'Enter your service Id';
    const templateId = 'Enter your template Id';
    const userId = 'Enter your User Id';
    final response = await http.post(url,
        headers: {'Content-Type': 'application/json'},//This line makes sure it works for all platforms.
        body: json.encode({
          'service_id': serviceId,
          'template_id': templateId,
          'user_id': userId,
          'template_params': {
            'from_name': name,
            'from_email': email,
            'message': message
          }
        })
    );
    print (response.body);
    return response.statusCode;

  }

您将从MailJS上创建的帐户中获取服务ID,模板ID和用户ID。

Future sendEmail(String name, String email, String message) async {
    final url = Uri.parse('https://api.emailjs.com/api/v1.0/email/send%27);
    const serviceId = 'Enter your service Id';
    const templateId = 'Enter your template Id';
    const userId = 'Enter your User Id';
    final response = await http.post(url,
        headers: {'Content-Type': 'application/json'},//This line makes sure it works for all platforms.
        body: json.encode({
          'service_id': serviceId,
          'template_id': templateId,
          'user_id': userId,
          'template_params': {
            'from_name': name,
            'from_email': email,
            'message': message
          }
        })
    );
    print (response.body);
    return response.statusCode;

  }

You will get Service Id, template Id and User Id from the account that you have created on MailJS.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文