Flutter异步操作按钮插件async_button的使用

Flutter异步操作按钮插件async_button的使用

什么是这个插件?

这个项目提供了与你常用的按钮类似的组件,但增加了对异步操作的支持。你可以根据onTap函数的状态(空闲、加载中或加载完成)来控制按钮的状态。

Async Button

如何使用它?

这个项目提供了三种类型的按钮。让我们通过示例来看看如何使用它们。

AsyncElevatedBtn

AsyncElevatedBtn 类似于 ElevatedButton,但用于异步操作的 onPressed

AsyncBtnStatesController btnStateController = AsyncBtnStatesController();

AsyncElevatedBtn(
  asyncBtnStatesController: btnStateController,
  onPressed: () async {
    btnStateController.update(AsyncBtnState.loading);
    try {
      // 等待你的API调用或其他异步操作
      await Future.delayed(const Duration(seconds: 2));
      btnStateController.update(AsyncBtnState.success);
    } catch (e) {
      btnStateController.update(AsyncBtnState.failure);
    }
  },
  loadingStyle: AsyncBtnStateStyle(
    style: ElevatedButton.styleFrom(
      backgroundColor: Colors.amber,
    ),
    widget: const SizedBox.square(
      dimension: 24,
      child: CircularProgressIndicator(
        color: Colors.white,
      ),
    ),
  ),
  successStyle: AsyncBtnStateStyle(
    style: ElevatedButton.styleFrom(
      backgroundColor: Colors.green,
      foregroundColor: Colors.white,
    ),
    widget: Row(
      mainAxisSize: MainAxisSize.min,
      children: const [
        Icon(Icons.check),
        SizedBox(width: 4),
        Text('Success!')
      ],
    ),
  ),
  failureStyle: AsyncBtnStateStyle(
    style: ElevatedButton.styleFrom(
      backgroundColor: Colors.red,
      foregroundColor: Colors.white,
    ),
    widget: Row(
      mainAxisSize: MainAxisSize.min,
      children: const [
        Icon(Icons.error),
        SizedBox(width: 4),
        Text('Error!')
      ],
    ),
  ),
  child: const Text('Execute'),
);

如果你不想定义 loadingStyle, successStyle, 和 failureStyle,也可以使用默认样式:

AsyncBtnStatesController btnStateController = AsyncBtnStatesController();

AsyncElevatedBtn.withDefaultStyles(
  asyncBtnStatesController: btnStateController,
  onPressed: () async {
    btnStateController.update(AsyncBtnState.loading);
    try {
      // 等待你的API调用或其他异步操作
      await Future.delayed(const Duration(seconds: 2));
      btnStateController.update(AsyncBtnState.success);
    } catch (e) {
      btnStateController.update(AsyncBtnState.failure);
    }
  },
  child: const Text('Execute'),
);

AsyncTextBtn

AsyncTextBtn 是我们版本的异步 TextButton

AsyncBtnStatesController btnStateController = AsyncBtnStatesController();

AsyncTextBtn(
  asyncBtnStatesController: btnStateController,
  onPressed: () async {
    btnStateController.update(AsyncBtnState.loading);
    try {
      // 等待你的API调用或其他异步操作
      await Future.delayed(const Duration(seconds: 2));
      btnStateController.update(AsyncBtnState.success);
    } catch (e) {
      btnStateController.update(AsyncBtnState.failure);
    }
  },
  loadingStyle: AsyncBtnStateStyle(
    style: TextButton.styleFrom(
      foregroundColor: Colors.amber,
    ),
    widget: const SizedBox.square(
      dimension: 24,
      child: CircularProgressIndicator(
        color: Colors.amber,
      ),
    ),
  ),
  successStyle: AsyncBtnStateStyle(
    style: TextButton.styleFrom(
      foregroundColor: Colors.green,
    ),
    widget: Row(
      mainAxisSize: MainAxisSize.min,
      children: const [
        Icon(Icons.check),
        SizedBox(width: 4),
        Text('Success!')
      ],
    ),
  ),
  failureStyle: AsyncBtnStateStyle(
    style: TextButton.styleFrom(
      foregroundColor: Colors.red,
    ),
    widget: Row(
      mainAxisSize: MainAxisSize.min,
      children: const [
        Icon(Icons.error),
        SizedBox(width: 4),
        Text('Error!')
      ],
    ),
  ),
  child: const Text('Execute'),
);

