Flutter实用工具插件smart_utils的使用

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

Flutter实用工具插件smart_utils的使用

smart_utils

webview 页面参数

以下是 webview 页面的主要参数说明:

参数名称 值类型 默认值 是否必填 备注
initialUrl String - 初始化加载的URL
userAgent String - 用户代理字符串
channelName String NativeFun JS通道名称
processColor Color - 进程颜色
safeAreaBg Color - 安全区域背景色

jsChannel 方法说明

以下是 jsChannel 的方法详细说明:

方法名 说明 请求参数 响应 备注
Toaster toast提示 String msg null 显示简单的提示信息
CloseApp 退出app - - 关闭应用程序
StartPosition 启动位置监听 int interval String success/fail 定位间隔时间(单位:秒)
StopPosition 停止位置监听 - - 停止位置监听
ChooseMedia 选择媒体文件 见:mediaOption Array 支持图片或视频文件的选择
setStatusBarColor 设置状态栏颜色 String color (无#号) String success/fail 状态栏颜色值,例如:“000000”
Wakelock 设置屏幕常亮 bool state String success/fail true开启,false关闭屏幕常亮
WakelockState 获取屏幕常亮状态 - bool true/false 获取当前屏幕常亮状态
GetVolume 获取音量大小 - double 4.002 返回当前音量值
SetVolume 设置音量大小 double volume String success/fail 设置音量值
Speak 语音读文字 String text String success/fail 将文本内容朗读出来
WechatShare 微信分享 见 WechatShareOptions - 支持微信分享功能
Scan 扫描二维码 - - 跳转到扫描二维码页面
LaunchJPush 启动极光推送 appKey channel - 极光推送服务
NotificationEnabled 检查通知权限 - - 检查通知权限是否开启
OpenNotificationSetting 打开通知设置 - - 跳转到系统通知设置页面
SetJPushTags 设置极光推送tags - - 设置极光推送的标签
GetJPushTags 获取极光推送tags - {“tags”:[“Shop5909”]} 获取当前极光推送的tags
StopJPush 停止极光推送 - - 停止极光推送服务
ResumeJPush 重启极光推送 - - 重启极光推送服务
ScanBlue 扫描蓝牙设备 - - 扫描附近的蓝牙设备
ConnectBlue 连接蓝牙设备 name, address, type, alias - 连接指定的蓝牙设备
DisConnectBlue 断开蓝牙连接 name, address, type, alias - 断开指定的蓝牙连接
ConnectedItem 获取已连接蓝牙设备 alias - 获取已连接的蓝牙设备信息
PrintTicket 打印小票 url, alias, pageSize - 打印指定格式的小票
TestPrintTicket 打印测试小票 alias - 测试打印功能

flutter 调用 web 方法说明

以下是 flutter 调用 web 的方法说明:

方法名 说明 data flag 备注
positionChanged 位置改变时的回调 位置的map信息 - {“callbackTime”:“2022-06-17 14:40:30”,“locationTime”:“2022-06-17 14:29:54”,…}
volumeChanged 系统音量改变时的回调 - - 当系统音量发生变化时触发
receiveJPushMessage 收到极光推送消息时的回调 Map jPushMessage ‘’ {“alert”:“Hello World”}

mediaOption

以下是 mediaOption 的参数说明:

参数名称 可选值 默认值 备注
type image/video image 文件类型选择
source photo/camera photo 来源:相册/相机

WechatShareOptions

以下是 WechatShareOptions 的参数说明:

参数名称 值类型 默认值 备注
shareType int - 1为网页分享,2为小程序分享
scene int - 0为聊天界面,1为朋友圈,2为收藏
webpageUrl String - 必填,分享的网页链接
title String - 必填,分享的标题
description String - 必填,分享的描述
imgUrl String - 必填,分享的图片链接
miniappId String - 小程序分享必填,小程序的AppID
path String - 小程序分享必填,小程序的具体路径

完整示例代码

以下是一个完整的示例代码,展示如何使用 smart_utils 插件。

import 'package:flutter/material.dart';
import 'package:smart_utils/smart_utils.dart'; // 导入smart_utils插件

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Smart Utils Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const SmartUtilsExamplePage(),
    );
  }
}

class SmartUtilsExamplePage extends StatefulWidget {
  const SmartUtilsExamplePage({Key? key}) : super(key: key);

  [@override](/user/override)
  _SmartUtilsExamplePageState createState() => _SmartUtilsExamplePageState();
}

class _SmartUtilsExamplePageState extends State<SmartUtilsExamplePage> {
  late Future<String> _future;

