Flutter邮件检查功能插件mail_check的使用

发布于 1周前 作者 ionicwang 来自 Flutter

Flutter邮件检查功能插件 mail_check 的使用

mail_check 是一个用于 Flutter 的包,支持 Android、iOS 和 Web。它提供了验证电子邮件地址并给出建议的功能。

截图

邮件建议

使用方法

添加依赖

首先,在你的 pubspec.yaml 文件中添加 mail_check 依赖:

dependencies:
  flutter:
    sdk: flutter
  mail_check:

如何使用

以下是一个完整的示例代码,展示了如何在 Flutter 应用中使用 mail_check 插件来验证电子邮件地址并获取建议:

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

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'MailCheck Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      debugShowCheckedModeBanner: false,
      home: const MyHomePage(title: 'MailCheck Example'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  TextEditingController controller = TextEditingController();
  String _message = "";

  @override
  void initState() {
    super.initState();
    MailCheck.shared.initial();
  }

  void _checkEmail() {
    var email = controller.value.text;
    MailCheck.shared.run(email,
        customRegex:
            r"^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$",
        customDomains: ["yopmail.com"], callBack: (response) {
      var message = "this email is a valid email";
      if (response.isValidEmail) {
        if (response.suggestion != null) {
          message =
              "Are you sure with email: $email\nSuggestion: ${response.suggestion?.fullEmail}\nsuggestion Type: ${response.suggestion?.suggestionType}";
        }
      } else {
        message = "this email is an invalid email";
      }
      setState(() {
        _message = message;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 20),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              const SizedBox(
                height: 50,
              ),
              Container(
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(16),
                ),
                child: TextField(
                  controller: controller,
                  decoration: const InputDecoration(
                    hintStyle: TextStyle(fontSize: 17),
                    hintText: 'Email',
                    prefixIcon: Icon(Icons.email),
                    border: InputBorder.none,
                    contentPadding: EdgeInsets.all(20),
                  ),
                ),
              ),
              const SizedBox(
                height: 10,
              ),
              TextButton(
                onPressed: () {
                  _checkEmail();
                },
                child: const Text('Tap to check'),
              ),
              const SizedBox(
                height: 10,
              ),
              Text(
                _message,
              ),
            ],
          ),
        ),
      ),
    );
  }
}

支持的默认域名列表

许可证

版权所有 © 2023 HiepLe

许可协议为 MIT 许可证,具体内容如下:

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

入门指南

如果你刚开始使用 Flutter,可以查看我们的 在线文档

如果你需要编辑包代码,可以查看 开发包文档


更多关于Flutter邮件检查功能插件mail_check的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter邮件检查功能插件mail_check的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用mail_check插件来检查邮件的一个示例。请注意,mail_check插件可能并非一个真实存在的插件,因为Flutter的官方插件集合中并没有直接名为mail_check的插件。然而,我们可以模拟一个类似的功能,通过调用邮件服务提供商的API来检查邮件。

为了说明这一点,我将使用一个假设的邮件检查API,并通过HTTP请求来实现邮件检查功能。我们将使用http包来发送请求,并假设有一个邮件服务提供商提供了一个简单的API来检查指定邮箱是否有新邮件。

首先,确保在pubspec.yaml文件中添加http依赖:

dependencies:
  flutter:
    sdk: flutter
  http: ^0.13.3 # 请检查最新版本号并更新

然后,运行flutter pub get来获取依赖。

接下来,我们创建一个Flutter应用,并在其中实现邮件检查功能。以下是一个简化的示例:

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Mail Check Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MailCheckScreen(),
    );
  }
}

class MailCheckScreen extends StatefulWidget {
  @override
  _MailCheckScreenState createState() => _MailCheckScreenState();
}

class _MailCheckScreenState extends State<MailCheckScreen> {
  String _email = '';
  String _result = '';

  void _checkMail() async {
    setState(() {
      _result = 'Checking...';
    });

    String email = _email.trim();
    if (email.isEmpty) {
      setState(() {
        _result = 'Please enter an email address.';
      });
      return;
    }

    // 假设有一个邮件检查API的URL,例如:https://api.example.com/check-mail?email=<email>
    String apiUrl = 'https://api.example.com/check-mail?email=$email';

    try {
      http.Response response = await http.get(Uri.parse(apiUrl));
      Map<String, dynamic> data = jsonDecode(response.body);

      if (response.statusCode == 200) {
        setState(() {
          _result = data['hasNewMail'] ? 'You have new mail!' : 'No new mail.';
        });
      } else {
        setState(() {
          _result = 'Failed to check mail: ${data['message'] ?? 'Unknown error'}';
        });
      }
    } catch (e) {
      setState(() {
        _result = 'Error: $e';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Mail Check Demo'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            TextField(
              decoration: InputDecoration(labelText: 'Email'),
              onChanged: (value) {
                setState(() {
                  _email = value;
                });
              },
            ),
            SizedBox(height: 16),
            ElevatedButton(
              onPressed: _checkMail,
              child: Text('Check Mail'),
            ),
            SizedBox(height: 16),
            Text(
              _result,
              style: TextStyle(fontSize: 18),
            ),
          ],
        ),
      ),
    );
  }
}

在这个示例中,我们创建了一个简单的Flutter应用,用户可以在其中输入邮箱地址并点击按钮来检查是否有新邮件。我们假设了一个邮件检查API的URL,并通过HTTP GET请求来访问它。根据API的响应,我们更新UI以显示结果。

请注意,由于mail_check插件可能不存在,上述代码使用了http包来模拟邮件检查功能。如果你找到一个真实的邮件检查插件,请查阅其文档并按照其使用说明进行集成。

回到顶部