flutter如何实现骨架屏效果
在Flutter中如何实现骨架屏效果?我看到很多App在加载数据时会显示灰色占位图,等数据加载完毕再替换为真实内容。想请教大家:1) Flutter有哪些常用的骨架屏实现方案?2) 是否需要依赖第三方库,还是有原生支持的方式?3) 能否提供一个简单的代码示例?4) 实现过程中有哪些需要注意的性能问题?
        
          2 回复
        
      
      
        Flutter中实现骨架屏效果可使用shimmer库或自定义实现。通过Container模拟内容区域,配合透明度或渐变效果,在数据加载前展示占位骨架。常用shimmer包快速实现。
更多关于flutter如何实现骨架屏效果的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在Flutter中实现骨架屏效果可以通过以下几种方式:
1. 使用shimmer库(推荐)
import 'package:shimmer/shimmer.dart';
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,
      ),
      // 更多骨架屏元素...
    ],
  ),
)
2. 自定义骨架屏组件
class SkeletonItem extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.symmetric(vertical: 8),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            width: 50,
            height: 50,
            color: Colors.grey[300],
          ),
          SizedBox(width: 16),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  width: double.infinity,
                  height: 16,
                  color: Colors.grey[300],
                ),
                SizedBox(height: 8),
                Container(
                  width: 200,
                  height: 14,
                  color: Colors.grey[300],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
3. 完整示例
class SkeletonScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('加载中...')),
      body: ListView.builder(
        itemCount: 10,
        itemBuilder: (context, index) {
          return Shimmer.fromColors(
            baseColor: Colors.grey[300]!,
            highlightColor: Colors.grey[100]!,
            child: SkeletonItem(),
          );
        },
      ),
    );
  }
}
实现要点:
- 使用
shimmer包实现闪烁动画效果 - 骨架屏元素应与实际内容布局一致
 - 在数据加载完成后切换到真实内容
 - 可以设置不同的骨架屏样式匹配不同页面
 
这种方式能有效提升用户体验,让用户感知到内容正在加载中。
        
      
            
            
            
