介绍

Flutter Widget采用现代响应式框架构建,这是从 React 中获得的灵感,中心思想是用widget构建你的UI。 Widget描述了他们的视图在给定其当前配置和状态时应该看起来像什么。当widget的状态发生变化时,widget会重新构建UI,Flutter会对比前后变化的不同, 以确定底层渲染树从一个状态转换到下一个状态所需的最小更改(译者语:类似于React/Vue中虚拟DOM的diff算法)。

Hello World

一个最简单的Flutter应用程序,只需一个widget即可!如下面示例:将一个widget传给runApp函数即可:

  1. import 'package:flutter/material.dart';
  2. void main() {
  3. runApp(
  4. new Center(
  5. child: new Text(
  6. 'Hello, world!',
  7. textDirection: TextDirection.ltr,
  8. ),
  9. ),
  10. );
  11. }

runApp函数接受给定的Widget并使其成为widget树的根。 在此示例中,widget树由两个widget:Center(及其子widget)和Text组成。框架强制根widget覆盖整个屏幕,这意味着文本“Hello, world”会居中显示在屏幕上。文本显示的方向需要在Text实例中指定,当使用MaterialApp时,文本的方向将自动设定,稍后将进行演示。

在编写应用程序时,通常会创建新的widget,这些widget是无状态的StatelessWidget或者是有状态的StatefulWidget, 具体的选择取决于您的widget是否需要管理一些状态。widget的主要工作是实现一个build函数,用以构建自身。一个widget通常由一些较低级别widget组成。Flutter框架将依次构建这些widget,直到构建到最底层的子widget时,这些最低层的widget通常为RenderObject,它会计算并描述widget的几何形状。

基础 Widget

主要文章: widget概述-布局模型

Flutter有一套丰富、强大的基础widget,其中以下是很常用的:

  • Text:该 widget 可让创建一个带格式的文本。

  • RowColumn: 这些具有弹性空间的布局类Widget可让您在水平(Row)和垂直(Column)方向上创建灵活的布局。其设计是基于web开发中的Flexbox布局模型。

  • Stack: 取代线性布局 (译者语:和Android中的LinearLayout相似),Stack允许子 widget 堆叠, 你可以使用 Positioned 来定位他们相对于Stack的上下左右四条边的位置。Stacks是基于Web开发中的绝度定位(absolute positioning )布局模型设计的。

  • ContainerContainer 可让您创建矩形视觉元素。container 可以装饰为一个BoxDecoration, 如 background、一个边框、或者一个阴影。 Container 也可以具有边距(margins)、填充(padding)和应用于其大小的约束(constraints)。另外, Container可以使用矩阵在三维空间中对其进行变换。

以下是一些简单的Widget,它们可以组合出其它的Widget:

  1. import 'package:flutter/material.dart';
  2. class MyAppBar extends StatelessWidget {
  3. MyAppBar({this.title});
  4. // Widget子类中的字段往往都会定义为"final"
  5. final Widget title;
  6. @override
  7. Widget build(BuildContext context) {
  8. return new Container(
  9. height: 56.0, // 单位是逻辑上的像素(并非真实的像素,类似于浏览器中的像素)
  10. padding: const EdgeInsets.symmetric(horizontal: 8.0),
  11. decoration: new BoxDecoration(color: Colors.blue[500]),
  12. // Row 是水平方向的线性布局(linear layout)
  13. child: new Row(
  14. //列表项的类型是 <Widget>
  15. children: <Widget>[
  16. new IconButton(
  17. icon: new Icon(Icons.menu),
  18. tooltip: 'Navigation menu',
  19. onPressed: null, // null 会禁用 button
  20. ),
  21. // Expanded expands its child to fill the available space.
  22. new Expanded(
  23. child: title,
  24. ),
  25. new IconButton(
  26. icon: new Icon(Icons.search),
  27. tooltip: 'Search',
  28. onPressed: null,
  29. ),
  30. ],
  31. ),
  32. );
  33. }
  34. }
  35. class MyScaffold extends StatelessWidget {
  36. @override
  37. Widget build(BuildContext context) {
  38. // Material 是UI呈现的“一张纸”
  39. return new Material(
  40. // Column is 垂直方向的线性布局.
  41. child: new Column(
  42. children: <Widget>[
  43. new MyAppBar(
  44. title: new Text(
  45. 'Example title',
  46. style: Theme.of(context).primaryTextTheme.title,
  47. ),
  48. ),
  49. new Expanded(
  50. child: new Center(
  51. child: new Text('Hello, world!'),
  52. ),
  53. ),
  54. ],
  55. ),
  56. );
  57. }
  58. }
  59. void main() {
  60. runApp(new MaterialApp(
  61. title: 'My app', // used by the OS task switcher
  62. home: new MyScaffold(),
  63. ));
  64. }

