Flutter进度状态按钮插件progress_state_button的使用

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

Flutter进度状态按钮插件progress_state_button的使用

progress_state_button 是一个用于Flutter的高度可定制的进度按钮插件。它允许开发者轻松地创建具有不同状态(如闲置、加载、失败和成功)的按钮。

安装

pubspec.yaml 文件中添加以下依赖项:

dependencies:
  progress_state_button: "^1.0.4"

然后运行 flutter pub get 来安装该插件。

使用示例

带图标按钮

下面是一个带有图标的进度按钮示例:

ProgressButton.icon(
  iconedButtons: {
    ButtonState.idle: IconedButton(
        text: "Send",
        icon: Icon(Icons.send, color: Colors.white),
        color: Colors.deepPurple.shade500),
    ButtonState.loading: IconedButton(
        text: "Loading",
        color: Colors.deepPurple.shade700),
    ButtonState.fail: IconedButton(
        text: "Failed",
        icon: Icon(Icons.cancel, color: Colors.white),
        color: Colors.red.shade300),
    ButtonState.success: IconedButton(
        text: "Success",
        icon: Icon(Icons.check_circle, color: Colors.white),
        color: Colors.green.shade400)
  },
  onPressed: onPressed,
  state: ButtonState.idle,
);

自定义部件按钮

下面是一个使用自定义部件的进度按钮示例:

ProgressButton(
  stateWidgets: {
    ButtonState.idle: Text("Idle", style: TextStyle(color: Colors.white, fontWeight: FontWeight.w500)),
    ButtonState.loading: Text("Loading", style: TextStyle(color: Colors.white, fontWeight: FontWeight.w500)),
    ButtonState.fail: Text("Fail", style: TextStyle(color: Colors.white, fontWeight: FontWeight.w500)),
    ButtonState.success: Text("Success", style: TextStyle(color: Colors.white, fontWeight: FontWeight.w500))
  },
  stateColors: {
    ButtonState.idle: Colors.grey.shade400,
    ButtonState.loading: Colors.blue.shade300,
    ButtonState.fail: Colors.red.shade300,
    ButtonState.success: Colors.green.shade400,
  },
  onPressed: onPressed,
  state: ButtonState.idle,
);

示例Demo

以下是一个完整的Flutter应用示例,展示了如何使用 progress_state_button 插件:

import 'dart:async';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:progress_state_button/iconed_button.dart';
import 'package:progress_state_button/progress_button.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Progress Button',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: ProgressButtonHomePage(title: 'Progress Button'),
    );
  }
}

class ProgressButtonHomePage extends StatefulWidget {
  ProgressButtonHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _ProgressButtonHomePageState createState() => _ProgressButtonHomePageState();
}

class _ProgressButtonHomePageState extends State<ProgressButtonHomePage> {
  ButtonState stateOnlyText = ButtonState.idle;
  ButtonState stateOnlyCustomIndicatorText = ButtonState.idle;
  ButtonState stateTextWithIcon = ButtonState.idle;
  ButtonState stateTextWithIconMinWidthState = ButtonState.idle;

  Widget buildCustomButton() {
    var progressTextButton = ProgressButton(
      stateWidgets: {
        ButtonState.idle: Text(
          "Idle",
          style: TextStyle(color: Colors.white, fontWeight: FontWeight.w500),
        ),
        ButtonState.loading: Text(
          "Loading",
          style: TextStyle(color: Colors.white, fontWeight: FontWeight.w500),
        ),
        ButtonState.fail: Text(
          "Fail",
          style: TextStyle(color: Colors.white, fontWeight: FontWeight.w500),
        ),
        ButtonState.success: Text(
          "Success",
          style: TextStyle(color: Colors.white, fontWeight: FontWeight.w500),
        )
      },
      stateColors: {
        ButtonState.idle: Colors.grey.shade400,
        ButtonState.loading: Colors.blue.shade300,
        ButtonState.fail: Colors.red.shade300,
        ButtonState.success: Colors.green.shade400,
      },
      onPressed: onPressedCustomButton,
      state: stateOnlyText,
      padding: EdgeInsets.all(8.0),
    );
    return progressTextButton;
  }

