Flutter辅助工具插件flutter_helper_kit的使用

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

Flutter辅助工具插件 flutter_helper_kit 的使用

安装

首先,在 pubspec.yaml 文件中添加 flutter_helper_kit 依赖:

dependencies:
  flutter_helper_kit: ^latest_version

然后运行以下命令来安装包:

$ flutter pub add flutter_helper_kit

接下来,导入包:

import 'package:flutter_helper_kit/flutter_helper_kit.dart';

主要内容

有用的扩展方法

Toast 示例

AppButton(
  onTap: () {
    FlutterToast.show('Flutter Helper Kit', context, position: FlutterToastPosition.bottom, duration: 500.milliseconds);
  },
  text: '点击显示Toast',
)

Widgets

FlutterTag 示例

FlutterTag(
  tagContent: Icon(Icons.ac_unit),
  tagStyle: FlutterTagStyle(
    tagColor: Colors.blue,
    borderRadius: 0.circularSharpBorderRadius,
    shape: FlutterTagShape.circle,
  ),
  tagAnimation: FlutterTagAnimation.fade(
    animationDuration: Duration(milliseconds: 1500),
    colorChangeAnimationCurve: Curves.decelerate,
    curve: Curves.ease,
    toAnimate: true,
  ),
  position: FlutterTagPosition.topEnd(),
  showTag: true,
  child: Icon(Icons.add_shopping_cart, size: 40),
  onTap: () {},
)

SharpRectangleBorder 示例

Column(
  children: <Widget>[
    Container(color: Colors.red, height: 20),
    const Gap(20), // 添加一个高度为20像素的空隙
    Container(color: Colors.red, height: 20),
  ],
)

TapSafeGesture 示例

TapSafeGesture(
  builder: (context, onTap) {
    return ElevatedButton(
      onPressed: onTap,
      child: Text('点击我'),
    );
  },
  waitBuilder: (context, child) {
    return Stack(
      alignment: Alignment.center,
      children: [
        child,
        CircularProgressIndicator(),
      ],
    );
  },
  onTap: () async {
    await Future.delayed(Duration(seconds: 2));
  },
  cooldown: Duration(seconds: 2),
)

GoogleLogoWidget 示例

GoogleLogoWidget(size: 36)

FlutterListView 示例

FlutterListView(
  items: myItems,
  itemBuilder: (context, item) {
    return ListTile(title: Text(item.title));
  },
  separatorBuilder: (context, index) {
    return Divider();
  },
  padding: EdgeInsets.all(16.0),
  scrollDirection: FlutterScrollDirection.vertical,
)

AvatarGlow 示例

AvatarGlow(
  glowColor: Colors.cyan,
  glowCount: 5,
  startDelay: 2.seconds,
  glowRadiusFactor: 2,
  child: GoogleLogoWidget(),
)

OutlineAvatarGlow 示例

OutlineAvatarGlow(
  glowColor: Colors.cyan,
  glowCount: 5,
  startDelay: 2.seconds,
  glowRadiusFactor: 2,
  child: GoogleLogoWidget(),
)

AppButton 示例

AppButton(
  onTap: () {},
  text: 'Flutter Helper Kit',
  shapeBorder: RoundedRectangleBorder(borderRadius: 16.circularBorderRadius),
  color: Colors.blue,
  textStyle: TextStyle(fontSize: 28),
  enabled: false,
)

CustomIndicator 示例

CustomIndicator(
  isActive: true,
  opacity: 0.6,
  bgColor: Colors.grey,
  child: Column(
    mainAxisAlignment: MainAxisAlignment.center,
    children: [
      Text('Screen1')
    ],
  ),
)

DashDivider 示例

DashDivider()

DoublePressBackWidget 示例

DoublePressBackWidget(
  message: '再次按下退出',
  onWillPop: () {
    print('双击确认');
  },
  child: AnyWidget(),
)

UnFocusable 示例

UnFocusable(
  child: Scaffold(),
)

Marquee 示例

