Flutter工具集插件flutter_util_code的使用

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

Flutter工具集插件flutter_util_code的使用

flutter_util_code 是一个Flutter工具类集合库,包含了一些常用的功能和封装的系统API调用,旨在提高开发效率。以下是该插件的详细使用说明和完整示例代码。

1. 添加依赖

pubspec.yaml 文件中添加 flutter_util_code 依赖:

dependencies:
  flutter_util_code: ^latest_version

确保你的项目支持以下环境:

  • SDK: >=2.18.0 <4.0.0
  • Flutter: >=3.3.0

2. 使用示例

下面是一个完整的示例应用,展示了如何使用 flutter_util_code 中的各种工具类。

main.dart
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_util_code/flutter_util_code.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  // 强制竖屏
  SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Util Code Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const HomeScreen(),
    );
  }
}

class HomeScreen extends StatelessWidget {
  const HomeScreen({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Flutter Util Code Demo'),
      ),
      body: ListView(
        children: [
          ListTile(
            title: const Text('LogUtils'),
            onTap: () {
              LogUtils.println("This is a log message");
              Navigator.push(context, MaterialPageRoute(builder: (context) => const LogPage()));
            },
          ),
          ListTile(
            title: const Text('SharedPrefsUtils'),
            onTap: () {
              SharedPrefsUtils.putString("key", "value");
              final value = SharedPrefsUtils.getString("key");
              ToastUtils.show("Stored value: $value");
              Navigator.push(context, MaterialPageRoute(builder: (context) => const SharedPrefsPage()));
            },
          ),
          ListTile(
            title: const Text('ToastUtils'),
            onTap: () {
              ToastUtils.show("This is a toast message");
              Navigator.push(context, MaterialPageRoute(builder: (context) => const ToastPage()));
            },
          ),
          ListTile(
            title: const Text('UuidUtils'),
            onTap: () {
              final uuid = UuidUtils.getUuidV4();
              ToastUtils.show("Generated UUID: $uuid");
              Navigator.push(context, MaterialPageRoute(builder: (context) => const UuidPage()));
            },
          ),
          ListTile(
            title: const Text('DeviceUtils'),
            onTap: () {
              final deviceId = DeviceUtils.getDeviceId();
              final model = DeviceUtils.getModel();
              final systemVersion = DeviceUtils.getSystemVersion();
              final systemName = DeviceUtils.getSystemName();
              final brand = DeviceUtils.getBrand();
              ToastUtils.show("Device Info: $deviceId, $model, $systemVersion, $systemName, $brand");
              Navigator.push(context, MaterialPageRoute(builder: (context) => const DevicePage()));
            },
          ),
          ListTile(
            title: const Text('AppUtils'),
            onTap: () {
              final appName = AppUtils.getAppName();
              final packageName = AppUtils.getPackageName();
              final versionName = AppUtils.getVersionName();
              final versionNumber = AppUtils.getVersionNumber();
              ToastUtils.show("App Info: $appName, $packageName, $versionName, $versionNumber");
              Navigator.push(context, MaterialPageRoute(builder: (context) => const AppPage()));
            },
          ),
          ListTile(
            title: const Text('PathUtils'),
            onTap: () {
              final cachePath = PathUtils.getAppCachePath();
              final supportPath = PathUtils.getAppSupportPath();
              final docPath = PathUtils.getAppDocPath();
              ToastUtils.show("Paths: $cachePath, $supportPath, $docPath");
              Navigator.push(context, MaterialPageRoute(builder: (context) => const PathPage()));
            },
          ),
          ListTile(
            title: const Text('EncryptUtils'),
            onTap: () {
              final originalText = "Hello, World!";
              final encryptedText = EncryptUtils.aesEncrypt(originalText);
              final decryptedText = EncryptUtils.aesDecrypt(encryptedText);
              ToastUtils.show("Original: $originalText, Encrypted: $encryptedText, Decrypted: $decryptedText");
              Navigator.push(context, MaterialPageRoute(builder: (context) => const EncryptPage()));
            },
          ),
          ListTile(
            title: const Text('UrlLauncherUtils'),
            onTap: () {
              UrlLauncherUtils.launchInBrowser("https://flutter.dev");
              ToastUtils.show("Launched URL in browser");
              Navigator.push(context, MaterialPageRoute(builder: (context) => const UrlLauncherPage()));
            },
          ),
          ListTile(
            title: const Text('NullSafetyUtils'),
            onTap: () {
              final nullString = NullSafetyUtils.toNonNull<String>(null);
              final nonNullString = NullSafetyUtils.toNonNull<String>("Non-null string");
              ToastUtils.show("Null String: $nullString, Non-null String: $nonNullString");
              Navigator.push(context, MaterialPageRoute(builder: (context) => const NullSafetyPage()));
            },
          ),
          ListTile(
            title: const Text('ShareUtils'),
            onTap: () {
              ShareUtils.shareText("Check out this awesome app!");
              ToastUtils.show("Shared text");
              Navigator.push(context, MaterialPageRoute(builder: (context) => const SharePage()));
            },
          ),
          ListTile(
            title: const Text('NetworkUtils'),
            onTap: () async {
              final isConnected = await NetworkUtils.checkConnectivity();
              ToastUtils.show("Is Connected: $isConnected");
              Navigator.push(context, MaterialPageRoute(builder: (context) => const NetworkPage()));
            },
          ),
          ListTile(
            title: const Text('PermissionUtils'),
            onTap: () async {
              final status = await PermissionUtils.getPermissionStatus(Permission.storage);
              if (status.isDenied) {
                final result = await PermissionUtils.requestPermission(Permission.storage);
                ToastUtils.show("Permission Status: $result");
              } else {
                ToastUtils.show("Permission already granted");
              }
              Navigator.push(context, MaterialPageRoute(builder: (context) => const PermissionPage()));
            },
          ),
          ListTile(
            title: const Text('FormatUtils'),
            onTap: () {
              final formattedMoney = FormatUtils.formatMoney(1234567.89);
              final formattedPercent = FormatUtils.formatPercent(0.75);
              ToastUtils.show("Formatted Money: $formattedMoney, Formatted Percent: $formattedPercent");
              Navigator.push(context, MaterialPageRoute(builder: (context) => const FormatPage()));
            },
          ),
        ],
      ),
    );
  }
}
LogPage.dart
import 'package:flutter/material.dart';
import 'package:flutter_util_code/flutter_util_code.dart';

