Flutter重发请求插件resend_dart的使用

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

Flutter重发请求插件resend_dart的使用

在本指南中,我们将介绍如何使用resend_dart插件来发送电子邮件。该插件支持多种平台,并提供了简单的API来管理电子邮件发送。

许可证

License: MIT

平台支持

Android iOS MacOS Web Linux Windows

API支持

Api keys Domains Email

安装

要安装resend_dart插件,请执行以下命令:

flutter pub add resend_dart

配置

首先,您需要获取一个API密钥,该密钥可以在Resend仪表板中找到。

示例

以下是一个完整的示例代码,展示了如何使用resend_dart插件发送电子邮件。

import 'package:resend_dart/resend.dart';
import 'package:flutter/material.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:motion_toast/motion_toast.dart';

void main() async {
  await dotenv.load(fileName: '.env');
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) => MaterialApp(
        home: const ExamplePage(),
      );
}

class ExamplePage extends StatefulWidget {
  const ExamplePage({super.key});

  @override
  State<ExamplePage> createState() => _ExamplePageState();
}

class _ExamplePageState extends State<ExamplePage> {
  late final _apiKey = dotenv.env['API_KEY'] as String;
  late final resend = Resend(apiKey: _apiKey);

  var _formState = FormStateModel(
    from: 'onboarding@resend.dev',
  );
  var _attachments = <PlatformFile>[];

  late final _fromController = TextEditingController(text: _formState.from);
  late final _toController = TextEditingController();
  late final _subjectController = TextEditingController();
  late final _textController = TextEditingController();
  late final _htmlController = TextEditingController();
  late final _formKey = GlobalKey<FormState>();

  void _showSuccess() => MotionToast.success(
        title: Text('Success'),
        description: Text('Email successfully sent'),
      ).show(context);

  void _showError(String name, String message) =>
      MotionToast.error(
        title: Text(name),
        description: Text(message),
      ).show(context);

  Future<void> _onSendEmail() async {
    try {
      await resend.email.send(
        from: _formState.from ?? '',
        to: [_formState.to ?? ''],
        subject: _formState.subject ?? '',
        text: (_formState.html?.isNotEmpty ?? false) ? null : _formState.text,
        html: _formState.html,
        attachments: _attachments.isEmpty
            ? null
            : _attachments
                .map(
                  (file) => ResendAttachment(
                    content: file.bytes ?? [],
                    filename: file.name,
                  ),
                )
                .toList(),
      );
      _resetForm();
      _showSuccess();
    } on ResendApiException catch (err) {
      _showError(err.name, '${err.message}');
    }
  }

  Future<void> _onAttachFile() async {
    await Permission.photos.request();
    final result = await FilePicker.platform.pickFiles(allowMultiple: true);
    final files = result?.files;
    if (files != null) {
      setState(() => _attachments.addAll(files));
    }
  }

  void _onRemoveAttachment(PlatformFile file) =>
      setState(() => _attachments.remove(file));

  void _resetForm() {
    setState(
      () {
        _formKey.currentState?.reset();
        _toController.text = '';
        _subjectController.text = '';
        _textController.text = '';
        _htmlController.text = '';
        _formState = FormStateModel(from: _formState.from);
        _attachments.clear();
      },
    );
  }

