返回

Flutter(十一):封装几个小 Widget

见解分享

本文是 Flutter 系列教程的第 11 篇,主要内容是封装几个小 Widget。

评分展示

评分展示是一个常见的功能,可以用于显示用户对某个产品的评分。Flutter 提供了内置的 RatingBar Widget,可以轻松实现评分展示功能。但是,RatingBar Widget 功能有限,无法满足一些特殊的需求。因此,我们需要自己封装一个评分展示的 Widget。

class RatingBar extends StatelessWidget {
  final double rating;
  final int starCount;

  const RatingBar({Key? key, required this.rating, required this.starCount})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Row(
      children: List.generate(starCount, (index) {
        return Icon(
          index < rating ? Icons.star : Icons.star_border,
          color: Colors.amber,
        );
      }),
    );
  }
}

这个 Widget 接受两个参数:rating 和 starCount。rating 是要显示的评分,starCount 是星星的个数。

分割线

分割线用于将不同的内容分开,使页面布局更清晰。Flutter 提供了内置的 Divider Widget,可以轻松实现分割线的功能。但是,Divider Widget 样式单一,无法满足一些特殊的需求。因此,我们需要自己封装一个分割线的 Widget。

class DashedLine extends StatelessWidget {
  final double height;
  final Color color;

  const DashedLine({Key? key, required this.height, required this.color})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: height,
      decoration: BoxDecoration(
        border: Border(
          bottom: BorderSide(
            color: color,
            width: 1,
            style: BorderStyle.dashed,
          ),
        ),
      ),
    );
  }
}

这个 Widget 接受两个参数:height 和 color。height 是分割线的高度,color 是分割线的颜色。

bottomNavigationBar

bottomNavigationBar 是一个位于屏幕底部的导航栏,可以用于在不同页面之间切换。Flutter 提供了内置的 BottomNavigationBar Widget,可以轻松实现 bottomNavigationBar 的功能。但是,BottomNavigationBar Widget 功能有限,无法满足一些特殊的需求。因此,我们需要自己封装一个 bottomNavigationBar 的 Widget。

class BottomNavigationBar extends StatelessWidget {
  final List<BottomNavigationBarItem> items;
  final int currentIndex;
  final void Function(int) onTap;

  const BottomNavigationBar({
    Key? key,
    required this.items,
    required this.currentIndex,
    required this.onTap,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return BottomNavigationBar(
      items: items,
      currentIndex: currentIndex,
      onTap: onTap,
    );
  }
}

这个 Widget 接受三个参数:items、currentIndex 和 onTap。items 是 bottomNavigationBar 的项目列表,currentIndex 是当前选中的项目索引,onTap 是项目被点击时的回调函数。

这些就是我们封装的几个小 Widget。这些 Widget 可以帮助你快速构建出更美观、更易用的 Flutter 应用程序。