class LogPage extends StatelessWidget {
  const LogPage({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Log Page'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            LogUtils.println("Logging from LogPage");
            ToastUtils.show("Log printed");
          },
          child: const Text('Print Log'),
        ),
      ),
    );
  }
}
SharedPrefsPage.dart
import 'package:flutter/material.dart';
import 'package:flutter_util_code/flutter_util_code.dart';

class SharedPrefsPage extends StatelessWidget {
  const SharedPrefsPage({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('SharedPrefs Page'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: () {
                SharedPrefsUtils.putString("key", "new_value");
                final value = SharedPrefsUtils.getString("key");
                ToastUtils.show("Updated value: $value");
              },
              child: const Text('Update Value'),
            ),
            ElevatedButton(
              onPressed: () {
                final value = SharedPrefsUtils.getString("key");
                ToastUtils.show("Retrieved value: $value");
              },
              child: const Text('Get Value'),
            ),
          ],
        ),
      ),
    );
  }
}
ToastPage.dart
import 'package:flutter/material.dart';
import 'package:flutter_util_code/flutter_util_code.dart';

class ToastPage extends StatelessWidget {
  const ToastPage({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Toast Page'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            ToastUtils.show("This is another toast message");
          },
          child: const Text('Show Toast'),
        ),
      ),
    );
  }
}
UuidPage.dart
import 'package:flutter/material.dart';
import 'package:flutter_util_code/flutter_util_code.dart';

class UuidPage extends StatelessWidget {
  const UuidPage({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('UUID Page'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            final uuid = UuidUtils.getUuidV4();
            ToastUtils.show("Generated UUID: $uuid");
          },
          child: const Text('Generate UUID'),
        ),
      ),
    );
  }
}
DevicePage.dart
import 'package:flutter/material.dart';
import 'package:flutter_util_code/flutter_util_code.dart';

class DevicePage extends StatelessWidget {
  const DevicePage({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Device Page'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            final deviceId = DeviceUtils.getDeviceId();
            final model = DeviceUtils.getModel();
            final systemVersion = DeviceUtils.getSystemVersion();
            final systemName = DeviceUtils.getSystemName();
            final brand = DeviceUtils.getBrand();
            ToastUtils.show("Device Info: $deviceId, $model, $systemVersion, $systemName, $brand");
          },
          child: const Text('Get Device Info'),
        ),
      ),
    );
  }
}
AppPage.dart
import 'package:flutter/material.dart';
import 'package:flutter_util_code/flutter_util_code.dart';

