option?拆包

87 阅读1分钟

extension LetS on String? {
  String let({String placeholder = '暂无'}) {
    if (this == null || this!.isEmpty) {
      return placeholder;
    } else {
      return this!;
    }
  }

  String get lets => let();
}

extension LetL<E> on List<E>? {
  List<E> let({List<E>? placeholder}) {
    if (this == null) {
      return placeholder ?? [];
    } else {
      return this!;
    }
  }

  List<E> get lets => let();
}

extension LetI on int? {
  int let({int? placeholder}) {
    if (this == null) {
      return placeholder ?? 0;
    } else {
      return this!;
    }
  }

  int get lets => let();
}

extension LetD on double? {
  double let({double? placeholder}) {
    if (this == null) {
      return placeholder ?? 0;
    } else {
      return this!;
    }
  }

  double get lets => let();
}

extension LetN on num? {
  num let({num? placeholder}) {
    if (this == null) {
      return placeholder ?? 0;
    } else {
      return this!;
    }
  }

  num get lets => let();
}

extension LetB on bool? {
  bool let({bool? placeholder}) {
    if (this == null) {
      return placeholder ?? false;
    } else {
      return this!;
    }
  }

  bool get lets => let();
}

extension LetM<K, V> on Map<K, V>? {
  Map<K, V> let({Map<K, V>? placeholder}) {
    if (this == null) {
      return placeholder ?? {};
    } else {
      return this!;
    }
  }

  Map<K, V> get lets => let();
}

T let<T>(T? obj, {T? placeholder}) {
  if (obj is String?) {
    return obj.let(placeholder: placeholder as String) as T;
  }

  if (obj is List?) {
    return obj.let(placeholder: placeholder as List) as T;
  }

  if (obj is int?) {
    return obj.let(placeholder: placeholder as int) as T;
  }

  if (obj is double?) {
    return obj.let(placeholder: placeholder as double) as T;
  }

  if (obj is bool?) {
    return obj.let(placeholder: placeholder as bool) as T;
  }

  if (obj is num?) {
    return obj.let(placeholder: placeholder as num) as T;
  }

  if (obj is Map?) {
    return obj.let(placeholder: placeholder as Map) as T;
  }

  return obj ?? placeholder!;
}


example:


/// 用法一: 通过扩展调用
      String? s;
      print(s.lets.length);
      print(s.let(placeholder: '暂无'));

      List? b;
      print(b?.lets);
      print(b.let(placeholder: []));
      
/// 用法二: 顶层函数调用
      final ss = let(s, placeholder: '暂无');
      print(ss);

      final bb = let(b, placeholder: []);
      print(bb);