Flutter动态加载插件with_loader的使用

Flutter 动态加载插件 with_loader 的使用

with_loader

with_loader 是一个为 Flutter 提供加载功能的插件。只需将你的小部件包裹在 WithLoader 中,并提供所有必要的参数。

特性

  • 当你需要在按钮点击时执行 Future 函数时,它可以派上用场。
  • 你可以在加载状态下自定义子部件的不透明度。
  • 它会通过暴露的 Future 函数的结果来决定函数的 成功失败 条件。
  • 根据这个 成功条件,它将在 成功失败 时执行相应的操作。

开始使用

首先,在你的项目 pubspec.yaml 文件中添加 with_loader

dependencies:
  with_loader: ^0.0.1

然后,在你的 Dart 代码中导入该包:

import 'package:with_loader/with_loader.dart';

使用示例

将任何小部件包裹在 WithLoader<T>() 中:

WithLoader<String>(
  future: () => Future.delayed(const Duration(seconds: 2), () => "Success"),
  successCondition: (result) => result == "Success",
  child: Container(
    decoration: BoxDecoration(
      color: Colors.purple.shade400,
      borderRadius: BorderRadius.circular(50),
    ),
    child: const Padding(
      padding: EdgeInsets.symmetric(
        horizontal: 32.0,
        vertical: 16.0,
      ),
      child: Text(
        "Button",
        style: TextStyle(
          color: Colors.white,
          fontSize: 20,
          fontWeight: FontWeight.w500,
        ),
      ),
    ),
  ),
)

一些必需的参数使此小部件工作:

  • future: 需要执行的异步任务,返回 Future 对象。
  • successCondition: 判断结果是否成功的条件函数。
  • child: 在加载时显示的小部件。

示例代码

以下是一个完整的示例代码,展示了如何使用 with_loader 插件:

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:with_loader/with_loader.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'With Loader 示例',
      theme: ThemeData(
        primarySwatch: Colors.purple,
      ),
      home: Scaffold(
        body: Center(
          child: WithLoader<String>(
            future: () => Future.delayed(const Duration(seconds: 2), () => "Success"),
            successCondition: (result) => result == "Success",
            loaderAlignment: Alignment.center,
            onSuccess: () {
              if (kDebugMode) {
                print("加载成功");
              }
            },
            onFailure: () {
              if (kDebugMode) {
                print("加载失败");
              }
            },
            child: Container(
              decoration: BoxDecoration(
                color: Colors.purple.shade400,
                borderRadius: BorderRadius.circular(50),
              ),
              child: const Padding(
                padding: EdgeInsets.symmetric(
                  horizontal: 32.0,
                  vertical: 16.0,
                ),
                child: Text(
                  "按钮",
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 20,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
            ),
            loader: CircularProgressIndicator(
              color: Colors.purple.shade600,
            ),
          ),
        ),
      ),
    );
  }
}

更多关于Flutter动态加载插件with_loader的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

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


with_loader 是一个用于在 Flutter 应用中动态加载内容时显示加载动画的插件。它可以帮助你在异步操作(如网络请求、数据库查询等)进行时显示一个加载指示器,直到操作完成后再显示实际内容。

安装 with_loader

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

dependencies:
  flutter:
    sdk: flutter
  with_loader: ^1.0.0  # 请检查最新版本

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

使用 with_loader

with_loader 提供了一个 WithLoader 小部件,它可以在异步操作进行时显示加载指示器,并在操作完成后显示实际内容。

基本用法

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('WithLoader Example'),
        ),
        body: WithLoader<bool>(
          future: _fetchData(),  // 异步操作
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return Center(child: CircularProgressIndicator());
            } else if (snapshot.hasError) {
              return Center(child: Text('Error: ${snapshot.error}'));
            } else {
              return Center(child: Text('Data loaded: ${snapshot.data}'));
            }
          },
        ),
      ),
    );
  }

  Future<bool> _fetchData() async {
    await Future.delayed(Duration(seconds: 3));  // 模拟网络请求
    return true;
  }
}

void main() => runApp(MyApp());

参数说明

  • future: 一个 Future 对象,表示需要等待的异步操作。
  • builder: 一个回调函数,根据 snapshot 的状态来构建 UI。
    • snapshot.connectionState: 表示异步操作的状态,可以是 waiting, done, active, none
    • snapshot.hasError: 表示异步操作是否出错。
    • snapshot.data: 异步操作完成后返回的数据。

自定义加载指示器

你可以通过 loadingBuilder 参数来自定义加载指示器:

WithLoader<bool>(
  future: _fetchData(),
  loadingBuilder: (context) {
    return Center(child: CircularProgressIndicator());
  },
  builder: (context, snapshot) {
    if (snapshot.hasError) {
      return Center(child: Text('Error: ${snapshot.error}'));
    } else {
      return Center(child: Text('Data loaded: ${snapshot.data}'));
    }
  },
)

处理错误

你可以在 builder 中处理错误,或者在 errorBuilder 中自定义错误显示:

WithLoader<bool>(
  future: _fetchData(),
  errorBuilder: (context, error) {
    return Center(child: Text('Error: $error'));
  },
  builder: (context, snapshot) {
    return Center(child: Text('Data loaded: ${snapshot.data}'));
  },
)
回到顶部