class AppPage extends StatelessWidget {
  const AppPage({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('App Page'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            final appName = AppUtils.getAppName();
            final packageName = AppUtils.getPackageName();
            final versionName = AppUtils.getVersionName();
            final versionNumber = AppUtils.getVersionNumber();
            ToastUtils.show("App Info: $appName, $packageName, $versionName, $versionNumber");
          },
          child: const Text('Get App Info'),
        ),
      ),
    );
  }
}
PathPage.dart
import 'package:flutter/material.dart';
import 'package:flutter_util_code/flutter_util_code.dart';

class PathPage extends StatelessWidget {
  const PathPage({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Path Page'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            final cachePath = PathUtils.getAppCachePath();
            final supportPath = PathUtils.getAppSupportPath();
            final docPath = PathUtils.getAppDocPath();
            ToastUtils.show("Paths: $cachePath, $supportPath, $docPath");
          },
          child: const Text('Get Paths'),
        ),
      ),
    );
  }
}
EncryptPage.dart
import 'package:flutter/material.dart';
import 'package:flutter_util_code/flutter_util_code.dart';

class EncryptPage extends StatelessWidget {
  const EncryptPage({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Encrypt Page'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            final originalText = "Hello, World!";
            final encryptedText = EncryptUtils.aesEncrypt(originalText);
            final decryptedText = EncryptUtils.aesDecrypt(encryptedText);
            ToastUtils.show("Original: $originalText, Encrypted: $encryptedText, Decrypted: $decryptedText");
          },
          child: const Text('Encrypt/Decrypt Text'),
        ),
      ),
    );
  }
}
UrlLauncherPage.dart
import 'package:flutter/material.dart';
import 'package:flutter_util_code/flutter_util_code.dart';

class UrlLauncherPage extends StatelessWidget {
  const UrlLauncherPage({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('URL Launcher Page'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            UrlLauncherUtils.launchInBrowser("https://flutter.dev");
            ToastUtils.show("Launched URL in browser");
          },
          child: const Text('Launch URL in Browser'),
        ),
      ),
    );
  }
}
NullSafetyPage.dart
import 'package:flutter/material.dart';
import 'package:flutter_util_code/flutter_util_code.dart';

class NullSafetyPage extends StatelessWidget {
  const NullSafetyPage({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Null Safety Page'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            final nullString = NullSafetyUtils.toNonNull<String>(null);
            final nonNullString = NullSafetyUtils.toNonNull<String>("Non-null string");
            ToastUtils.show("Null String: $nullString, Non-null String: $nonNullString");
          },
          child: const Text('Test Null Safety'),
        ),
      ),
    );
  }
}
SharePage.dart
import 'package:flutter/material.dart';
import 'package:flutter_util_code/flutter_util_code.dart';

class SharePage extends StatelessWidget {
  const SharePage({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Share Page'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            ShareUtils.shareText("Check out this awesome app!");
            ToastUtils.show("Shared text");
          },
          child: const Text('Share Text'),
        ),
      ),
    );
  }
}
NetworkPage.dart
import 'package:flutter/material.dart';
import 'package:flutter_util_code/flutter_util_code.dart';

class NetworkPage extends StatefulWidget {
  const NetworkPage({super.key});

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

class _NetworkPageState extends State<NetworkPage> {
  bool _isConnected = false;

  [@override](/user/override)
  void initState() {
    super.initState();
    _checkConnectivity();
  }

  Future<void> _checkConnectivity() async {
    final isConnected = await NetworkUtils.checkConnectivity();
    setState(() {
      _isConnected = isConnected;
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Network Page'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text("Is Connected: $_isConnected"),
            ElevatedButton(
              onPressed: _checkConnectivity,
              child: const Text('Check Connectivity'),
            ),
          ],
        ),
      ),
    );
  }
}
PermissionPage.dart
import 'package:flutter/material.dart';
import 'package:flutter_util_code/flutter_util_code.dart';
import 'package:permission_handler/permission_handler.dart';

class PermissionPage extends StatefulWidget {
  const PermissionPage({super.key});

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

class _PermissionPageState extends State<PermissionPage> {
  PermissionStatus _status = PermissionStatus.denied;

