$switch<TKey, TValue> method

Widget $switch<TKey, TValue>(
  1. ValueListenable<TValue> valueListenable, {
  2. Map<TKey, ValueWidgetBuilder<TValue>>? options,
  3. ValueWidgetBuilder<TValue>? defalut,
  4. Widget? child,
  5. TKey valueToKey(
    1. TValue
    )?,
})

绑定到指定 ValueListenable, 当 valueListenable 值发生变化时, 其值做为 keyoptions 中查找对应 Widget 构建方法, 若未找到则使用 default 构建, 如 defaultnull 则不构建 Widget

如值与 optionskey 类型不同, 可通过指定 valueToKey 进行转换 child 用于向构建方法中传入 Widget

// example
final bp1$ = BindableProperty.$value(initial: 1);
@override
Widget build(BuildContext context) {
  return $switch<String, int>(bp1$,
    options: const {
               "1.": (context, value, child) => Text("$value"),
               "2.": (context, value, child) => Text("2") },
    default: (context, value, child) => Text("default"),
    valueToKey: (value) => "${value}.");
}

Implementation

Widget $switch<TKey, TValue>(ValueListenable<TValue> valueListenable,
        {Map<TKey, ValueWidgetBuilder<TValue>>? options,
        ValueWidgetBuilder<TValue>? defalut,
        Widget? child,
        TKey Function(TValue)? valueToKey}) =>
    (options == null || options.isEmpty)
        ? $build(valueListenable, builder: defalut ?? _, child: child)
        : $select(valueListenable,
            selector: (TValue value) =>
                options[valueToKey != null ? valueToKey(value) : value] ??
                defalut?.call,
            child: child);