Flutter条件切换插件switch_when的使用
Flutter条件切换插件switch_when的使用
Getting Started
Add dependency
在pubspec.yaml
文件中添加依赖:
dependencies:
switch_when: ^0.0.1 #请使用pub上的最新版本
Use Library
导入库
在需要使用该库的地方导入包:
import 'package:switch_when/switch_when.dart';
使用函数
根据不同的情况使用不同的方法。对于一般的情况,可以使用when
或whenValue
方法。如果需要返回结果为非空安全类型,可以使用whenSafe
或whenValueSafe
方法。
示例代码:
@override
void initState() {
_curtainAnimationImage = TweenImageWidget(
ImagesEntry(1, 20, "equipmentcontrol_pic_curtain%s".toAssetImg()),
durationMilliseconds: 5000,
repeat: false,
);
super.initState();
}
函数
// 不安全
T? whenString<T>(String value, Map<String, ValueGetter<T>> conditionMap)
T? whenInt<T>(int value, Map<int, ValueGetter<T>> conditionMap)
T? whenDouble<T>(double value, Map<double, ValueGetter<T>> conditionMap)
T? whenBool<T>(bool value, List<Tuple2<bool, ValueGetter<T>>> conditionList)
T? whenValue<V, T>(V value, Map<V, ValueGetter<T>> conditionMap)
T? when<T>(Map<bool, ValueGetter<T>> conditionMap)
T? whenTrue<T>(Map<ValueGetter<bool>, ValueGetter<T>> conditionMap)
// 安全
T whenStringSafe<T>(String value, Map<String, ValueGetter<T>> conditionMap, {ValueGetter<T>? defaultValue})
T whenIntSafe<T>(int value, Map<int, ValueGetter<T>> conditionMap, {ValueGetter<T>? defaultValue})
T whenDoubleSafe<T>(double value, Map<double, ValueGetter<T>> conditionMap, {ValueGetter<T>? defaultValue})
T? whenBoolSafe<T>(bool value, List<Tuple2<bool, ValueGetter<T>>> conditionList, {ValueGetter<T>? defaultValue})
T whenValueSafe<V, T>(V value, Map<V, ValueGetter<T>> conditionMap, {ValueGetter<T>? defaultValue})
T whenSafe<T>(Map<bool, ValueGetter<T>> conditionMap, {ValueGetter<T>? defaultValue})
T whenTrueSafe<T>(Map<ValueGetter<bool>, ValueGetter<T>> conditionMap, {ValueGetter<T>? defaultValue})
示例代码
T? whenString
用于替换switch
方法,因为某些场景下Case
表达式必须为常量;
如果value
存在于conditionMap
的keys
中,则执行其对应的ValueGetter
方法。
示例:
int? index = whenString<int>("banana🍌", {
"water" + "melon": () {
return 1;
},
"apple": () {
return 2;
},
"orange": () {
return 3;
},
"banana" + "🍌": () {
return 4;
},
"grape": () {
return 5;
},
});
T? whenInt
用于替换switch
方法,因为某些场景下Case
表达式必须为常量;
如果value
存在于conditionMap
的keys
中,则执行其对应的ValueGetter
方法。
示例:
String? status = whenInt<String>(1, {
1: () {
return "good";
},
1 + 1: () {
return "nice";
},
int.parse("3"): () {
return "better";
},
});
T? whenDouble
用于替换switch
方法,因为某些场景下Case
表达式必须为常量;
如果value
存在于conditionMap
的keys
中,则执行其对应的ValueGetter
方法。
示例:
String? status = whenDouble<String>(2.0, {
0.1: () {
return "good";
},
1.0 + 1: () {
return "nice";
},
double.parse("3.2"): () {
return "better";
},
});
T? whenBool
用于替换switch
方法,因为某些场景下Case
表达式必须为常量。
如果value
存在于conditionList
的Tuple2.item1
中,则执行其对应的ValueGetter
方法。
示例:
double? degree = whenBool<double>(false, [
Tuple2(
"is Long String".length > 10,
() {
return 0.0;
},
),
Tuple2(
100 / 10 == 0,
() {
return 1.0;
},
),
Tuple2(
"apple".contains("a"),
() {
return 2.0;
},
),
]);
return degree;
T? whenValue
switch
方法的超级进化版,所有基本类型的值都可以比较,包括List
、Map
、Set
和Iterable
。
只需要value
存在于conditionMap
的keys
中,其对应的ValueGetter
方法将被执行。
示例:
String? kind = whenValue<List, String>(
["apple", "orange"],
{
["cat", "dog"]: () {
return "pets";
},
["apple", "orange"]: () {
return "fruits";
},
["red", "white", "black"]: () {
return "colors";
},
},
);
T? when
Kotlin版本的switch
方法的when
函数。
只要在conditionMap
的keys
中找到第一个为真的值,就会立即执行其对应的ValueGetter
方法并返回相应的值。
如果没有找到,则返回null;如果需要默认值,可以在Map
末尾添加一个键等于true
的MapEntry
。
示例:
String? winner = when<String>({
"Dart is Language".contains("UI"): () {
return "Flutter";
},
"Flutter is UI Framework".contains("UI"): () {
return "Flutter";
},
});
T? whenTrue
Kotlin版本的switch
方法的when
函数,其条件表达式会被计算。
只要在conditionMap
的keys
中出现的第一个执行结果为真,就会立即执行其对应的ValueGetter
方法,并返回相应的值。
如果没有找到,则返回null;如果需要默认值,可以在Map
末尾添加一个键等于true
的MapEntry
。
示例:
String? something = whenTrue<String>({
() {
if (1 + 100 * 1000 < 2000) {
return false;
} else if ("Who is my lovely baby?".length > 10) {
return true;
} else {
return false;
}
}: () {
return "Test OK";
},
() {
return int.tryParse("3.14*") != null;
}: () {
return "PI get";
}
});
Example Demo
testWhenValue() {
String? kind = whenValue<List, String>(
["apple", "orange"],
{
["cat", "dog"]: () {
return "pets";
},
["apple", "orange"]: () {
return "fruits";
},
["red", "white", "black"]: () {
return "colors";
},
},
);
return kind;
}
testWhenString() {
int howManyFruits = 2;
int? index = whenString<int>("banana🍌", {
"water" + "melon".more(): () {
return 1;
},
"apple".more(): () {
return 2;
},
howManyFruits <= 1 ? "orange" : "oranges": () {
return 3;
},
"banana" + "🍌": () {
return 4;
},
"grape": () {
return 5;
},
});
return index;
}
testWhen() {
String? winner = when<String>({
"Dart is Language".contains("UI"): () {
return "Flutter";
},
"Flutter is UI Framework".contains("UI"): () {
return "Flutter";
},
});
return winner;
}
testWhenDoubleSafe() {
String status = whenDoubleSafe<String>(
2.1,
{
0.1: () {
return "good";
},
1.0 + 1: () {
return "nice";
},
double.parse("3.2"): () {
return "better";
},
},
defaultValue: () => "other",
);
expect(status, "other");
};
更多关于Flutter条件切换插件switch_when的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter条件切换插件switch_when的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,switch_when
是一个用于在 Flutter 中根据条件切换 Widget 的插件。尽管 Flutter 本身已经提供了条件渲染的能力(例如使用 if
或 ternary
运算符),但 switch_when
插件提供了一个更加简洁和可读的方式来处理复杂的条件切换。
下面是一个使用 switch_when
插件的示例代码案例。首先,你需要确保在你的 pubspec.yaml
文件中添加了 switch_when
依赖:
dependencies:
flutter:
sdk: flutter
switch_when: ^x.y.z # 请替换为实际的版本号
然后,运行 flutter pub get
来安装依赖。
接下来是示例代码,展示如何使用 SwitchWhen
组件来根据条件切换不同的 Widget:
import 'package:flutter/material.dart';
import 'package:switch_when/switch_when.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('SwitchWhen Example'),
),
body: Center(
child: ConditionalWidget(),
),
),
);
}
}
class ConditionalWidget extends StatefulWidget {
@override
_ConditionalWidgetState createState() => _ConditionalWidgetState();
}
class _ConditionalWidgetState extends State<ConditionalWidget> {
int _selectedIndex = 0;
void _onItemSelected(int index) {
setState(() {
_selectedIndex = index;
});
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SwitchWhen<int, Widget>(
value: _selectedIndex,
cases: {
0: Text('You selected the first option'),
1: Image.network('https://via.placeholder.com/150'),
2: Center(child: CircularProgressIndicator()),
},
defaultCase: Text('Default case'),
),
SizedBox(height: 20),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: List<Widget>.generate(3, (index) {
return ElevatedButton(
onPressed: () => _onItemSelected(index),
child: Text('Option $index'),
);
}),
),
],
);
}
}
在这个示例中:
- 我们创建了一个
ConditionalWidget
,它是一个有状态的 Widget,用于管理选中的索引_selectedIndex
。 - 使用
SwitchWhen
组件,根据_selectedIndex
的值来切换不同的 Widget。- 当
_selectedIndex
为 0 时,显示Text('You selected the first option')
。 - 当
_selectedIndex
为 1 时,显示一个网络图片。 - 当
_selectedIndex
为 2 时,显示一个CircularProgressIndicator
。 - 如果
_selectedIndex
不匹配上述任何一个值,则显示defaultCase
中的Text('Default case')
。
- 当
- 使用
ElevatedButton
组件来更改_selectedIndex
的值,从而触发SwitchWhen
组件的重新渲染。
这个示例展示了 switch_when
插件的基本用法,你可以根据需要扩展和自定义它。