Flutter类型安全转换插件safe_cast的使用

Flutter类型安全转换插件safe_cast的使用

DIG Dart Safe Cast

Build Status Pub Pub Score License
  • 简单的语法
  • 减少样板代码

使用

import 'package:safe_cast/safe_cast.dart';

// 可能为null的实例
Fruit? fruit = Cast.asNullable<Fruit>(maybeFruit);

// 如果需要一个非null的实例
Fruit fruit = SafeCast.as<Fruit>(maybeFruit, ifNull: () => availableFruit());

安全转换的优势

安全转换在链式操作中特别有效。

CuttedFruit? cutted = maybeFruit is Fruit ? maybeFruit.cut(fruitCutter) : null;
// 相当于
CuttedFruit? cutted = Cast.asNullable<Fruit>(maybeFruit)?.cut(fruitCutter);

示例代码

以下是一个完整的示例代码,展示了如何使用 safe_cast 插件进行类型安全转换:

import 'dart:math';

import 'package:safe_cast/safe_cast.dart';

// 水果抽象类
abstract class Fruit {}

// 苹果类
class Apple extends Fruit {}

// 香蕉类
class Banana extends Fruit {}

// 汽车类
class Car {}

// 随机返回一个对象
dynamic _randomObject() => switch (Random().nextInt(3)) {
      0 => Apple(),
      1 => Banana(),
      _ => Car(),
    };

void main() {
  // 获取随机对象
  dynamic object = _randomObject();

  // 尝试将对象转换为水果类型
  final fruit = Cast.asNullable<Fruit>(object);
  
  // 如果对象是水果,则打印吃水果的信息
  if (fruit != null) {
    print('Eat fruit $fruit');
  } else {
    // 如果对象不是水果,则尝试将其转换为汽车类型
    final car = Cast.as<Car>(object);
    print('Driving a $car');
  }
}

更多关于Flutter类型安全转换插件safe_cast的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter类型安全转换插件safe_cast的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter开发中,类型安全转换是一个常见的需求。为了避免在类型转换时出现运行时错误,可以使用 safe_cast 插件。safe_cast 提供了一种安全的方式来转换类型,如果转换失败,它会返回 null 或者一个默认值,而不是抛出异常。

安装 safe_cast

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

dependencies:
  safe_cast: ^2.0.0

然后运行 flutter pub get 来安装依赖。

使用 safe_cast

safe_cast 提供了几种方法来安全地进行类型转换。

1. safeCast<T>

safeCast<T> 是最常用的方法,它尝试将对象转换为指定类型 T。如果转换失败,则返回 null

import 'package:safe_cast/safe_cast.dart';

void main() {
  dynamic value = '123';

  // 尝试将 value 转换为 int
  int? intValue = safeCast<int>(value);

  print(intValue); // 输出: null (因为 '123' 是 String 类型,无法直接转换为 int)
}

2. safeCastAs<T>

safeCastAs<T>safeCast<T> 类似,但它允许你指定一个默认值,如果转换失败,则返回这个默认值。

import 'package:safe_cast/safe_cast.dart';

void main() {
  dynamic value = '123';

  // 尝试将 value 转换为 int,如果失败则返回 0
  int intValue = safeCastAs<int>(value, defaultValue: 0);

  print(intValue); // 输出: 0
}

3. safeCastList<T>

safeCastList<T> 用于将列表中的元素转换为指定类型 T。如果某个元素转换失败,则跳过该元素。

import 'package:safe_cast/safe_cast.dart';

void main() {
  dynamic value = ['123', 456, '789'];

  // 尝试将列表中的元素转换为 int
  List<int> intList = safeCastList<int>(value);

  print(intList); // 输出: [456]
}

4. safeCastMap<K, V>

safeCastMap<K, V> 用于将 Map 中的键和值转换为指定类型 KV。如果某个键或值转换失败,则跳过该键值对。

import 'package:safe_cast/safe_cast.dart';

void main() {
  dynamic value = {'a': '123', 'b': 456, 'c': '789'};

  // 尝试将 Map 中的值转换为 int
  Map<String, int> intMap = safeCastMap<String, int>(value);

  print(intMap); // 输出: {'b': 456}
}
回到顶部