Flutter如何使用skeletontheme

在Flutter中如何使用SkeletonTheme?我尝试在项目里实现骨架屏效果,但不太清楚如何正确配置SkeletonTheme的属性和使用方式。能否提供一个简单的代码示例,说明如何设置骨架屏的颜色、动画效果以及与其他组件的配合?另外,SkeletonTheme是否支持自定义形状和尺寸?

2 回复

在Flutter中使用SkeletonTheme非常简单,只需以下几步:

  1. 添加依赖:在pubspec.yaml中添加shimmer依赖
dependencies:
  shimmer: ^2.0.0
  1. 基本用法
SkeletonTheme(
  // 设置骨架屏主题
  shimmerGradient: LinearGradient(
    colors: [
      Colors.grey[300]!,
      Colors.grey[100]!,
      Colors.grey[300]!,
    ],
  ),
  child: SkeletonItem(
    child: Container(
      width: 200,
      height: 100,
      decoration: BoxDecoration(
        color: Colors.grey[300],
        borderRadius: BorderRadius.circular(8),
      ),
    ),
  ),
)
  1. 常用属性
  • shimmerGradient:设置闪烁渐变效果
  • child:需要显示骨架屏的组件
  • 可以配合SkeletonAnimation实现动画效果
  1. 使用场景
  • 网络加载时的占位图
  • 列表项加载状态
  • 图片加载前的预览

简单来说,就是用一个渐变色在灰色背景上移动,模拟加载效果,提升用户体验。

更多关于Flutter如何使用skeletontheme的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter中使用SkeletonTheme可以为骨架屏(加载占位效果)提供统一的样式配置。以下是使用方法:

1. 添加依赖

dependencies:
  flutter:
    sdk: flutter
  shimmer: ^3.0.0  # 常用骨架屏库

2. 基本使用

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

class SkeletonExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return SkeletonTheme(
      // 配置骨架屏主题
      shimmerGradient: LinearGradient(
        colors: [
          Colors.grey[300]!,
          Colors.grey[100]!,
          Colors.grey[300]!,
        ],
        stops: [0.1, 0.5, 0.9],
        begin: Alignment(-1.0, -0.3),
        end: Alignment(1.0, 0.3),
      ),
      darkShimmerGradient: LinearGradient(  // 深色模式
        colors: [
          Colors.grey[800]!,
          Colors.grey[600]!,
          Colors.grey[800]!,
        ],
        stops: [0.1, 0.5, 0.9],
        begin: Alignment(-1.0, -0.3),
        end: Alignment(1.0, 0.3),
      ),
      child: Shimmer.fromColors(
        baseColor: Colors.grey[300]!,
        highlightColor: Colors.grey[100]!,
        child: Column(
          children: [
            Container(
              width: double.infinity,
              height: 20,
              color: Colors.white,
            ),
            SizedBox(height: 10),
            Container(
              width: double.infinity,
              height: 20,
              color: Colors.white,
            ),
          ],
        ),
      ),
    );
  }
}

3. 通过主题获取配置

Widget buildSkeletonItem(BuildContext context) {
  final skeletonTheme = SkeletonTheme.of(context);
  
  return Shimmer(
    gradient: skeletonTheme.shimmerGradient,
    child: // 你的骨架屏内容
  );
}

主要配置属性

  • shimmerGradient: 闪烁渐变效果
  • darkShimmerGradient: 深色模式渐变
  • child: 子组件

这样可以在整个应用中保持骨架屏样式的一致性。

回到顶部