  [@override](/user/override)
  void initState() {
    super.initState();
    // 初始化插件
    SmartUtils.init();
    _future = SmartUtils.showToast("Hello Smart Utils");
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Smart Utils Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ElevatedButton(
              onPressed: () async {
                // 调用Toast提示
                await SmartUtils.showToast("点击了按钮");
              },
              child: const Text('显示Toast'),
            ),
            ElevatedButton(
              onPressed: () {
                // 调用设置状态栏颜色
                SmartUtils.setStatusBarColor("FF0000");
              },
              child: const Text('设置状态栏红色'),
            ),
            ElevatedButton(
              onPressed: () async {
                // 获取当前音量
                final volume = await SmartUtils.getVolume();
                print("当前音量: $volume");
              },
              child: const Text('获取音量'),
            ),
            ElevatedButton(
              onPressed: () async {
                // 设置音量
                await SmartUtils.setVolume(5.0);
                print("音量已设置为5.0");
              },
              child: const Text('设置音量为5.0'),
            ),
          ],
        ),
      ),
    );
  }
}

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

1 回复

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


smart_utils 是一个 Flutter 实用工具插件,提供了许多常用的功能,如网络状态检查、设备信息获取、屏幕工具、日期时间工具、字符串工具等。它可以帮助开发者更高效地开发 Flutter 应用程序。

以下是 smart_utils 插件的一些常见用法:

1. 安装插件

首先,你需要在 pubspec.yaml 文件中添加 smart_utils 依赖:

dependencies:
  flutter:
    sdk: flutter
  smart_utils: ^1.0.0  # 请使用最新版本

然后运行 flutter pub get 来安装插件。

2. 导入插件

在你的 Dart 文件中导入 smart_utils

import 'package:smart_utils/smart_utils.dart';

3. 使用工具类

3.1 网络状态检查

NetworkUtils 类提供了检查网络连接状态的功能。

bool isConnected = await NetworkUtils.isConnected();
if (isConnected) {
  print("设备已连接到网络");
} else {
  print("设备未连接到网络");
}

3.2 设备信息获取

DeviceUtils 类提供了获取设备信息的功能。

String deviceId = await DeviceUtils.getDeviceId();
String deviceModel = await DeviceUtils.getDeviceModel();
String deviceBrand = await DeviceUtils.getDeviceBrand();
String osVersion = await DeviceUtils.getOsVersion();

print("设备ID: $deviceId");
print("设备型号: $deviceModel");
print("设备品牌: $deviceBrand");
print("操作系统版本: $osVersion");

3.3 屏幕工具

ScreenUtils 类提供了与屏幕相关的工具,如获取屏幕宽度、高度、密度等。

double screenWidth = ScreenUtils.screenWidth;
double screenHeight = ScreenUtils.screenHeight;
double pixelRatio = ScreenUtils.pixelRatio;

print("屏幕宽度: $screenWidth");
print("屏幕高度: $screenHeight");
print("像素密度: $pixelRatio");

3.4 日期时间工具

DateUtils 类提供了日期时间格式化和解析的功能。

DateTime now = DateTime.now();
String formattedDate = DateUtils.formatDate(now, "yyyy-MM-dd HH:mm:ss");
print("格式化后的日期: $formattedDate");

DateTime parsedDate = DateUtils.parseDate("2023-10-01 12:00:00", "yyyy-MM-dd HH:mm:ss");
print("解析后的日期: $parsedDate");

3.5 字符串工具

StringUtils 类提供了字符串处理的工具,如判断字符串是否为空、是否为邮箱、是否为手机号等。

bool isEmpty = StringUtils.isEmpty("");
bool isEmail = StringUtils.isEmail("test@example.com");
bool isPhone = StringUtils.isPhone("13800138000");

print("字符串是否为空: $isEmpty");
print("字符串是否为邮箱: $isEmail");
print("字符串是否为手机号: $isPhone");

4. 其他工具

smart_utils 还提供了其他一些实用工具,如 FileUtils(文件操作)、LogUtils(日志打印)、SharedPreferencesUtils(本地存储)等。你可以根据需求使用这些工具。

5. 示例代码

以下是一个简单的示例,展示了如何使用 smart_utils 插件中的一些功能:

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

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Smart Utils Example'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ElevatedButton(
                onPressed: () async {
                  bool isConnected = await NetworkUtils.isConnected();
                  print("设备已连接到网络: $isConnected");
                },
                child: Text("检查网络连接"),
              ),
              ElevatedButton(
                onPressed: () async {
                  String deviceId = await DeviceUtils.getDeviceId();
                  print("设备ID: $deviceId");
                },
                child: Text("获取设备ID"),
              ),
              ElevatedButton(
                onPressed: () {
                  double screenWidth = ScreenUtils.screenWidth;
                  print("屏幕宽度: $screenWidth");
                },
                child: Text("获取屏幕宽度"),
              ),
              ElevatedButton(
                onPressed: () {
                  DateTime now = DateTime.now();
                  String formattedDate = DateUtils.formatDate(now, "yyyy-MM-dd HH:mm:ss");
                  print("格式化后的日期: $formattedDate");
                },
                child: Text("格式化日期"),
              ),
              ElevatedButton(
                onPressed: () {
                  bool isEmail = StringUtils.isEmail("test@example.com");
                  print("字符串是否为邮箱: $isEmail");
                },
                child: Text("检查邮箱格式"),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!