Marquee(
  child: Text(
    'Flutter Helper Kit 示例 使用 Marquee 小部件。',
    style: TextStyle(fontSize: 24),
  ),
  direction: Axis.horizontal,
  textDirection: TextDirection.ltr,
  animationDuration: Duration(milliseconds: 3000),
  backDuration: Duration(milliseconds: 2000),
  pauseDuration: Duration(milliseconds: 1000),
  directionMarguee: DirectionMarguee.twoDirection,
)

RatingBarWidget 示例

RatingBarWidget(
  rating: 3.5,
  onRatingChanged: (newRating) {
    print('评分改变:$newRating');
  },
  activeColor: Colors.yellow,
  inActiveColor: Colors.grey,
  size: 40,
  allowHalfRating: true,
  filledIconData: Icons.star,
  halfFilledIconData: Icons.star_half,
  defaultIconData: Icons.star_border,
  spacing: 4.0,
  disable: false,
)

ReadMoreText 示例

ReadMoreText(
  '这是一段非常长的文本,需要被截断。\n点击“阅读更多”链接查看完整文本。\n点击“收起”链接折叠文本。',
  trimLines: 2,
  trimMode: TrimMode.line,
  trimCollapsedText: '...阅读更多',
  trimExpandedText: ' 收起',
  style: TextStyle(color: Colors.black),
  colorClickableText: Colors.blue,
  textAlign: TextAlign.start,
)

RoundedCheckBox 示例

RoundedCheckBox(
  isChecked: true,
  borderColor: Colors.grey,
  onTap: (isChecked) {
    print('复选框状态:$isChecked');
  },
  text: '接受条款',
)

SeparatedColumn 示例

SeparatedColumn(
  separatorBuilder: (BuildContext context, int index) => Container(height: 1, color: Colors.grey),
  children: const [
    Text('项目 1'),
    Text('项目 2'),
    Text('项目 3'),
  ],
)

TextAvatar 示例

TextAvatar(
  text: 'Flutter Helper Kit',
)

TextIcon 示例

TextIcon(
  text: '你好,世界',
  textStyle: TextStyle(color: Colors.blue, fontSize: 18),
  prefix: Icon(Icons.star, color: Colors.yellow),
  suffix: Icon(Icons.arrow_forward, color: Colors.red),
  spacing: 8,
  maxLine: 1,
  onTap: () {
    print('TextIcon 被点击了!');
  },
  edgeInsets: EdgeInsets.all(10),
  expandedText: true,
  useMarquee: false,
  boxDecoration: BoxDecoration(
    border: Border.all(color: Colors.grey),
    borderRadius: BorderRadius.circular(8),
  ),
)

TimerBuilder 示例

TimerBuilder.periodic(
  Duration(seconds: 5),
  builder: (context) {
    return Text(
      '当前时间:${DateTime.now()}',
      style: TextStyle(fontSize: 20),
    );
  },
)

扩展方法

String Extensions 示例

String example = "Hello World";
print(example.capitalizeFirstCharacter); // 输出: Hello World
print(example.removeAllWhiteSpace);     // 输出: HelloWorld

Bool Extensions 示例

bool flag = true;
print(flag.isTrue);                      // 输出: true
print(flag.toggle);                      // 输出: false

Color Extensions 示例

Color color = Colors.red;
print(color.toHex());                    // 输出: #ff0000
print(color.lighten(0.1));               // 返回浅色颜色

Build Context Extensions 示例

double screenHeight = context.height;    // 获取屏幕高度
context.showSnackBar();                  // 显示 SnackBar

DateTime Extensions 示例

DateTime pastDate = DateTime.now().subtract(Duration(hours: 2, minutes: 30));
print(pastDate.timeAgo);                 // 输出: 3 hours ago

Double Extensions 示例

double value = 10.0;
BorderRadius radius = value.circularRadius;

Duration Extensions 示例

await Duration(seconds: 1).delay();      // 延迟执行 1 秒

Int Extensions 示例

int number = 5;
number.height;                           // 创建一个高度为 5 的 SizedBox

List Extensions 示例

List<int> numbers = [1, 2, 3];
numbers.firstOrNull;                     // 返回第一个元素或 null

Num Extensions 示例