请确保在pubspec.yaml文件中,将flutter的值设置为:uses-material-design: true。这允许我们可以使用一组预定义Material icons

  1. name: my_app
  2. flutter:
  3. uses-material-design: true

为了继承主题数据,widget需要位于MaterialApp内才能正常显示, 因此我们使用MaterialApp来运行该应用。

MyAppBar中创建一个Container,高度为56像素(像素单位独立于设备,为逻辑像素),其左侧和右侧均有8像素的填充。在容器内部, MyAppBar使用Row 布局来排列其子项。 中间的title widget被标记为Expanded, ,这意味着它会填充尚未被其他子项占用的的剩余可用空间。Expanded可以拥有多个children, 然后使用flex参数来确定他们占用剩余空间的比例。

MyScaffold 通过一个Column widget,在垂直方向排列其子项。在Column的顶部,放置了一个MyAppBar实例,将一个Text widget作为其标题传递给应用程序栏。将widget作为参数传递给其他widget是一种强大的技术,可以让您创建各种复杂的widget。最后,MyScaffold使用了一个Expanded来填充剩余的空间,正中间包含一条message。

使用 Material 组件

主要文章: Widgets 总览 - Material 组件

Flutter提供了许多widgets,可帮助您构建遵循Material Design的应用程序。Material应用程序以MaterialApp widget开始, 该widget在应用程序的根部创建了一些有用的widget,其中包括一个Navigator, 它管理由字符串标识的Widget栈(即页面路由栈)。Navigator可以让您的应用程序在页面之间的平滑的过渡。 是否使用MaterialApp完全是可选的,但是使用它是一个很好的做法。

  1. import 'package:flutter/material.dart';
  2. void main() {
  3. runApp(new MaterialApp(
  4. title: 'Flutter Tutorial',
  5. home: new TutorialHome(),
  6. ));
  7. }
  8. class TutorialHome extends StatelessWidget {
  9. @override
  10. Widget build(BuildContext context) {
  11. //Scaffold是Material中主要的布局组件.
  12. return new Scaffold(
  13. appBar: new AppBar(
  14. leading: new IconButton(
  15. icon: new Icon(Icons.menu),
  16. tooltip: 'Navigation menu',
  17. onPressed: null,
  18. ),
  19. title: new Text('Example title'),
  20. actions: <Widget>[
  21. new IconButton(
  22. icon: new Icon(Icons.search),
  23. tooltip: 'Search',
  24. onPressed: null,
  25. ),
  26. ],
  27. ),
  28. //body占屏幕的大部分
  29. body: new Center(
  30. child: new Text('Hello, world!'),
  31. ),
  32. floatingActionButton: new FloatingActionButton(
  33. tooltip: 'Add', // used by assistive technologies
  34. child: new Icon(Icons.add),
  35. onPressed: null,
  36. ),
  37. );
  38. }
  39. }

现在我们已经从MyAppBarMyScaffold切换到了AppBarScaffold widget, 我们的应用程序现在看起来已经有一些“Material”了!例如,应用栏有一个阴影,标题文本会自动继承正确的样式。我们还添加了一个浮动操作按钮,以便进行相应的操作处理。

请注意,我们再次将widget作为参数传递给其他widget。该 Scaffold widget 需要许多不同的widget的作为命名参数,其中的每一个被放置在Scaffold布局中相应的位置。 同样,AppBar 中,我们给参数leading、actions、title分别传一个widget。 这种模式在整个框架中会经常出现,这也可能是您在设计自己的widget时会考虑到一点。

处理手势

主要文章: Flutter中的手势

大多数应用程序包括某种形式与系统的交互。构建交互式应用程序的第一步是检测输入手势。让我们通过创建一个简单的按钮来了解它的工作原理:

  1. class MyButton extends StatelessWidget {
  2. @override
  3. Widget build(BuildContext context) {
  4. return new GestureDetector(
  5. onTap: () {
  6. print('MyButton was tapped!');
  7. },
  8. child: new Container(
  9. height: 36.0,
  10. padding: const EdgeInsets.all(8.0),
  11. margin: const EdgeInsets.symmetric(horizontal: 8.0),
  12. decoration: new BoxDecoration(
  13. borderRadius: new BorderRadius.circular(5.0),
  14. color: Colors.lightGreen[500],
  15. ),
  16. child: new Center(
  17. child: new Text('Engage'),
  18. ),
  19. ),
  20. );
  21. }
  22. }