  Future<void> _requestPermission() async {
    final status = await PermissionUtils.getPermissionStatus(Permission.storage);
    if (status.isDenied) {
      final result = await PermissionUtils.requestPermission(Permission.storage);
      setState(() {
        _status = result;
      });
    } else {
      setState(() {
        _status = status;
      });
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Permission Page'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text("Permission Status: $_status"),
            ElevatedButton(
              onPressed: _requestPermission,
              child: const Text('Request Permission'),
            ),
          ],
        ),
      ),
    );
  }
}
FormatPage.dart
import 'package:flutter/material.dart';
import 'package:flutter_util_code/flutter_util_code.dart';

class FormatPage extends StatelessWidget {
  const FormatPage({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Format Page'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            final formattedMoney = FormatUtils.formatMoney(1234567.89);
            final formattedPercent = FormatUtils.formatPercent(0.75);
            ToastUtils.show("Formatted Money: $formattedMoney, Formatted Percent: $formattedPercent");
          },
          child: const Text('Format Numbers'),
        ),
      ),
    );
  }
}

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

1 回复

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


当然,flutter_util_code 是一个 Flutter 插件集合,通常用于提供一系列实用的工具函数和组件,以减少开发者的重复劳动。虽然具体的插件功能和实现可能因版本而异,但以下是一个如何使用 flutter_util_code(假设它包含一些常见工具函数)的示例代码。

请注意,由于 flutter_util_code 并非一个广为人知的官方或广泛使用的插件,以下示例是基于假设的功能集编写的。实际使用时,请参考该插件的官方文档和源代码。

首先,确保在 pubspec.yaml 文件中添加依赖项(假设插件名为 flutter_util_code):

dependencies:
  flutter:
    sdk: flutter
  flutter_util_code: ^x.y.z  # 替换为实际版本号

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

示例代码

1. 使用字符串工具函数

假设 flutter_util_code 提供了一些字符串处理函数,如首字母大写、反转字符串等。

import 'package:flutter/material.dart';
import 'package:flutter_util_code/flutter_util_code.dart';  // 假设插件提供这个导入路径

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Util Code Demo'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(
                'Original String: hello world',
              ),
              Text(
                'Capitalized String: ${StringUtil.capitalize("hello world")}',  // 假设 StringUtil 是插件提供的一个类
              ),
              Text(
                'Reversed String: ${StringUtil.reverse("hello world")}',
              ),
            ],
          ),
        ),
      ),
    );
  }
}

2. 使用日期工具函数

假设 flutter_util_code 还提供了一些日期处理函数,如格式化日期等。

import 'package:flutter/material.dart';
import 'package:flutter_util_code/flutter_util_code.dart';  // 假设插件提供这个导入路径
import 'package:intl/intl.dart';  // 用于日期格式化对比

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    DateTime now = DateTime.now();
    
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Util Code Demo'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(
                'Current Date: ${DateFormat('yyyy-MM-dd').format(now)}',
              ),
              Text(
                'Formatted Date (Util): ${DateUtil.format(now, 'yyyy-MM-dd')}',  // 假设 DateUtil 是插件提供的一个类
              ),
            ],
          ),
        ),
      ),
    );
  }
}

3. 使用网络请求工具函数

假设 flutter_util_code 还提供了简化 HTTP 请求的函数。

import 'package:flutter/material.dart';
import 'package:flutter_util_code/flutter_util_code.dart';  // 假设插件提供这个导入路径
import 'dart:convert';

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String responseData = '';

  @override
  void initState() {
    super.initState();
    _fetchData();
  }

  Future<void> _fetchData() async {
    try {
      String url = 'https://jsonplaceholder.typicode.com/posts/1';  // 示例 API
      Map<String, String> headers = {'Content-Type': 'application/json'};
      String responseBody = await NetworkUtil.get(url, headers: headers);  // 假设 NetworkUtil 是插件提供的一个类
      Map<String, dynamic> responseJson = jsonDecode(responseBody);
      setState(() {
        responseData = responseJson['title'] ?? 'Failed to load data';
      });
    } catch (e) {
      setState(() {
        responseData = 'Error: $e';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Util Code Demo'),
        ),
        body: Center(
          child: Text(
            responseData,
            style: TextStyle(fontSize: 20),
          ),
        ),
      ),
    );
  }
}

注意

  • 上述代码是基于假设的 flutter_util_code 插件功能编写的。实际使用时,请参考该插件的官方文档和 API 参考。
  • 插件的导入路径、类名和函数名可能与实际插件有所不同。
  • 确保插件已正确安装并导入到你的 Flutter 项目中。
  • 如果 flutter_util_code 插件不存在或功能不符合预期,可以考虑使用其他流行的 Flutter 工具集插件,如 fluttertoasthttpshared_preferences 等。
回到顶部