Flutter实用工具插件danisoft_utils的使用

Flutter实用工具插件danisoft_utils的使用

本包有助于以优雅且简单的方式管理屏幕之间的过渡,并帮助生成JWT!

可用功能

  • PageRouteTransition(以优雅且简便的方式管理屏幕之间的过渡)
  • JwtClient(生成JWT)
  • verifyJwtHS256Signature(验证签名并提取JwtClient)
final JwtClient decClientSet = verifyJwtHS256Signature(token, key);

完整示例

以下是使用danisoft_utils插件的完整示例。

示例代码

import 'package:danisoft_utils/danisoft_utils.dart';
import 'package:flutter/material.dart';
import 'dart:math';

const String sharedSecret = 's3cr3t';

void main() {
  final jwt = senderCreatesJwt();
  receiverProcessesJwt(jwt);
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Material App',
      initialRoute: 'page1',
      routes: {
        'page1': (_) => Page1(),
        'page2': (_) => Page2(),
      },
    );
  }
}

class Page1 extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Page 1'),
        backgroundColor: Colors.transparent,
      ),
      backgroundColor: Colors.blue,
      body: Center(
        child: MaterialButton(
          child: Text('Go to page2'),
          color: Colors.white,
          onPressed: () {
            PageRouteTransition(
              context: context,
              page: Page2(),
              animation: AnimationType.fadeIn,
              duration: Duration(milliseconds: 100),
              replacement: true,
            );
          },
        ),
      ),
    );
  }
}

class Page2 extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Page 2'),
        backgroundColor: Colors.transparent,
      ),
      backgroundColor: Colors.blueGrey,
      body: Center(
        child: Text('Page2'),
      ),
    );
  }
}

String senderCreatesJwt() {
  // 创建一个 JwtClient

  final claimSet = new JwtClient(
      issuer: 'ds+',
      subject: 'Ds+',
      audience: ['danisoft.com.co', 'www.danisoft.com.co'],
      jwtId: _randomString(32),
      otherClaims: {
        "IdUsuario": "prueba 1",
        "nombre": "My name",
        "apellidos": "My Apellidos",
        "direccion": "My direccion",
        "tel": "My tel",
        "typ": "authnresponse",
        "pld": {"k": "v"}
      },
      maxAge: const Duration(minutes: 5));

  // 从声明集生成JWT

  final token = issueJwtHS256(claimSet, sharedSecret);

  print('JWT: "$token"\n');

  return token;
}

void receiverProcessesJwt(String token) {
  try {
    // 验证JWT中的签名并提取声明集
    final decClaimSet = verifyJwtHS256Signature(token, sharedSecret);
    print('JwtClaim: $decClaimSet\n');

    // 验证声明集

    decClaimSet.validate(issuer: 'ds+', audience: 'danisoft.com.co');

    // 使用声明集中的值

    if (decClaimSet.subject != null) {
      print('JWT ID: "${decClaimSet.jwtId}"');
    }
    if (decClaimSet.jwtId != null) {
      print('Subject: "${decClaimSet.subject}"');
    }
    if (decClaimSet.issuedAt != null) {
      print('Issued At: ${decClaimSet.issuedAt}');
    }
    if (decClaimSet.containsKey('typ')) {
      final dynamic v = decClaimSet['typ'];
      if (v is String) {
        print('typ: "$v"');
      } else {
        print('Error: unexpected type for "typ" claim');
      }
    }
  } on JwtException catch (e) {
    print('Error: bad JWT: $e');
  }
}

String _randomString(int length) {
  const chars = 
      '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
  final rnd = new Random(new DateTime.now().millisecondsSinceEpoch);
  final buf = new StringBuffer();

  for (var x = 0; x < length; x++) {
    buf.write(chars[rnd.nextInt(chars.length)]);
  }
  return buf.toString();
}

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

1 回复

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


danisoft_utils 是一个 Flutter 实用工具插件,旨在为开发者提供一系列常用的功能和工具,以简化开发过程并提高效率。以下是如何使用 danisoft_utils 插件的一些基本步骤和示例。

1. 添加依赖

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

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

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

2. 导入包

在你的 Dart 文件中导入 danisoft_utils 包:

import 'package:danisoft_utils/danisoft_utils.dart';

3. 使用工具函数

danisoft_utils 提供了多种实用工具函数,以下是一些常见的用法示例:

3.1 字符串工具

void main() {
  String str = "  Hello, World!  ";

  // 去除字符串两端的空格
  String trimmedStr = StringUtils.trim(str);
  print(trimmedStr); // 输出: "Hello, World!"

  // 将字符串转换为驼峰命名
  String camelCaseStr = StringUtils.toCamelCase("hello_world");
  print(camelCaseStr); // 输出: "helloWorld"
}

3.2 日期工具

void main() {
  DateTime now = DateTime.now();

  // 格式化日期
  String formattedDate = DateUtils.formatDate(now, "yyyy-MM-dd");
  print(formattedDate); // 输出: "2023-10-05"

  // 获取当前时间戳
  int timestamp = DateUtils.getTimestamp();
  print(timestamp); // 输出: 1696521600 (示例)
}

3.3 网络工具

void main() async {
  // 检查网络连接
  bool isConnected = await NetworkUtils.isConnected();
  print(isConnected); // 输出: true 或 false

  // 获取当前设备的IP地址
  String ipAddress = await NetworkUtils.getIPAddress();
  print(ipAddress); // 输出: "192.168.1.1"
}

3.4 文件工具

void main() async {
  // 读取文件内容
  String fileContent = await FileUtils.readFile("path/to/file.txt");
  print(fileContent);

  // 写入文件内容
  await FileUtils.writeFile("path/to/file.txt", "Hello, World!");
}

3.5 加密工具

void main() {
  String originalText = "Hello, World!";

  // MD5 加密
  String md5Hash = EncryptionUtils.md5(originalText);
  print(md5Hash); // 输出: "ed076287532e86365e841e92bfc50d8c"

  // SHA-256 加密
  String sha256Hash = EncryptionUtils.sha256(originalText);
  print(sha256Hash); // 输出: "dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f"
}
回到顶部