GestureDetector widget并不具有显示效果,而是检测由用户做出的手势。 当用户点击Container时, GestureDetector会调用它的onTap回调, 在回调中,将消息打印到控制台。您可以使用GestureDetector来检测各种输入手势,包括点击、拖动和缩放。

许多widget都会使用一个GestureDetector为其他widget提供可选的回调。 例如,IconButtonRaisedButton、 和FloatingActionButton ,它们都有一个onPressed回调,它会在用户点击该widget时被触发。

根据用户输入改变widget

主要文章: StatefulWidget, State.setState

到目前为止,我们只使用了无状态的widget。无状态widget从它们的父widget接收参数, 它们被存储在final型的成员变量中。 当一个widget被要求构建时,它使用这些存储的值作为参数来构建widget。

为了构建更复杂的体验 - 例如,以更有趣的方式对用户输入做出反应 - 应用程序通常会携带一些状态。 Flutter使用StatefulWidgets来满足这种需求。StatefulWidgets是特殊的widget,它知道如何生成State对象,然后用它来保持状态。 思考下面这个简单的例子,其中使用了前面提到RaisedButton

  1. class Counter extends StatefulWidget {
  2. // This class is the configuration for the state. It holds the
  3. // values (in this nothing) provided by the parent and used by the build
  4. // method of the State. Fields in a Widget subclass are always marked "final".
  5. @override
  6. _CounterState createState() => new _CounterState();
  7. }
  8. class _CounterState extends State<Counter> {
  9. int _counter = 0;
  10. void _increment() {
  11. setState(() {
  12. // This call to setState tells the Flutter framework that
  13. // something has changed in this State, which causes it to rerun
  14. // the build method below so that the display can reflect the
  15. // updated values. If we changed _counter without calling
  16. // setState(), then the build method would not be called again,
  17. // and so nothing would appear to happen.
  18. _counter++;
  19. });
  20. }
  21. @override
  22. Widget build(BuildContext context) {
  23. // This method is rerun every time setState is called, for instance
  24. // as done by the _increment method above.
  25. // The Flutter framework has been optimized to make rerunning
  26. // build methods fast, so that you can just rebuild anything that
  27. // needs updating rather than having to individually change
  28. // instances of widgets.
  29. return new Row(
  30. children: <Widget>[
  31. new RaisedButton(
  32. onPressed: _increment,
  33. child: new Text('Increment'),
  34. ),
  35. new Text('Count: $_counter'),
  36. ],
  37. );
  38. }
  39. }

您可能想知道为什么StatefulWidget和State是单独的对象。在Flutter中,这两种类型的对象具有不同的生命周期: Widget是临时对象,用于构建当前状态下的应用程序,而State对象在多次调用build()之间保持不变,允许它们记住信息(状态)。

上面的例子接受用户点击,并在点击时使_counter自增,然后直接在其build方法中使用_counter值。在更复杂的应用程序中,widget结构层次的不同部分可能有不同的职责; 例如,一个widget可能呈现一个复杂的用户界面,其目标是收集特定信息(如日期或位置),而另一个widget可能会使用该信息来更改整体的显示。

在Flutter中,事件流是“向上”传递的,而状态流是“向下”传递的(译者语:这类似于React/Vue中父子组件通信的方式:子widget到父widget是通过事件通信,而父到子是通过状态),重定向这一流程的共同父元素是State。让我们看看这个稍微复杂的例子是如何工作的:

  1. class CounterDisplay extends StatelessWidget {
  2. CounterDisplay({this.count});
  3. final int count;
  4. @override
  5. Widget build(BuildContext context) {
  6. return new Text('Count: $count');
  7. }
  8. }
  9. class CounterIncrementor extends StatelessWidget {
  10. CounterIncrementor({this.onPressed});
  11. final VoidCallback onPressed;
  12. @override
  13. Widget build(BuildContext context) {
  14. return new RaisedButton(
  15. onPressed: onPressed,
  16. child: new Text('Increment'),
  17. );
  18. }
  19. }
  20. class Counter extends StatefulWidget {
  21. @override
  22. _CounterState createState() => new _CounterState();
  23. }
  24. class _CounterState extends State<Counter> {
  25. int _counter = 0;
  26. void _increment() {
  27. setState(() {
  28. ++_counter;
  29. });
  30. }
  31. @override
  32. Widget build(BuildContext context) {
  33. return new Row(children: <Widget>[
  34. new CounterIncrementor(onPressed: _increment),
  35. new CounterDisplay(count: _counter),
  36. ]);
  37. }
  38. }