  Widget buildCustomProgressIndicatorButton() {
    var progressTextButton = ProgressButton(
      stateWidgets: {
        ButtonState.idle: Text(
          "Idle",
          style: TextStyle(color: Colors.white, fontWeight: FontWeight.w500),
        ),
        ButtonState.loading: Text(
          "Loading",
          style: TextStyle(color: Colors.white, fontWeight: FontWeight.w500),
        ),
        ButtonState.fail: Text(
          "Fail",
          style: TextStyle(color: Colors.white, fontWeight: FontWeight.w500),
        ),
        ButtonState.success: Text(
          "Success",
          style: TextStyle(color: Colors.white, fontWeight: FontWeight.w500),
        )
      },
      progressIndicator: CircularProgressIndicator(
        backgroundColor: Colors.white,
        valueColor: AlwaysStoppedAnimation(Colors.red),
        strokeWidth: 1,
      ),
      stateColors: {
        ButtonState.idle: Colors.grey.shade400,
        ButtonState.loading: Colors.blue.shade300,
        ButtonState.fail: Colors.red.shade300,
        ButtonState.success: Colors.green.shade400,
      },
      onPressed: onPressedCustomIndicatorButton,
      state: stateOnlyCustomIndicatorText,
      padding: EdgeInsets.all(8.0),
    );
    return progressTextButton;
  }

  Widget buildTextWithIcon() {
    return ProgressButton.icon(
      iconedButtons: {
        ButtonState.idle: IconedButton(
            text: "Send",
            icon: Icon(Icons.send, color: Colors.white),
            color: Colors.deepPurple.shade500),
        ButtonState.loading: IconedButton(text: "Loading", color: Colors.deepPurple.shade700),
        ButtonState.fail: IconedButton(
            text: "Failed",
            icon: Icon(Icons.cancel, color: Colors.white),
            color: Colors.red.shade300),
        ButtonState.success: IconedButton(
            text: "",
            icon: Icon(Icons.check_circle, color: Colors.white),
            color: Colors.green.shade400)
      },
      onPressed: onPressedIconWithText,
      state: stateTextWithIcon,
    );
  }

  Widget buildTextWithIconWithMinState() {
    return ProgressButton.icon(
      iconedButtons: {
        ButtonState.idle: IconedButton(
            text: "Send",
            icon: Icon(Icons.send, color: Colors.white),
            color: Colors.deepPurple.shade500),
        ButtonState.loading: IconedButton(text: "Loading", color: Colors.deepPurple.shade700),
        ButtonState.fail: IconedButton(
            text: "Failed",
            icon: Icon(Icons.cancel, color: Colors.white),
            color: Colors.red.shade300),
        ButtonState.success: IconedButton(
            icon: Icon(Icons.check_circle, color: Colors.white),
            color: Colors.green.shade400)
      },
      onPressed: onPressedIconWithMinWidthStateText,
      state: stateTextWithIconMinWidthState,
      minWidthStates: [ButtonState.loading, ButtonState.success],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            buildCustomButton(),
            Container(height: 32),
            buildTextWithIcon(),
            Container(height: 32),
            buildTextWithIconWithMinState(),
            Container(height: 32),
            buildCustomProgressIndicatorButton()
          ],
        ),
      ),
    );
  }

  void onPressedCustomButton() {
    setState(() {
      switch (stateOnlyText) {
        case ButtonState.idle:
          stateOnlyText = ButtonState.loading;
          break;
        case ButtonState.loading:
          stateOnlyText = ButtonState.fail;
          break;
        case ButtonState.success:
          stateOnlyText = ButtonState.idle;
          break;
        case ButtonState.fail:
          stateOnlyText = ButtonState.success;
          break;
      }
    });
  }

  void onPressedCustomIndicatorButton() {
    setState(() {
      switch (stateOnlyCustomIndicatorText) {
        case ButtonState.idle:
          stateOnlyCustomIndicatorText = ButtonState.loading;
          break;
        case ButtonState.loading:
          stateOnlyCustomIndicatorText = ButtonState.fail;
          break;
        case ButtonState.success:
          stateOnlyCustomIndicatorText = ButtonState.idle;
          break;
        case ButtonState.fail:
          stateOnlyCustomIndicatorText = ButtonState.success;
          break;
      }
    });
  }

  void onPressedIconWithText() async {
    switch (stateTextWithIcon) {
      case ButtonState.idle:
        stateTextWithIcon = ButtonState.loading;
        Future.delayed(Duration(seconds: 1), () {
          setState(() {
            stateTextWithIcon = Random.secure().nextBool() ? ButtonState.success : ButtonState.fail;
          });
        });
        break;
      case ButtonState.loading:
        break;
      case ButtonState.success:
        stateTextWithIcon = ButtonState.idle;
        break;
      case ButtonState.fail:
        stateTextWithIcon = ButtonState.idle;
        break;
    }
    setState(() {
      stateTextWithIcon = stateTextWithIcon;
    });
  }

  void onPressedIconWithMinWidthStateText() {
    switch (stateTextWithIconMinWidthState) {
      case ButtonState.idle:
        stateTextWithIconMinWidthState = ButtonState.loading;
        Future.delayed(Duration(seconds: 1), () {
          setState(() {
            stateTextWithIconMinWidthState = Random.secure().nextBool() ? ButtonState.success : ButtonState.fail;
          });
        });
        break;
      case ButtonState.loading:
        break;
      case ButtonState.success:
        stateTextWithIconMinWidthState = ButtonState.idle;
        break;
      case ButtonState.fail:
        stateTextWithIconMinWidthState = ButtonState.idle;
        break;
    }
    setState(() {
      stateTextWithIconMinWidthState = stateTextWithIconMinWidthState;
    });
  }
}

