1) 什么是Widget?
2) Widget与View的异同?
3)什么是有状态的Widget?无状态的Widget?
4) 响应式编程和声明式编程的特点和区别?
一、什么是响应式编程?
Flutter使用的是声明式UI。
1.1 命令式UI
从 Win32 到 Web 再到 Android 和 iOS,框架通常使用一种命令式的编程风格来完成 UI 编程。这可能是你最熟悉的风格——手动构建一个全功能的 UI 实例,比如一个 UIView 或其他类似的内容,在随后 UI 发生变化时,使用方法或 Setter 修改它。
简而言之:发送命令-变更UI(结果),侧重每一个变化的步骤。
1.2 声明式UI
声明式UI,采用状态的思想,通过控制不同的状态下展示不同的UI。
开发者定义界面的各种状态,以及这些状态如何映射到 UI 的展现上。
1.3 声明式UI优缺点
优点:
简洁性: 代码通常更简洁,因为只需声明想要的结果。
可维护性: 更新 UI 的状态更简单,不需要直接操作 DOM 或视图元素。
可预测性: 由于界面是根据状态自动渲染的,UI 的状态更加可预测。
缺点:
性能: 在某些情况下,性能可能会受到影响,因为框架需要跟踪状态变化并重新渲染 UI。
学习曲线: 对于习惯了命令式编程的开发者来说,理解声明式编程可能需要时间。
1.4 对比总结
编程范式: 声明式 UI 侧重于“什么”(描述最终状态),而命令式 UI 侧重于“如何”(具体步骤)。
开发效率和可维护性: 声明式 UI 通常提供了更高的开发效率和可维护性,特别是在复杂应用中。
性能和控制: 命令式 UI 在某些情况下可能提供更好的性能和更精细的控制,但代价是增加了开发的复杂性。(声明式UI:重绘-->命令式UI:局部刷新)
二、什么是Widget?
Widget是Flutter声明和构建UI的方式(元素)。类似安卓的View。
安卓生成的视图View构成ViewRoot树。Widget构成的UI生成一个Widget树。
2.1 Widget与View的差异
2.1.1 生命周期不同
widget 有着不一样的生命周期:它们是不可变的,一旦需要变化则生命周期终止。任何时候 widget 或它们的状态变化时, Flutter 框架都会创建一个新的 widget 树的实例。对比来看,一个 Android View 只会绘制一次,除非调用 invalidate
才会重绘。
2.1.2 Widget特性
- Flutter 的 widget 很轻量,部分原因在于它们的不可变性。因为它们本身既非视图,也不会直接绘制任何内容,而是 UI 及其底层创建真正视图对象的语义的描述。
- Flutter 支持 Material Components 库。它提供实现了 Material Design 设计规范 的 widgets。 Material Design 是一套 为所有平台优化 (包括 iOS)的灵活的设计系统。
- Flutter 非常灵活、有表达能力,它可以实现任何设计语言。例如,在 iOS 平台上,你可以使用 Cupertino widgets 创建 Apple 的 iOS 设计语言 风格的界面。
2.2 Widget更新
从上可知,View支持局部更新,可以直接操作更新View。但是Widget是不可变的,可以在状态变化时,重绘Widget树。
2.2.1 有状态和无状态
根据Widget是否需要根据状态更新,分为有状态和无状态。
StatelessWidget
:没有状态信息的Widget。StatelessWidget
用于你描述的用户界面的一部分不依赖于除了对象中的配置信息以外的任何东西的场景。例如: Text
StatefulWidget:有状态的Widget。可以根据 HTTP 请求返回的数据或者用户的交互来动态地更新界面。
区别:
无状态和有状态的 Widget 本质上是行为一致的。它们每一帧都会重建,不同之处在于 StatefulWidget
有一个跨帧存储和恢复状态数据的 State
对象。
2.2.2 如何更新无状态Widget属性
例如一个Text, 想动态更新Text的文本。
Text(
'I like Flutter very much!',
style: TextStyle(fontWeight: FontWeight.bold),
);
应该怎么处理?
1)要实现动态更新Text, 必须使用StatefulWidget。将Text嵌套到一个 StatefulWidget
中;
2)创建一个状态State,存储文本内容 textToShow,定义状态变更方法;
3) 按钮点击的时候,更新 State 中存储的文本内容
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo', // 标题
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
// 文本内容
String textToShow = 'I love Flutter!';
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
// 更新文本内容
if (_counter % 4 == 0) {
textToShow = 'I Study Flutter now';
} else if (_counter % 4 == 1) {
textToShow = 'Flutter is so interesting';
} else if (_counter % 4 == 2) {
textToShow = 'I love it more';
} else {
textToShow = 'I learn it more funny';
}
});
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
// 新增一个自定义的Text(在State中存储)
Text(textToShow)
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
2.3 Widget布局
Widget通过调整属性来改变布局样式,与Android View的布局文件不同。
2.4 如果在布局树中添加或者删除组件
定义Widget显示的逻辑,例如定义一个布尔变量,控制显示不同的Widget。
Widget树重绘的时候就会显示对应的视图。
2.5 Widget动画
Android View系统中,存在渐变动画,帧动画,属性动画。调用View.animate()播放动画。
Widget中怎么实现动画呢?
在 Flutter 里,则使用动画库,通过将 Widget 嵌入一个动画 Widget 的方式实现 Widget 的动画效果。
import 'package:flutter/material.dart';
void main() {
runApp(const FadeAppTest());
}
class FadeAppTest extends StatelessWidget {
const FadeAppTest({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Fade Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
),
home: const MyFadeTest(title: 'Fade Demo'),
);
}
}
class MyFadeTest extends StatefulWidget {
const MyFadeTest({super.key, required this.title});
final String title;
@override
State<MyFadeTest> createState() => _MyFadeTest();
}
class _MyFadeTest extends State<MyFadeTest> with TickerProviderStateMixin {
late AnimationController controller;
late CurvedAnimation curve;
@override
void initState() {
super.initState();
controller = AnimationController(
duration: const Duration(milliseconds: 2000),
vsync: this,
);
curve = CurvedAnimation(
parent: controller,
curve: Curves.easeIn,
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: FadeTransition(
opacity: curve,
child: const FlutterLogo(
size: 100,
),
),
),
floatingActionButton: FloatingActionButton(
tooltip: 'Fade',
onPressed: () {
controller.forward();
},
child: const Icon(Icons.brush),
),
);
}
}
2.6 如何使用 Canvas 进行绘制?
Flutter 有两个帮助你用画布 (canvas) 进行绘制的类: CustomPaint
和 CustomPainter
,后者可以实现自定义的绘制算法。
2.7 如何创建自定义 Widget?
在 Flutter 中,通过 组合 更小的 Widget 来创建自定义 Widget(而不是继承它们)。这和 Android 中实现一个自定义的 ViewGroup
有些类似,所有的构建 UI 的模块代码都已存在,不过由你提供不同的行为—例如,自定义布局 (layout) 逻辑。
采用组合的思想,Widget都切分成特别细的组件,通过组合得到自定义的Widget。
class CustomButton extends StatelessWidget {
final String label;
const CustomButton(this.label, {super.key});
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () {},
child: Text(label),
);
}
}