Flutter加载动画插件shimmer_loading的使用

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

Flutter加载动画插件shimmer_loading的使用

shimmer_loading 是一个简单的 Flutter 插件,用于创建骨架屏和闪烁加载动画。

截图

App Screenshot

使用/示例

以下是一个完整的示例代码,展示了如何在 Flutter 应用中使用 shimmer_loading 插件来实现加载动画。

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

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

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

  final String title;

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

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

  void toggleLoading() {
    setState(() {
      isLoading = !isLoading;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            isLoading
                ? ShimmerLoading(
                    child: Container(
                      width: 200,
                      height: 50,
                      decoration: const BoxDecoration(
                        borderRadius: BorderRadius.all(Radius.circular(8.0)),
                        color: Color(0xFFEBEBF4),
                      ),
                      child: const UnconstrainedBox(
                          child: CircularProgressIndicator.adaptive()),
                    ),
                  )
                : Container(
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(8.0),
                      color: Theme.of(context).colorScheme.surface,
                    ),
                    child: const Text(
                      "lorum ipsum",
                    ),
                  ),
            const SizedBox(
              height: 16,
            ),
            isLoading
                ? ShimmerLoading(
                    child: Container(
                      decoration: const BoxDecoration(
                        borderRadius: BorderRadius.all(Radius.circular(8.0)),
                        color: Color(0xFFEBEBF4),
                      ),
                      child: const Text(
                        "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam",
                      ),
                    ),
                  )
                : Container(
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(8.0),
                      color: Theme.of(context).colorScheme.surface,
                    ),
                    child: Text(
                      "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam",
                      style: Theme.of(context).textTheme.headlineMedium,
                    ),
                  ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: toggleLoading,
        tooltip: 'Increment',
        child: Icon(
          isLoading ? Icons.hourglass_full : Icons.hourglass_bottom,
        ),
      ),
    );
  }
}

代码解释

  1. 导入必要的库:

    import 'package:flutter/material.dart';
    import 'package:shimmer_loading/shimmer_loading.dart';
    
  2. 定义主应用类:

    class MyApp extends StatelessWidget {
      const MyApp({super.key});
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
            useMaterial3: true,
          ),
          home: const MyHomePage(title: 'Flutter Demo Home Page'),
        );
      }
    }
    
  3. 定义主页类:

    class MyHomePage extends StatefulWidget {
      const MyHomePage({super.key, required this.title});
    
      final String title;
    
      @override
      State<MyHomePage> createState() => _MyHomePageState();
    }
    
  4. 定义主页状态类:

    class _MyHomePageState extends State<MyHomePage> {
      bool isLoading = true;
    
      void toggleLoading() {
        setState(() {
          isLoading = !isLoading;
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            backgroundColor: Theme.of(context).colorScheme.inversePrimary,
          ),
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                isLoading
                    ? ShimmerLoading(
                        child: Container(
                          width: 200,
                          height: 50,
                          decoration: const BoxDecoration(
                            borderRadius: BorderRadius.all(Radius.circular(8.0)),
                            color: Color(0xFFEBEBF4),
                          ),
                          child: const UnconstrainedBox(
                              child: CircularProgressIndicator.adaptive()),
                        ),
                      )
                    : Container(
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(8.0),
                          color: Theme.of(context).colorScheme.surface,
                        ),
                        child: const Text(
                          "lorum ipsum",
                        ),
                      ),
                const SizedBox(
                  height: 16,
                ),
                isLoading
                    ? ShimmerLoading(
                        child: Container(
                          decoration: const BoxDecoration(
                            borderRadius: BorderRadius.all(Radius.circular(8.0)),
                            color: Color(0xFFEBEBF4),
                          ),
                          child: const Text(
                            "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam",
                          ),
                        ),
                      )
                    : Container(
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(8.0),
                          color: Theme.of(context).colorScheme.surface,
                        ),
                        child: Text(
                          "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam",
                          style: Theme.of(context).textTheme.headlineMedium,
                        ),
                      ),
              ],
            ),
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: toggleLoading,
            tooltip: 'Increment',
            child: Icon(
              isLoading ? Icons.hourglass_full : Icons.hourglass_bottom,
            ),
          ),
        );
      }
    }
    

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

1 回复

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


当然,以下是如何在Flutter项目中使用shimmer_loading插件来展示加载动画的一个简单示例。这个插件常用于模拟数据加载的占位符动画,以提供用户友好的反馈。

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

dependencies:
  flutter:
    sdk: flutter
  shimmer_loading: ^1.0.0  # 请确保使用最新版本

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

接下来,你可以在你的Dart文件中使用ShimmerLoading组件。以下是一个完整的示例,展示如何在一个简单的Flutter应用中集成并使用shimmer_loading插件:

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

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

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

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

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

  @override
  void initState() {
    super.initState();
    // 模拟数据加载过程
    Future.delayed(Duration(seconds: 2), () {
      setState(() {
        isLoading = false;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Shimmer Loading Example'),
      ),
      body: isLoading
          ? Center(
              child: ShimmerLoading(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    SizedBox(height: 20),
                    ShimmerBase(
                      height: 20,
                      width: 100,
                      baseColor: Colors.grey[300]!,
                    ),
                    SizedBox(height: 10),
                    ShimmerBase(
                      height: 40,
                      width: 200,
                      borderRadius: BorderRadius.circular(10),
                      baseColor: Colors.grey[300]!,
                    ),
                    SizedBox(height: 10),
                    ShimmerBase(
                      height: 20,
                      width: 150,
                      baseColor: Colors.grey[300]!,
                    ),
                    SizedBox(height: 20),
                  ],
                ),
              ),
            )
          : ListView.builder(
              itemCount: 10,
              itemBuilder: (context, index) {
                return ListTile(
                  title: Text('Item $index'),
                );
              }),
    );
  }
}

在这个示例中:

  1. 我们首先定义了一个MyApp类作为应用的入口,并在MaterialApp中设置了主页面MyHomePage
  2. MyHomePage是一个有状态的组件,其中isLoading状态用于控制是否显示加载动画。
  3. initState方法中,我们使用Future.delayed来模拟数据加载过程,2秒后更新isLoading状态为false
  4. build方法根据isLoading状态返回不同的Widget:
    • 如果isLoadingtrue,则显示ShimmerLoading组件,该组件包含一个Column,其中包含了几个ShimmerBase子组件,用于模拟不同的加载占位符。
    • 如果isLoadingfalse,则显示一个包含10个ListTileListView

你可以根据需要调整ShimmerBase的属性,如heightwidthborderRadiusbaseColor,以符合你的UI设计需求。

回到顶部