Flutter加载按钮样式插件material_loading_buttons的使用

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

Flutter加载按钮样式插件material_loading_buttons的使用

简介

material_loading_buttons 是一个基于 Flutter Material Design 按钮实现的简单加载按钮插件。它提供了多种类型的加载按钮,包括 ElevatedButtonFilledButtonFilledTonalButtonOutlinedButtonTextButton,并且支持自动和手动管理加载状态。

特点

  • 实现了 ElevatedButtonFilledButtonFilledTonalButtonOutlinedButtonTextButton 的加载版本。
  • 加载状态可以被控制。
  • 可以自定义加载图标和标签。
  • 支持自动加载状态管理。
  • 不添加额外的样式。

开始使用

添加依赖

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

dependencies:
  material_loading_buttons: ^1.1.0

使用示例

自动管理状态

ElevatedAutoLoadingButton(
  onPressed: () async {
    // 模拟加载操作
    await Future.delayed(Duration(seconds: 3));
  },
  child: const Text('ElevatedAutoLoadingButton'),
);

手动管理状态

bool _isLoading = false;

ElevatedLoadingButton(
  isLoading: _isLoading,
  onPressed: () async {
    setState(() {
      _isLoading = true;
    });

    // 模拟加载操作
    await Future.delayed(Duration(seconds: 3));

    setState(() {
      _isLoading = false;
    });
  },
  child: const Text('ElevatedLoadingButton'),
);

自定义样式

ElevatedAutoLoadingButton(
  style: ElevatedButton.styleFrom(), // 原始样式
  loadingIcon: const SizedBox(
    width: 24,
    height: 24,
    child: CircularProgressIndicator(color: Colors.red),
  ),
  loadingLabel: Text('loading...', style: TextStyle(color: Colors.red)),
  onPressed: () async {},
  child: const Text('ElevatedAutoLoadingButton'),
);

完整示例

以下是一个完整的示例,展示了如何在 Flutter 应用中使用 material_loading_buttons 插件。

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:material_loading_buttons/material_loading_buttons.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Material loading buttons',
      theme: ThemeData(
        useMaterial3: true,
        colorSchemeSeed: Colors.blue,
      ),
      home: const MyHomePage(title: 'Material loading buttons'),
    );
  }
}

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

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  Future<void> _onPressed() async {
    await Future.delayed(const Duration(seconds: 3));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(widget.title)),
      body: Center(
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                ElevatedAutoLoadingButton(
                  onPressed: _onPressed,
                  child: const Text('ElevatedLoadingButton'),
                ),
                const SizedBox(height: 16),
                FilledAutoLoadingButton(
                  onPressed: _onPressed,
                  loadingLabel: const Text('loading...'),
                  child: const Text('FilledLoadingButton'),
                ),
                const SizedBox(height: 16),
                FilledAutoLoadingButton.tonal(
                  onPressed: _onPressed,
                  loadingIcon: const SizedBox(
                    width: 24,
                    height: 24,
                    child: CircularProgressIndicator(color: Colors.red),
                  ),
                  child: const Text('ElevatedLoadingButton tonal'),
                ),
                const SizedBox(height: 16),
                OutlinedAutoLoadingButton(
                  onPressed: _onPressed,
                  loadingIcon: const SizedBox(
                    width: 24,
                    height: 24,
                    child: CircularProgressIndicator(color: Colors.green),
                  ),
                  loadingLabel: const Text('loading...'),
                  child: const Text('OutlinedLoadingButton'),
                ),
                const SizedBox(height: 16),
                TextAutoLoadingButton(
                  onPressed: _onPressed,
                  child: const Text('TextLoadingButton'),
                ),
              ],
            ),
            const SizedBox(width: 16),
            Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                ElevatedAutoLoadingButton.icon(
                  onPressed: _onPressed,
                  icon: const Icon(Icons.add),
                  label: const Text('ElevatedLoadingButton Icon'),
                ),
                const SizedBox(height: 16),
                FilledAutoLoadingButton.icon(
                  onPressed: _onPressed,
                  loadingLabel: const Text('loading...'),
                  icon: const Icon(Icons.add),
                  label: const Text('FilledLoadingButton Icon'),
                ),
                const SizedBox(height: 16),
                FilledAutoLoadingButton.tonalIcon(
                  onPressed: _onPressed,
                  loadingIcon: const SizedBox(
                    width: 24,
                    height: 24,
                    child: CircularProgressIndicator(color: Colors.red),
                  ),
                  loadingLabel: const Text('loading...'),
                  icon: const Icon(Icons.add),
                  label: const Text('FilledLoadingButton tonal Icon'),
                ),
                const SizedBox(height: 16),
                const ManualOutlinedLoadingButton(),
                const SizedBox(height: 16),
                const BackgroundTextAutoLoadingButton(),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

