Flutter、JetpackCompose 和 Swift UI
移动端
Flutter、JetpackCompose 和 Swift UI
在Android/iOS原生应用的开发中,“使用声明式UI的UI框架”(简称为声明式UI框架)即将出现。这一趋势始于 React 的想法和使用它的 Flutter 和 React Native 等多平台框架,现在它被整合到 Android 上的 Jetpack Compose、iOS 上的 Swift UI,以及现在的各个平台。
声明式 UI 框架让您可以比传统的过程式方法更直观地编写 UI,并且通过采用它,您可以更有效地构建 View。
Flutter 2.8.0
垂直排列文本
Flutter
class ColumnPatternWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Column(children: [
Text('Hello,'),
Text('World!'),
]);
}
}
Jetpack Compose
@Composable
fun ColumnPattern() {
Column {
BasicText(text = "Hello,")
BasicText(text = "World!")
}
}
SwiftUI
struct ColumnPattern: View {
@ViewBuilder
public var body: some View {
VStack {
Text("Hello,")
Text("World!")
}
}
}
数字增加
Flutter
class Counter with ChangeNotifier {
int value = 0;
increment() {
value++;
notifyListeners();
}
}
class ProviderUpdatePatternWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider<Counter>.value(
value: Counter(),
child: ButtonAndText(),
);
}
}
class ButtonAndText extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Column(children: [
Text(context.select((Counter counter) => counter.value.toString())),
FlatButton(
onPressed: () => context.read<Counter>().increment(),
child: Text('increment'),
),
]);
}
}
Jetpack Compose
@Composable
fun UpdatePattern() {
val count = remember { mutableStateOf(0) }
Column {
BasicText(text = count.value.toString())
Button(onClick = { count.value++ }) {
BasicText(text = "increment")
}
}
}
SwiftUI
struct UpdatePattern: View {
@State var count: Int = 0
@ViewBuilder
public var body: some View {
VStack {
Text("\(count)")
Button("increment") { count += 1 }
}
}
}