  @override
  Widget build(BuildContext context) => Scaffold(
        appBar: AppBar(
          title: Text('Resend Dart SDK example'),
          backgroundColor: Colors.black,
          elevation: 0,
        ),
        backgroundColor: Colors.white,
        body: SafeArea(
          child: SingleChildScrollView(
            child: Form(
              key: _formKey,
              child: Padding(
                padding: EdgeInsets.symmetric(horizontal: 16),
                child: Column(
                  mainAxisSize: MainAxisSize.max,
                  children: [
                    TextInput(
                      controller: _fromController,
                      onInputChanged: (text) {
                        setState(
                            () => _formState = _formState.copyWith(from: text));
                      },
                      hint: 'From',
                    ),
                    TextInput(
                      controller: _toController,
                      onInputChanged: (text) {
                        setState(
                            () => _formState = _formState.copyWith(to: text));
                      },
                      hint: 'To',
                    ),
                    TextInput(
                      controller: _subjectController,
                      onInputChanged: (text) {
                        setState(() =>
                            _formState = _formState.copyWith(subject: text));
                      },
                      hint: 'Subject',
                    ),
                    TextInput(
                      controller: _textController,
                      onInputChanged: (text) {
                        setState(
                            () => _formState = _formState.copyWith(text: text));
                      },
                      hint: 'Message',
                    ),
                    TextInput(
                      controller: _htmlController,
                      onInputChanged: (text) => setState(() =>
                          _formState = _formState.copyWith(
                              html: text.isEmpty ? null : text)),
                      hint: 'html',
                    ),
                    FormAttachments(
                      attachments: _attachments,
                      onRemoveAttachment: _onRemoveAttachment,
                    ),
                    FormActions(
                      onSendEmail: _onSendEmail,
                      onAttachFile: _onAttachFile,
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      );
}

说明

  1. 导入必要的库

    import 'package:resend_dart/resend.dart';
    import 'package:flutter/material.dart';
    import 'package:flutter_dotenv/flutter_dotenv.dart';
    import 'package:motion_toast/motion_toast.dart';
    
  2. 加载环境变量

    void main() async {
      await dotenv.load(fileName: '.env');
      runApp(const MyApp());
    }
    
  3. 初始化插件

    class _ExamplePageState extends State<ExamplePage> {
      late final _apiKey = dotenv.env['API_KEY'] as String;
      late final resend = Resend(apiKey: _apiKey);
    
  4. 定义表单状态

    var _formState = FormStateModel(
      from: 'onboarding@resend.dev',
    );
    
  5. 定义控制器

    late final _fromController = TextEditingController(text: _formState.from);
    late final _toController = TextEditingController();
    late final _subjectController = TextEditingController();
    late final _textController = TextEditingController();
    late final _htmlController = TextEditingController();
    late final _formKey = GlobalKey<FormState>();
    
  6. 处理成功和错误信息

    void _showSuccess() => MotionToast.success(
          title: Text('Success'),
          description: Text('Email successfully sent'),
        ).show(context);
    
    void _showError(String name, String message) =>
        MotionToast.error(
          title: Text(name),
          description: Text(message),
        ).show(context);
    
  7. 发送电子邮件

    Future<void> _onSendEmail() async {
      try {
        await resend.email.send(
          from: _formState.from ?? '',
          to: [_formState.to ?? ''],
          subject: _formState.subject ?? '',
          text: (_formState.html?.isNotEmpty ?? false) ? null : _formState.text,
          html: _formState.html,
          attachments: _attachments.isEmpty
              ? null
              : _attachments
                  .map(
                    (file) => ResendAttachment(
                      content: file.bytes ?? [],
                      filename: file.name,
                    ),
                  )
                  .toList(),
        );
        _resetForm();
        _showSuccess();
      } on ResendApiException catch (err) {
        _showError(err.name, '${err.message}');
      }
    }
    
  8. 附件处理

    Future<void> _onAttachFile() async {
      await Permission.photos.request();
      final result = await FilePicker.platform.pickFiles(allowMultiple: true);
      final files = result?.files;
      if (files != null) {
        setState(() => _attachments.addAll(files));
      }
    }
    
  9. 移除附件

    void _onRemoveAttachment(PlatformFile file) =>
        setState(() => _attachments.remove(file));
    
  10. 重置表单

    void _resetForm() {
      setState(
        () {
          _formKey.currentState?.reset();
          _toController.text = '';
          _subjectController.text = '';
          _textController.text = '';
          _htmlController.text = '';
          _formState = FormStateModel(from: _formState.from);
          _attachments.clear();
        },
      );
    }
    

更多关于Flutter重发请求插件resend_dart的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter重发请求插件resend_dart的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何在Flutter项目中使用resend_dart插件来实现请求重发的示例代码。resend_dart插件可以帮助你在网络请求失败时自动或手动重发请求。

首先,确保你已经在pubspec.yaml文件中添加了resend_dart依赖:

dependencies:
  flutter:
    sdk: flutter
  resend_dart: ^最新版本号  # 请替换为最新的版本号

然后运行flutter pub get来安装依赖。

接下来,我们可以创建一个简单的示例来展示如何使用resend_dart。在这个示例中,我们将模拟一个网络请求,并在请求失败时自动重发。

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Resend Dart Example'),
        ),
        body: Center(
          child: ResendRequestExample(),
        ),
      ),
    );
  }
}

class ResendRequestExample extends StatefulWidget {
  @override
  _ResendRequestExampleState createState() => _ResendRequestExampleState();
}

class _ResendRequestExampleState extends State<ResendRequestExample> {
  final ResendController resendController = ResendController();
  String responseData = '';

  @override
  void initState() {
    super.initState();
    // 发起网络请求
    makeRequest();
  }

  void makeRequest() async {
    resendController.resend(
      () async {
        try {
          final response = await http.get(Uri.parse('https://api.example.com/data'));
          if (response.statusCode == 200) {
            setState(() {
              responseData = jsonDecode(response.body)['message'];
            });
            resendController.stop(); // 请求成功,停止重发
          } else {
            throw Exception('Request failed with status code: ${response.statusCode}');
          }
        } catch (e) {
          throw e; // 请求失败,抛出异常以触发重发
        }
      },
      retries: 3, // 最大重发次数
      retryDelay: Duration(seconds: 2), // 每次重发之间的延迟时间
      onError: (error, stackTrace) {
        // 请求重发失败后的处理
        print('Final error: $error');
        setState(() {
          responseData = 'Error: $error';
        });
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Text(
          'Response Data:',
          style: TextStyle(fontSize: 20),
        ),
        SizedBox(height: 10),
        Text(
          responseData,
          style: TextStyle(fontSize: 18),
        ),
      ],
    );
  }

  @override
  void dispose() {
    resendController.dispose(); // 释放资源
    super.dispose();
  }
}

在这个示例中,我们创建了一个ResendRequestExample组件,并在initState方法中调用makeRequest方法来发起网络请求。resendController.resend方法接受一个函数作为参数,这个函数内包含实际的网络请求逻辑。如果请求失败,resendController会自动按照设定的重发策略(最大重发次数和重发间隔)进行重发。如果所有重发尝试都失败了,onError回调会被调用。

注意:

  1. 在实际使用中,请替换https://api.example.com/data为你的实际API端点。
  2. 确保处理网络请求的异常,以便在请求失败时能够触发重发机制。
  3. 在组件销毁时,调用resendController.dispose()来释放资源。
回到顶部