/// 手动控制loading状态
class ManualOutlinedLoadingButton extends StatefulWidget {
  const ManualOutlinedLoadingButton({super.key});

  @override
  State<ManualOutlinedLoadingButton> createState() => _ManualOutlinedLoadingButtonState();
}

class _ManualOutlinedLoadingButtonState extends State<ManualOutlinedLoadingButton> {
  Stream<double>? _progress;
  bool _isLoading = false;

  void _onPressed() {
    if (_isLoading) {
      return;
    }

    setState(() {
      _isLoading = true;
      // 模拟5秒的可指示进度的耗时操作
      _progress = Stream.periodic(
              const Duration(milliseconds: 50), (count) => count * 50 / 3000)
          .takeWhileInclusive((e) => e <= 1)
          .doOnDone(() {
        setState(() {
          _isLoading = false;
          _progress = null;
        });
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    final color = Theme.of(context).colorScheme.primary;
    return OutlinedLoadingButton.icon(
      isLoading: _isLoading,
      loadingIcon: SizedBox(
        width: 24,
        height: 24,
        child: StreamBuilder<double>(
          initialData: 0,
          stream: _progress,
          builder: (context, snapshot) => CircularProgressIndicator(
            value: snapshot.data,
            color: color,
          ),
        ),
      ),
      onPressed: _onPressed,
      icon: const Icon(Icons.add),
      label: const Text('OutlinedLoadingButton'),
    );
  }
}

/// 通过api在后台主动发起点击事件加载操作的按钮实例
class BackgroundTextAutoLoadingButton extends StatefulWidget {
  const BackgroundTextAutoLoadingButton({super.key});

  @override
  State<BackgroundTextAutoLoadingButton> createState() => _BackgroundTextAutoLoadingButtonState();
}

class _BackgroundTextAutoLoadingButtonState extends State<BackgroundTextAutoLoadingButton> {
  final _loadingKey = GlobalKey<AutoLoadingButtonState>();
  late Timer _timer;

  Future<void> _onPressed() async {
    await Future.delayed(const Duration(seconds: 3));
  }

  @override
  void initState() {
    super.initState();
    _timer = Timer.periodic(const Duration(seconds: 5), (timer) {
      _loadingKey.currentState!.doPress();
    });
  }

  @override
  void dispose() {
    _timer.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return TextAutoLoadingButton.icon(
      key: _loadingKey,
      onPressed: _onPressed,
      icon: const Icon(Icons.add),
      label: const Text('TextLoadingButton Icon'),
    );
  }
}

以上代码展示了如何在 Flutter 应用中使用 material_loading_buttons 插件,包括自动和手动管理加载状态的按钮,以及自定义样式的按钮。希望这些示例能帮助你更好地理解和使用这个插件。


更多关于Flutter加载按钮样式插件material_loading_buttons的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter加载按钮样式插件material_loading_buttons的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何在Flutter项目中使用material_loading_buttons插件来实现加载按钮样式的示例代码。

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

dependencies:
  flutter:
    sdk: flutter
  material_loading_buttons: ^0.5.0  # 请检查最新版本号

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

接下来,在你的Dart文件中,你可以按照以下方式使用MaterialLoadingButton

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

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

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

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

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

  void handleSubmit() async {
    setState(() {
      isLoading = true;
    });

    // 模拟一个异步操作,例如网络请求
    await Future.delayed(Duration(seconds: 2));

    setState(() {
      isLoading = false;
    });

    // 可以在这里处理请求完成后的逻辑,比如显示一个Snackbar
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('操作完成!')));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Material Loading Buttons Demo'),
      ),
      body: Center(
        child: MaterialLoadingButton(
          isLoading: isLoading,
          width: 200,
          height: 50,
          child: Text('点击加载'),
          onPressed: handleSubmit,
          color: Colors.blue,
          borderColor: Colors.blueAccent,
          disabledColor: Colors.grey,
          disabledBorderColor: Colors.grey[300]!,
          animationDuration: 700,
          elevation: 5.0,
          borderRadius: BorderRadius.circular(30),
          type: MaterialLoadingButtonType.circularProgress,
        ),
      ),
    );
  }
}

在这个示例中,我们创建了一个简单的Flutter应用,其中包含一个使用MaterialLoadingButton的加载按钮。当按钮被点击时,isLoading状态会被设置为true,模拟一个异步操作(例如网络请求),然后在操作完成后将isLoading设置回false

MaterialLoadingButton的构造函数接受多个参数,允许你自定义按钮的样式和行为。在这个示例中,我们设置了按钮的宽度、高度、文本、点击回调、颜色、边框颜色、禁用时的颜色和边框颜色、动画持续时间、阴影高度和边框圆角等属性。

希望这个示例能帮助你理解如何在Flutter项目中使用material_loading_buttons插件来实现加载按钮样式。如果你有任何进一步的问题,请随时提问!

回到顶部