以下内容参考《Flutter中文开发者社区》和《Flutter实战·第二版》,仅为个人学习、熟悉Flutter,不同版本可能有稍微不一样。
环境
///
/// 例子来源:
/// Widgets 介绍:https://flutter.cn/docs/development/ui/widgets-intro
/// 《Flutter实战·第二版》:https://book.flutterchina.club/chapter2/flutter_widget_intro.html
///
/// 环境:
/// Flutter 3.10.1 • channel stable • https://github.com/flutter/flutter.git
/// Framework • revision d3d8effc68 (7 days ago) • 2023-05-16 17:59:05 -0700
/// Engine • revision b4fb11214d
/// Tools • Dart 3.0.1 • DevTools 2.23.1
///
概念
-
Flutter
中万物皆为Widget
-
Widget
类本身是一个抽象类,其中最核心的就是定义了createElement()
接口 - 继承
StatelessWidget
或StatefulWidget
来间接继承widget
类来实现
StatelessWidget
用于不需要维护状态的场景,它通常在build
方法中通过嵌套其他widget
来构建UI,在构建过程中会递归的构建其嵌套的widget
。
如果widget
需要接收子widget
,那么child
: T()或children
: <T>[]参数通常应被放在参数列表的最后。
StatefulWidget
StatefulWidget
类中添加了一个新的接口createState()
。
createState()
用于创建和StatefulWidget
相关的状态,它在StatefulWidget
的生命周期中可能会被多次调用。
State
一个 StatefulWidget 类会对应一个 State 类,State 中的保存的状态信息可以:
- 在 widget 构建时可以被同步读取。
- 在 widget 生命周期中可以被改变,当State被改变时,可以手动调用其
setState()
方法通知Flutter 框架状态发生改变,Flutter 框架在收到消息后,会重新调用其build方法重新构建 widget 树,从而达到更新UI的目的。
State 中有两个常用属性:
-
widget
,它表示与该 State 实例关联的widget
实例,由Flutter 框架动态设置。比如:默认计算器中_MyHomePageState设置标题,获取的就是MyHomePage的title属性。
appBar: AppBar(
title: Text(widget.title),
)
-
context
。StatefulWidget对应的 BuildContext。
State生命周期
-
initState
:当 widget 第一次插入到 widget 树时会被调用,对于每一个State对象,Flutter 框架只会调用一次该回调,所以,通常在该回调中做一些一次性的操作,如状态初始化、订阅子树的事件通知等。不能在该回调中调用BuildContext.dependOnInheritedWidgetOfExactType
(该方法用于在 widget 树上获取离当前 widget 最近的一个父级InheritedWidget
,原因是在初始化完成后, widget 树中的InheritFrom widget
也可能会发生变化,所以正确的做法应该在在build()
方法或didChangeDependencies()
中调用它。 -
didChangeDependencies()
:当State对象的依赖发生变化时会被调用;需要注意,组件第一次被创建后挂载的时候(包括重创建)对应的didChangeDependencies
也会被调用。 -
build()
:用于构建 widget 子树的,会在如下场景被调用:- 在调用
initState()
之后。 - 在调用
didUpdateWidget()
之后。 - 在调用
setState()
之后。 - 在调用
didChangeDependencies()
之后。 - 在State对象从树中一个位置移除后(会调用deactivate)又重新插入到树的其他位置之后。
- 在调用
-
reassemble()
:此回调是专门为了开发调试而提供的,在热重载(hot reload)时会被调用,此回调在Release模式下永远不会被调用。 -
didUpdateWidget ()
:在 widget 重新构建时,Flutter 框架会调用widget.canUpdate
来检测 widget 树中同一位置的新旧节点,然后决定是否需要更新,如果widget.canUpdate
返回true则会调用此回调。正如之前所述,widget.canUpdate
会在新旧 widget 的key
和runtimeType
同时相等时会返回true,也就是说在在新旧 widget 的key
和runtimeType
同时相等时didUpdateWidget()
就会被调用。 -
deactivate()
:当 State 对象从树中被移除时,会调用此回调。在一些场景下,Flutter 框架会将 State 对象重新插到树中,如包含此 State 对象的子树在树的一个位置移动到另一个位置时(可以通过GlobalKey 来实现)。如果移除后没有重新插入到树中则紧接着会调用dispose()
方法。 -
dispose()
:当 State 对象从树中被永久移除时调用;通常在此回调中释放资源。
![](https://img.haomeiwen.com/i1673404/11c3131b78fc27bd.png)
代码
void main() {
runApp(const MaterialApp(
title: "Shopping App",
home: ShoppingList(
products: [
Product(name: "Eggs"),
Product(name: "Flour"),
Product(name: "Chocolate chips"),
]),
));
//runApp(const MaterialApp(home: Scaffold(body: Center(child: Counter2()))));
//runApp(const MaterialApp(home: Scaffold(body: Center(child: Counter()))));
//runApp(const MaterialApp(home: Scaffold(body: Center(child: MyButton()))));
//runApp(const MaterialApp(title: "Flutter Tutorial", home: TutorialHome(),));
//runApp(const MaterialApp(title: "My App", home: SafeArea(child: MyScaffold())));
//runApp(const Center(child: Text("Hello, world!", textDirection: TextDirection.ltr)));
//runApp(const MyApp());
}
class Product {
const Product({required this.name});
final String name;
}
typedef CartChangedCallback = Function(Product product, bool inCart);
class ShoppingListItem extends StatelessWidget {
ShoppingListItem({
required this.product,
required this.inCart,
required this.onCartChanged,
}) : super (key: ObjectKey(product));
final Product product;
final bool inCart;
final CartChangedCallback onCartChanged;
Color _getColor(BuildContext context) {
return inCart ? Colors.black54 : Theme.of(context).primaryColor;
}
TextStyle? _getTextStyle(BuildContext context) {
if (!inCart) return null;
return const TextStyle(color: Colors.black54, decoration: TextDecoration.lineThrough);
}
@override
Widget build(BuildContext context) {
return ListTile(
onTap: () {
onCartChanged(product, inCart);
},
leading: CircleAvatar(
backgroundColor: _getColor(context),
child: Text(product.name[0]),
),
title: Text(product.name, style: _getTextStyle(context)),
);
}
}
class ShoppingList extends StatefulWidget {
const ShoppingList({required this.products, super.key});
final List<Product> products;
@override
State<ShoppingList> createState() => _ShoppingListState();
}
class _ShoppingListState extends State<ShoppingList> {
final _shoppingCart = <Product> {};
void _handleCartChanged(Product product, bool inCart) {
setState(() {
if (!inCart) {
_shoppingCart.add(product);
} else {
_shoppingCart.remove(product);
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Shopping List"),
),
body: ListView(
padding: const EdgeInsets.symmetric(vertical: 8),
children: widget.products.map((product) {
return ShoppingListItem(product: product,
inCart: _shoppingCart.contains(product),
onCartChanged: _handleCartChanged);
}).toList(),
),
);
}
}
////////////////////////////////////
////////////////////////////////////
////////////////////////////////////
//展示用StatelessWidget
class CounterDisplay extends StatelessWidget {
const CounterDisplay({required this.count, super.key});
final int count;
@override
Widget build(BuildContext context) {
return Text("Count: $count");
}
}
class CounterIncrementor extends StatelessWidget {
const CounterIncrementor({required this.onPressed, super.key});
final VoidCallback onPressed;
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: onPressed,
child: const Text("Add2"));
}
}
class Counter2 extends StatefulWidget {
const Counter2({super.key});
@override
State<Counter2> createState() => _CounterState2();
}
class _CounterState2 extends State<Counter2> {
int _counter = 0;
void _increment() {
setState(() {
++_counter;
});
}
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
CounterIncrementor(onPressed: _increment),
const SizedBox(width: 20),
CounterDisplay(count: _counter),
],
);
}
}
////////////////////////////////////
////////////////////////////////////
////////////////////////////////////
class Counter extends StatefulWidget {
const Counter({super.key});
@override
State<Counter> createState() => _CounterState();
}
class _CounterState extends State<Counter> {
int _counter = 0;
void _increment() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(onPressed: _increment, child: const Text("Add")),
const SizedBox(width: 20),
Text("counter $_counter"),
],
);
}
}
////////////////////////////////////
////////////////////////////////////
////////////////////////////////////
class MyButton extends StatelessWidget {
const MyButton({super.key});
@override
Widget build(BuildContext context) {
return GestureDetector( //手势
onTap: (){
print("MyButton was tapped!");
},
child: Container( //矩形
height: 50,
padding: const EdgeInsets.all(8),
margin: const EdgeInsets.symmetric(horizontal: 20),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
color: Colors.green[500],
),
child: const Center(child: Text(
"点我鸭",
style: TextStyle(color: Colors.white, fontSize: 20),
),),
),
);
}
}
////////////////////////////////////
////////////////////////////////////
////////////////////////////////////
class TutorialHome extends StatelessWidget {
const TutorialHome({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: const IconButton(
icon: Icon(Icons.menu),
tooltip: "Navigation title",
onPressed: null,
),
title: const Text("Bar Title"),
actions: const [
IconButton(onPressed: null, icon: Icon(Icons.search), tooltip: "Search",),
],
shadowColor: Colors.red,
),
body: const Center(child: Text("Hello world!"),),
floatingActionButton: const FloatingActionButton(
onPressed: null,
tooltip: "Add",
child: Icon(Icons.add),
),
);
}
}
////////////////////////////////////
////////////////////////////////////
////////////////////////////////////
class MyAppBar extends StatelessWidget {
const MyAppBar({required this.title, super.key});
final Widget title;
@override
Widget build(BuildContext context) {
return Container( //高 56 独立像素,左右内边距 8 像素的 Container
height: 56.0, //in logical pixels
padding: const EdgeInsets.symmetric(horizontal: 8.0),
decoration: BoxDecoration(color: Colors.blue[500]), //Row is a horizontal, linear layout.
child: Row( //以 Row 布局来组织它的子元素
children: [
const IconButton(
onPressed: null,
icon: Icon(Icons.menu),
tooltip: "Navigation menu",
),
Expanded(child: title), //title widget,扩展以填充其它子 widget 未使用的可用空间
const IconButton(onPressed: null,
icon: Icon(Icons.search),
tooltip: "Search",
),
],
),
);
}
}
class MyScaffold extends StatelessWidget {
const MyScaffold({super.key});
@override
Widget build(BuildContext context) {
return Material(
child: Column( //子 widget 组织在垂直列中
children: [
MyAppBar(
title: Center(
child: Text(
"Example title",
style: Theme.of(context).primaryTextTheme.titleLarge),
),
),
const Expanded(
child: Center(
child: Text("Hello, world")),
),
],
),
);
}
}
![](https://img.haomeiwen.com/i1673404/063be62f22088f7b.png)
![](https://img.haomeiwen.com/i1673404/26b51f28176bd245.png)
![](https://img.haomeiwen.com/i1673404/260398f781876060.png)
网友评论