这个示例展示了如何在Flutter应用中使用 progress_state_button 插件来创建不同的进度状态按钮。您可以根据需要自定义按钮的状态和样式。


更多关于Flutter进度状态按钮插件progress_state_button的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter进度状态按钮插件progress_state_button的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用progress_state_button插件的一个详细代码示例。这个插件允许你创建一个带有进度状态的按钮,非常适合用于加载、成功、错误等状态的显示。

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

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

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

接下来,在你的Flutter项目中,你可以按如下方式使用ProgressStateButton

import 'package:flutter/material.dart';
import 'package:progress_state_button/iconed_button.dart';
import 'package:progress_state_button/progress_button.dart';

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

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

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool isLoading = false;
  ProgressButtonController? controller;

  @override
  void initState() {
    super.initState();
    controller = ProgressButtonController();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        ProgressButton.defaultButton(
          controller: controller!,
          onPressed: () async {
            setState(() {
              isLoading = true;
            });

            // Simulate a network request or other async task
            await Future.delayed(Duration(seconds: 2));

            // After the async task is completed
            controller!.transitionToSuccess();

            // Optionally reset the button state after a delay
            Future.delayed(Duration(seconds: 2), () {
              controller!.reset();
              setState(() {
                isLoading = false;
              });
            });
          },
          child: Text('Click Me'),
        ),
        SizedBox(height: 20),
        Text('Is Loading: $isLoading'),
      ],
    );
  }

  @override
  void dispose() {
    controller?.dispose();
    super.dispose();
  }
}

解释

  1. 依赖导入

    • package:flutter/material.dart:Flutter的基础Material Design组件。
    • package:progress_state_button/iconed_button.dartpackage:progress_state_button/progress_button.dartprogress_state_button插件的核心组件。
  2. 应用入口

    • MyApp类定义了一个基本的Flutter应用,包含一个ScaffoldAppBar
  3. 主页面

    • MyHomePage是一个StatefulWidget,它包含一个ProgressButton
    • initState方法中初始化ProgressButtonController
    • build方法中定义了ProgressButton,并绑定了一个onPressed回调,模拟了一个异步任务(例如网络请求)。
    • 使用setState来更新isLoading状态,以便在页面上显示按钮的加载状态。
    • 异步任务完成后,调用controller!.transitionToSuccess()将按钮状态改为成功。
    • 使用Future.delayed在2秒后重置按钮状态。
  4. 资源释放

    • dispose方法中调用controller?.dispose()来释放资源。

这个示例展示了如何使用progress_state_button插件来创建一个具有加载、成功状态的按钮,并处理按钮状态的更新。你可以根据实际需求进一步定制按钮的样式和行为。

回到顶部