同样地,你可以使用默认样式的构造器:

AsyncBtnStatesController btnStateController = AsyncBtnStatesController();

AsyncTextBtn.withDefaultStyles(
  asyncBtnStatesController: btnStateController,
  onPressed: () async {
    btnStateController.update(AsyncBtnState.loading);
    try {
      // 等待你的API调用或其他异步操作
      await Future.delayed(const Duration(seconds: 2));
      btnStateController.update(AsyncBtnState.success);
    } catch (e) {
      btnStateController.update(AsyncBtnState.failure);
    }
  },
  child: const Text('Execute'),
);

AsyncOutlinedBtn

AsyncOutlinedBtn 类似于 OutlinedButton,但用于异步操作的 onPressed

AsyncBtnStatesController btnStateController = AsyncBtnStatesController();

AsyncOutlinedBtn(
  asyncBtnStatesController: btnStateController,
  onPressed: () async {
    btnStateController.update(AsyncBtnState.loading);
    try {
      // 等待你的API调用或其他异步操作
      await Future.delayed(const Duration(seconds: 2));
      btnStateController.update(AsyncBtnState.success);
    } catch (e) {
      btnStateController.update(AsyncBtnState.failure);
    }
  },
  loadingStyle: AsyncBtnStateStyle(
    style: OutlinedButton.styleFrom(
      foregroundColor: Colors.amber,
    ),
    widget: const SizedBox.square(
      dimension: 24,
      child: CircularProgressIndicator(
        color: Colors.amber,
      ),
    ),
  ),
  successStyle: AsyncBtnStateStyle(
    style: OutlinedButton.styleFrom(
      foregroundColor: Colors.green,
    ),
    widget: Row(
      mainAxisSize: MainAxisSize.min,
      children: const [
        Icon(Icons.check),
        SizedBox(width: 4),
        Text('Success!')
      ],
    ),
  ),
  failureStyle: AsyncBtnStateStyle(
    style: OutlinedButton.styleFrom(
      foregroundColor: Colors.red,
    ),
    widget: Row(
      mainAxisSize: MainAxisSize.min,
      children: const [
        Icon(Icons.error),
        SizedBox(width: 4),
        Text('Error!')
      ],
    ),
  ),
  child: const Text('Execute'),
);

你也可以使用默认样式的构造器:

AsyncBtnStatesController btnStateController = AsyncBtnStatesController();

AsyncOutlinedBtn.withDefaultStyles(
  asyncBtnStatesController: btnStateController,
  onPressed: () async {
    btnStateController.update(AsyncBtnState.loading);
    try {
      // 等待你的API调用或其他异步操作
      await Future.delayed(const Duration(seconds: 2));
      btnStateController.update(AsyncBtnState.success);
    } catch (e) {
      btnStateController.update(AsyncBtnState.failure);
    }
  },
  child: const Text('Execute'),
);

更多关于Flutter异步操作按钮插件async_button的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter异步操作按钮插件async_button的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter中使用async_button插件的一个代码示例。async_button插件允许你在按钮点击时执行异步操作,并在操作进行期间显示加载状态。

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

dependencies:
  flutter:
    sdk: flutter
  async_button: ^x.y.z  # 替换为最新版本号

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

接下来,你可以在你的Flutter应用中这样使用AsyncButton

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

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

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

class AsyncButtonWidget extends StatelessWidget {
  Future<void> _handleButtonClick() async {
    // 模拟一个耗时操作,比如网络请求
    await Future.delayed(Duration(seconds: 3));
    // 操作完成后可以显示一个Snackbar或者做其他处理
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text('操作完成!')),
    );
  }

  @override
  Widget build(BuildContext context) {
    return AsyncButton<void>(
      onPressed: _handleButtonClick,
      loadingText: '加载中...',
      child: Text('点击我'),
    );
  }
}

在这个示例中:

  1. AsyncButtonasync_button插件提供的按钮组件。
  2. onPressed参数是一个异步函数,当按钮被点击时会调用这个函数。
  3. loadingText参数是在异步操作进行期间显示的文本。
  4. child参数是按钮的常规显示内容。

当用户点击按钮时,按钮的文本会从“点击我”变为“加载中…”,并在异步操作(这里是模拟的3秒延迟)完成后恢复为“点击我”,同时显示一个Snackbar提示操作完成。

你可以根据实际需求调整onPressed函数中的逻辑,以及loadingTextchild的内容。

回到顶部