注意我们是如何创建了两个新的无状态widget的!我们清晰地分离了 显示 计数器(CounterDisplay)和 更改 计数器(CounterIncrementor)的逻辑。 尽管最终效果与前一个示例相同,但责任分离允许将复杂性逻辑封装在各个widget中,同时保持父项的简单性。

整合所有

让我们考虑一个更完整的例子,将上面介绍的概念汇集在一起​​。我们假设一个购物应用程序,该应用程序显示出售的各种产品,并维护一个购物车。 我们先来定义ShoppingListItem

  1. class Product {
  2. const Product({this.name});
  3. final String name;
  4. }
  5. typedef void CartChangedCallback(Product product, bool inCart);
  6. class ShoppingListItem extends StatelessWidget {
  7. ShoppingListItem({Product product, this.inCart, this.onCartChanged})
  8. : product = product,
  9. super(key: new ObjectKey(product));
  10. final Product product;
  11. final bool inCart;
  12. final CartChangedCallback onCartChanged;
  13. Color _getColor(BuildContext context) {
  14. // The theme depends on the BuildContext because different parts of the tree
  15. // can have different themes. The BuildContext indicates where the build is
  16. // taking place and therefore which theme to use.
  17. return inCart ? Colors.black54 : Theme.of(context).primaryColor;
  18. }
  19. TextStyle _getTextStyle(BuildContext context) {
  20. if (!inCart) return null;
  21. return new TextStyle(
  22. color: Colors.black54,
  23. decoration: TextDecoration.lineThrough,
  24. );
  25. }
  26. @override
  27. Widget build(BuildContext context) {
  28. return new ListTile(
  29. onTap: () {
  30. onCartChanged(product, !inCart);
  31. },
  32. leading: new CircleAvatar(
  33. backgroundColor: _getColor(context),
  34. child: new Text(product.name[0]),
  35. ),
  36. title: new Text(product.name, style: _getTextStyle(context)),
  37. );
  38. }
  39. }

ShoppingListItem widget是无状态的。它将其在构造函​​数中接收到的值存储在final成员变量中,然后在build函数中使用它们。 例如,inCart布尔值表示在两种视觉展示效果之间切换:一个使用当前主题的主色,另一个使用灰色。

当用户点击列表项时,widget不会直接修改其inCart的值。相反,widget会调用其父widget给它的onCartChanged回调函数。 此模式可让您在widget层次结构中存储更高的状态,从而使状态持续更长的时间。在极端情况下,存储传给runApp应用程序的widget的状态将在的整个生命周期中持续存在。

当父项收到onCartChanged回调时,父项将更新其内部状态,这将触发父项使用新inCart值重建ShoppingListItem新实例。 虽然父项ShoppingListItem在重建时创建了一个新实例,但该操作开销很小,因为Flutter框架会将新构建的widget与先前构建的widget进行比较,并仅将差异部分应用于底层RenderObject