num value = 10;
value.between(5, 15);                    // 检查是否在范围内

ScopeFunction Extensions 示例

int number = 5;
String result = number.let((it) => 'Number is $it');
print(result);                           // 输出: Number is 5

系统方法

设置状态栏颜色

setStatusBarColor(Colors.blue);
setDarkStatusBar();
showStatusBar();
hideStatusBar();

工具函数

显示带有关闭按钮的对话框

showDialogWithCloseIcon(
  context: context,
  title: const Icon(Icons.image, size: 40),
  content: Column(children: [
    const Text('上传你的个人资料图片。'),
    20.height,
    OutlinedButton(onPressed: () {}, child: const Text('上传'))
  ]),
  closeButtonPosition: FlutterTagPosition.topEnd(),
  closeButtonAnimation: const FlutterTagAnimation.slide(),
  closeButtonStyle: FlutterTagStyle(borderRadius: 1000.circularSharpBorderRadius, shape: FlutterTagShape.circle),
  shape: SharpRectangleBorder(borderRadius: 16.circularSharpBorderRadius),
  closeIcon: const Icon(Icons.clear, color: Colors.white),
  dialogColor: Colors.white,
)

图片预览

以下是部分功能的示例截图链接:

贡献和反馈

如果你喜欢这个包,请给仓库加星。如果有任何问题或建议,请通过 GitHub 问题跟踪器提交请求或发送邮件至 sachin4kmt@gmail.com

感谢您的支持!❤️


更多关于Flutter辅助工具插件flutter_helper_kit的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter辅助工具插件flutter_helper_kit的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,关于Flutter辅助工具插件flutter_helper_kit的使用,以下是一个简单的代码示例,展示了如何集成和使用该插件的一些功能。请注意,flutter_helper_kit可能包含多个实用功能,这里仅展示几个常见的用途。

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

dependencies:
  flutter:
    sdk: flutter
  flutter_helper_kit: ^最新版本号  # 替换为实际的最新版本号

然后运行flutter pub get来获取依赖。

示例代码

以下是一个简单的Flutter应用,演示如何使用flutter_helper_kit中的一些功能,比如显示一个简单的对话框和网络请求。

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

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

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

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

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Helper Kit Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ElevatedButton(
              onPressed: () {
                // 使用FlutterHelperKit显示对话框
                showCustomDialog(
                  context: context,
                  title: '提示',
                  description: '这是一个使用flutter_helper_kit显示的对话框',
                  positiveButtonText: '确定',
                  onPositiveButtonPressed: () {
                    // 点击确定按钮后的操作
                    Navigator.of(context).pop();
                  },
                );
              },
              child: Text('显示对话框'),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () async {
                // 使用FlutterHelperKit进行网络请求(假设有一个GET请求的示例)
                try {
                  var response = await makeGetRequest(
                    url: 'https://jsonplaceholder.typicode.com/posts/1',
                  );
                  if (response.statusCode == 200) {
                    var data = jsonDecode(response.body);
                    print('请求成功: ${data}');
                    // 在这里处理响应数据,比如更新UI
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(content: Text('请求成功: ${data['title']}')),
                    );
                  } else {
                    print('请求失败: ${response.statusCode}');
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(content: Text('请求失败: ${response.statusCode}')),
                    );
                  }
                } catch (e) {
                  print('请求异常: $e');
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text('请求异常: $e')),
                  );
                }
              },
              child: Text('发送网络请求'),
            ),
          ],
        ),
      ),
    );
  }
}

说明

  1. 显示对话框:使用showCustomDialog函数显示一个自定义对话框。你可以根据需要调整对话框的标题、描述和按钮文本。

  2. 网络请求:使用makeGetRequest函数发送一个GET请求。这里假设你请求的是一个JSONPlaceholder的示例API。实际使用中,你需要替换为实际的API URL。

请注意,flutter_helper_kit的具体API和功能可能会随着版本更新而变化,因此建议查阅最新的官方文档以获取最准确的信息。如果flutter_helper_kit没有提供showCustomDialogmakeGetRequest这样的函数,你可能需要查阅其文档来找到相应的替代方案。

回到顶部