我们来看看父widget存储可变状态的示例:

  1. class ShoppingList extends StatefulWidget {
  2. ShoppingList({Key key, this.products}) : super(key: key);
  3. final List<Product> products;
  4. // The framework calls createState the first time a widget appears at a given
  5. // location in the tree. If the parent rebuilds and uses the same type of
  6. // widget (with the same key), the framework will re-use the State object
  7. // instead of creating a new State object.
  8. @override
  9. _ShoppingListState createState() => new _ShoppingListState();
  10. }
  11. class _ShoppingListState extends State<ShoppingList> {
  12. Set<Product> _shoppingCart = new Set<Product>();
  13. void _handleCartChanged(Product product, bool inCart) {
  14. setState(() {
  15. // When user changes what is in the cart, we need to change _shoppingCart
  16. // inside a setState call to trigger a rebuild. The framework then calls
  17. // build, below, which updates the visual appearance of the app.
  18. if (inCart)
  19. _shoppingCart.add(product);
  20. else
  21. _shoppingCart.remove(product);
  22. });
  23. }
  24. @override
  25. Widget build(BuildContext context) {
  26. return new Scaffold(
  27. appBar: new AppBar(
  28. title: new Text('Shopping List'),
  29. ),
  30. body: new ListView(
  31. padding: new EdgeInsets.symmetric(vertical: 8.0),
  32. children: widget.products.map((Product product) {
  33. return new ShoppingListItem(
  34. product: product,
  35. inCart: _shoppingCart.contains(product),
  36. onCartChanged: _handleCartChanged,
  37. );
  38. }).toList(),
  39. ),
  40. );
  41. }
  42. }
  43. void main() {
  44. runApp(new MaterialApp(
  45. title: 'Shopping App',
  46. home: new ShoppingList(
  47. products: <Product>[
  48. new Product(name: 'Eggs'),
  49. new Product(name: 'Flour'),
  50. new Product(name: 'Chocolate chips'),
  51. ],
  52. ),
  53. ));
  54. }

ShoppingList类继承自StatefulWidget,这意味着这个widget可以存储状态。 当ShoppingList首次插入到树中时,框架会调用其 createState 函数以创建一个新的_ShoppingListState实例来与该树中的相应位置关联(请注意,我们通常命名State子类时带一个下划线,这表示其是私有的)。 当这个widget的父级重建时,父级将创建一个新的ShoppingList实例,但是Flutter框架将重用已经在树中的_ShoppingListState实例,而不是再次调用createState创建一个新的。

要访问当前ShoppingList的属性,_ShoppingListState可以使用它的widget属性。 如果父级重建并创建一个新的ShoppingList,那么 _ShoppingListState也将用新的widget值重建(译者语:这里原文档有错误,应该是_ShoppingListState不会重新构建,但其widget的属性会更新为新构建的widget)。 如果希望在widget属性更改时收到通知,则可以覆盖didUpdateWidget函数,以便将旧的oldWidget与当前widget进行比较。

处理onCartChanged回调时,_ShoppingListState通过添加或删除产品来改变其内部_shoppingCart状态。 为了通知框架它改变了它的内部状态,需要调用setState。调用setState将该widget标记为”dirty”(脏的),并且计划在下次应用程序需要更新屏幕时重新构建它。 如果在修改widget的内部状态后忘记调用setState,框架将不知道您的widget是”dirty”(脏的),并且可能不会调用widget的build方法,这意味着用户界面可能不会更新以展示新的状态。

通过以这种方式管理状态,您不需要编写用于创建和更新子widget的单独代码。相反,您只需实现可以处理这两种情况的build函数。

响应widget生命周期事件

主要文章: State

在StatefulWidget调用createState之后,框架将新的状态对象插入树中,然后调用状态对象的initState。 子类化State可以重写initState,以完成仅需要执行一次的工作。 例如,您可以重写initState以配置动画或订阅platform services。initState的实现中需要调用super.initState

当一个状态对象不再需要时,框架调用状态对象的dispose。 您可以覆盖该dispose方法来执行清理工作。例如,您可以覆盖dispose取消定时器或取消订阅platform services。 dispose典型的实现是直接调用super.dispose

Key

主要文章: Key_

您可以使用key来控制框架将在widget重建时与哪些其他widget匹配。默认情况下,框架根据它们的runtimeType和它们的显示顺序来匹配。 使用key时,框架要求两个widget具有相同的keyruntimeType

Key在构建相同类型widget的多个实例时很有用。例如,ShoppingList构建足够的ShoppingListItem实例以填充其可见区域:

  • 如果没有key,当前构建中的第一个条目将始终与前一个构建中的第一个条目同步,即使在语义上,列表中的第一个条目如果滚动出屏幕,那么它将不会再在窗口中可见。

  • 通过给列表中的每个条目分配为“语义” key,无限列表可以更高效,因为框架将同步条目与匹配的语义key并因此具有相似(或相同)的可视外观。 此外,语义上同步条目意味着在有状态子widget中,保留的状态将附加到相同的语义条目上,而不是附加到相同数字位置上的条目。

全局 Key

主要文章: GlobalKey

您可以使用全局key来唯一标识子widget。全局key在整个widget层次结构中必须是全局唯一的,这与局部key不同,后者只需要在同级中唯一。由于它们是全局唯一的,因此可以使用全局key来检索与widget关联的状态。