Flutter Widget框架概述

Flutter Widget採用現代響應式框架構建,這是從 React 中得到的靈感,中心思想是用widget構建你的UI。 Widget描述了他們的視圖在給定其當前配置和狀態時應該看起來像什麼。當widget的狀態發生變化時,widget會從新構建UI,Flutter會對比先後變化的不一樣, 以肯定底層渲染樹從一個狀態轉換到下一個狀態所需的最小更改(譯者語:相似於React/Vue中虛擬DOM的diff算法)html

注意: 若是您想經過代碼來深刻了解Flutter,請查看 構建Flutter佈局 和 爲Flutter App添加交互功能react

Hello World

一個最簡單的Flutter應用程序,只需一個widget便可!以下面示例:將一個widget傳給runApp函數便可:git

import 'package:flutter/material.dart';

void main() {
  runApp(
    new Center(
      child: new Text(
        'Hello, world!',
        textDirection: TextDirection.ltr,
      ),
    ),
  );
}

runApp函數接受給定的Widget並使其成爲widget樹的根。 在此示例中,widget樹由兩個widget:Center(及其子widget)和Text組成。框架強制根widget覆蓋整個屏幕,這意味着文本「Hello, world」會居中顯示在屏幕上。文本顯示的方向須要在Text實例中指定,當使用MaterialApp時,文本的方向將自動設定,稍後將進行演示。github

在編寫應用程序時,一般會建立新的widget,這些widget是無狀態的StatelessWidget或者是有狀態的StatefulWidget, 具體的選擇取決於您的widget是否須要管理一些狀態。widget的主要工做是實現一個build函數,用以構建自身。一個widget一般由一些較低級別widget組成。Flutter框架將依次構建這些widget,直到構建到最底層的子widget時,這些最低層的widget一般爲RenderObject,它會計算並描述widget的幾何形狀。web

基礎 Widget

Flutter有一套豐富、強大的基礎widget,其中如下是很經常使用的:算法

  • Text:該 widget 可以讓建立一個帶格式的文本。瀏覽器

  • Row、 Column: 這些具備彈性空間的佈局類Widget可以讓您在水平(Row)和垂直(Column)方向上建立靈活的佈局。其設計是基於web開發中的Flexbox佈局模型。架構

  • Stack: 取代線性佈局 (譯者語:和Android中的LinearLayout類似),Stack容許子 widget 堆疊, 你可使用 Positioned 來定位他們相對於Stack的上下左右四條邊的位置。Stacks是基於Web開發中的絕度定位(absolute positioning )佈局模型設計的。app

  • Container: Container 可以讓您建立矩形視覺元素。container 能夠裝飾爲一個BoxDecoration, 如 background、一個邊框、或者一個陰影。 Container 也能夠具備邊距(margins)、填充(padding)和應用於其大小的約束(constraints)。另外, Container可使用矩陣在三維空間中對其進行變換。框架

如下是一些簡單的Widget,它們能夠組合出其它的Widget:

import 'package:flutter/material.dart';

class MyAppBar extends StatelessWidget {
  MyAppBar({this.title});

  // Widget子類中的字段每每都會定義爲"final"

  final Widget title;

  @override
  Widget build(BuildContext context) {
    return new Container(
      height: 56.0, // 單位是邏輯上的像素(並不是真實的像素,相似於瀏覽器中的像素)
      padding: const EdgeInsets.symmetric(horizontal: 8.0),
      decoration: new BoxDecoration(color: Colors.blue[500]),
      // Row 是水平方向的線性佈局(linear layout)
      child: new Row(
        //列表項的類型是 <Widget>
        children: <Widget>[
          new IconButton(
            icon: new Icon(Icons.menu),
            tooltip: 'Navigation menu',
            onPressed: null, // null 會禁用 button
          ),
          // Expanded expands its child to fill the available space.
          new Expanded(
            child: title,
          ),
          new IconButton(
            icon: new Icon(Icons.search),
            tooltip: 'Search',
            onPressed: null,
          ),
        ],
      ),
    );
  }
}

class MyScaffold extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // Material 是UI呈現的「一張紙」
    return new Material(
      // Column is 垂直方向的線性佈局.
      child: new Column(
        children: <Widget>[
          new MyAppBar(
            title: new Text(
              'Example title',
              style: Theme.of(context).primaryTextTheme.title,
            ),
          ),
          new Expanded(
            child: new Center(
              child: new Text('Hello, world!'),
            ),
          ),
        ],
      ),
    );
  }
}

void main() {
  runApp(new MaterialApp(
    title: 'My app', // used by the OS task switcher
    home: new MyScaffold(),
  ));
}

請確保在pubspec.yaml文件中,將flutter的值設置爲:uses-material-design: true。這容許咱們可使用一組預約義Material icons

name: my_app
flutter:
  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 組件

Flutter提供了許多widgets,可幫助您構建遵循Material Design的應用程序。Material應用程序以MaterialApp widget開始, 該widget在應用程序的根部建立了一些有用的widget,其中包括一個Navigator, 它管理由字符串標識的Widget棧(即頁面路由棧)。Navigator可讓您的應用程序在頁面之間的平滑的過渡。 是否使用MaterialApp徹底是可選的,可是使用它是一個很好的作法。

import 'package:flutter/material.dart';

void main() {
  runApp(new MaterialApp(
    title: 'Flutter Tutorial',
    home: new TutorialHome(),
  ));
}

class TutorialHome extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    //Scaffold是Material中主要的佈局組件.
    return new Scaffold(
      appBar: new AppBar(
        leading: new IconButton(
          icon: new Icon(Icons.menu),
          tooltip: 'Navigation menu',
          onPressed: null,
        ),
        title: new Text('Example title'),
        actions: <Widget>[
          new IconButton(
            icon: new Icon(Icons.search),
            tooltip: 'Search',
            onPressed: null,
          ),
        ],
      ),
      //body佔屏幕的大部分
      body: new Center(
        child: new Text('Hello, world!'),
      ),
      floatingActionButton: new FloatingActionButton(
        tooltip: 'Add', // used by assistive technologies
        child: new Icon(Icons.add),
        onPressed: null,
      ),
    );
  }
}

如今咱們已經從MyAppBarMyScaffold切換到了AppBar和 Scaffold widget, 咱們的應用程序如今看起來已經有一些「Material」了!例如,應用欄有一個陰影,標題文本會自動繼承正確的樣式。咱們還添加了一個浮動操做按鈕,以便進行相應的操做處理。

請注意,咱們再次將widget做爲參數傳遞給其餘widget。該 Scaffold widget 須要許多不一樣的widget的做爲命名參數,其中的每個被放置在Scaffold佈局中相應的位置。 一樣,AppBar 中,咱們給參數leading、actions、title分別傳一個widget。 這種模式在整個框架中會常常出現,這也多是您在設計本身的widget時會考慮到一點。

處理手勢

大多數應用程序包括某種形式與系統的交互。構建交互式應用程序的第一步是檢測輸入手勢。讓咱們經過建立一個簡單的按鈕來了解它的工做原理:

 

class MyButton extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new GestureDetector(
      onTap: () {
        print('MyButton was tapped!');
      },
      child: new Container(
        height: 36.0,
        padding: const EdgeInsets.all(8.0),
        margin: const EdgeInsets.symmetric(horizontal: 8.0),
        decoration: new BoxDecoration(
          borderRadius: new BorderRadius.circular(5.0),
          color: Colors.lightGreen[500],
        ),
        child: new Center(
          child: new Text('Engage'),
        ),
      ),
    );
  }
}

GestureDetector widget並不具備顯示效果,而是檢測由用戶作出的手勢。 當用戶點擊Container時, GestureDetector會調用它的onTap回調, 在回調中,將消息打印到控制檯。您可使用GestureDetector來檢測各類輸入手勢,包括點擊、拖動和縮放。

許多widget都會使用一個GestureDetector爲其餘widget提供可選的回調。 例如,IconButton、 RaisedButton、 和FloatingActionButton ,它們都有一個onPressed回調,它會在用戶點擊該widget時被觸發。

根據用戶輸入改變widget

到目前爲止,咱們只使用了無狀態的widget。無狀態widget從它們的父widget接收參數, 它們被存儲在final型的成員變量中。 當一個widget被要求構建時,它使用這些存儲的值做爲參數來構建widget。

爲了構建更復雜的體驗 - 例如,以更有趣的方式對用戶輸入作出反應 - 應用程序一般會攜帶一些狀態。 Flutter使用StatefulWidgets來知足這種需求。StatefulWidgets是特殊的widget,它知道如何生成State對象,而後用它來保持狀態。 思考下面這個簡單的例子,其中使用了前面提到RaisedButton

class Counter extends StatefulWidget {
  // This class is the configuration for the state. It holds the
  // values (in this nothing) provided by the parent and used by the build
  // method of the State. Fields in a Widget subclass are always marked "final".

  @override
  _CounterState createState() => new _CounterState();
}

class _CounterState extends State<Counter> {
  int _counter = 0;

  void _increment() {
    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++;
    });
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance
    // as done by the _increment 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 new Row(
      children: <Widget>[
        new RaisedButton(
          onPressed: _increment,
          child: new Text('Increment'),
        ),
        new Text('Count: $_counter'),
      ],
    );
  }
}

您可能想知道爲何StatefulWidget和State是單獨的對象。在Flutter中,這兩種類型的對象具備不一樣的生命週期: Widget是臨時對象,用於構建當前狀態下的應用程序,而State對象在屢次調用build()之間保持不變,容許它們記住信息(狀態)。

上面的例子接受用戶點擊,並在點擊時使_counter自增,而後直接在其build方法中使用_counter值。在更復雜的應用程序中,widget結構層次的不一樣部分可能有不一樣的職責; 例如,一個widget可能呈現一個複雜的用戶界面,其目標是收集特定信息(如日期或位置),而另外一個widget可能會使用該信息來更改總體的顯示。

在Flutter中,事件流是「向上」傳遞的,而狀態流是「向下」傳遞的(譯者語:這相似於React/Vue中父子組件通訊的方式:子widget到父widget是經過事件通訊,而父到子是經過狀態),重定向這一流程的共同父元素是State。讓咱們看看這個稍微複雜的例子是如何工做的:

class CounterDisplay extends StatelessWidget {
  CounterDisplay({this.count});

  final int count;

  @override
  Widget build(BuildContext context) {
    return new Text('Count: $count');
  }
}

class CounterIncrementor extends StatelessWidget {
  CounterIncrementor({this.onPressed});

  final VoidCallback onPressed;

  @override
  Widget build(BuildContext context) {
    return new RaisedButton(
      onPressed: onPressed,
      child: new Text('Increment'),
    );
  }
}

class Counter extends StatefulWidget {
  @override
  _CounterState createState() => new _CounterState();
}

class _CounterState extends State<Counter> {
  int _counter = 0;

  void _increment() {
    setState(() {
      ++_counter;
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Row(children: <Widget>[
      new CounterIncrementor(onPressed: _increment),
      new CounterDisplay(count: _counter),
    ]);
  }
}

注意咱們是如何建立了兩個新的無狀態widget的!咱們清晰地分離了 顯示 計數器(CounterDisplay)和 更改 計數器(CounterIncrementor)的邏輯。 儘管最終效果與前一個示例相同,但責任分離容許將複雜性邏輯封裝在各個widget中,同時保持父項的簡單性。

整合全部

讓咱們考慮一個更完整的例子,將上面介紹的概念聚集在一塊兒​​。咱們假設一個購物應用程序,該應用程序顯示出售的各類產品,並維護一個購物車。 咱們先來定義ShoppingListItem

class Product {
  const Product({this.name});
  final String name;
}

typedef void CartChangedCallback(Product product, bool inCart);

class ShoppingListItem extends StatelessWidget {
  ShoppingListItem({Product product, this.inCart, this.onCartChanged})
      : product = product,
        super(key: new ObjectKey(product));

  final Product product;
  final bool inCart;
  final CartChangedCallback onCartChanged;

  Color _getColor(BuildContext context) {
    // The theme depends on the BuildContext because different parts of the tree
    // can have different themes.  The BuildContext indicates where the build is
    // taking place and therefore which theme to use.

    return inCart ? Colors.black54 : Theme.of(context).primaryColor;
  }

  TextStyle _getTextStyle(BuildContext context) {
    if (!inCart) return null;

    return new TextStyle(
      color: Colors.black54,
      decoration: TextDecoration.lineThrough,
    );
  }

  @override
  Widget build(BuildContext context) {
    return new ListTile(
      onTap: () {
        onCartChanged(product, !inCart);
      },
      leading: new CircleAvatar(
        backgroundColor: _getColor(context),
        child: new Text(product.name[0]),
      ),
      title: new Text(product.name, style: _getTextStyle(context)),
    );
  }
}

ShoppingListItem widget是無狀態的。它將其在構造函​​數中接收到的值存儲在final成員變量中,而後在build函數中使用它們。 例如,inCart布爾值表示在兩種視覺展現效果之間切換:一個使用當前主題的主色,另外一個使用灰色。

當用戶點擊列表項時,widget不會直接修改其inCart的值。相反,widget會調用其父widget給它的onCartChanged回調函數。 此模式可以讓您在widget層次結構中存儲更高的狀態,從而使狀態持續更長的時間。在極端狀況下,存儲傳給runApp應用程序的widget的狀態將在的整個生命週期中持續存在。

當父項收到onCartChanged回調時,父項將更新其內部狀態,這將觸發父項使用新inCart值重建ShoppingListItem新實例。 雖然父項ShoppingListItem在重建時建立了一個新實例,但該操做開銷很小,由於Flutter框架會將新構建的widget與先前構建的widget進行比較,並僅將差別部分應用於底層RenderObject

咱們來看看父widget存儲可變狀態的示例:

class ShoppingList extends StatefulWidget {
  ShoppingList({Key key, this.products}) : super(key: key);

  final List<Product> products;

  // The framework calls createState the first time a widget appears at a given
  // location in the tree. If the parent rebuilds and uses the same type of
  // widget (with the same key), the framework will re-use the State object
  // instead of creating a new State object.

  @override
  _ShoppingListState createState() => new _ShoppingListState();
}

class _ShoppingListState extends State<ShoppingList> {
  Set<Product> _shoppingCart = new Set<Product>();

  void _handleCartChanged(Product product, bool inCart) {
    setState(() {
      // When user changes what is in the cart, we need to change _shoppingCart
      // inside a setState call to trigger a rebuild. The framework then calls
      // build, below, which updates the visual appearance of the app.

      if (inCart)
        _shoppingCart.add(product);
      else
        _shoppingCart.remove(product);
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Shopping List'),
      ),
      body: new ListView(
        padding: new EdgeInsets.symmetric(vertical: 8.0),
        children: widget.products.map((Product product) {
          return new ShoppingListItem(
            product: product,
            inCart: _shoppingCart.contains(product),
            onCartChanged: _handleCartChanged,
          );
        }).toList(),
      ),
    );
  }
}

void main() {
  runApp(new MaterialApp(
    title: 'Shopping App',
    home: new ShoppingList(
      products: <Product>[
        new Product(name: 'Eggs'),
        new Product(name: 'Flour'),
        new Product(name: 'Chocolate chips'),
      ],
    ),
  ));
}

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生命週期事件

在StatefulWidget調用createState以後,框架將新的狀態對象插入樹中,而後調用狀態對象的initState。 子類化State能夠重寫initState,以完成僅須要執行一次的工做。 例如,您能夠重寫initState以配置動畫或訂閱platform services。initState的實現中須要調用super.initState

當一個狀態對象再也不須要時,框架調用狀態對象的dispose。 您能夠覆蓋該dispose方法來執行清理工做。例如,您能夠覆蓋dispose取消定時器或取消訂閱platform services。 dispose典型的實現是直接調用super.dispose

Key

您可使用key來控制框架將在widget重建時與哪些其餘widget匹配。默認狀況下,框架根據它們的runtimeType和它們的顯示順序來匹配。 使用key時,框架要求兩個widget具備相同的keyruntimeType

Key在構建相同類型widget的多個實例時頗有用。例如,ShoppingList構建足夠的ShoppingListItem實例以填充其可見區域:

  • 若是沒有key,當前構建中的第一個條目將始終與前一個構建中的第一個條目同步,即便在語義上,列表中的第一個條目若是滾動出屏幕,那麼它將不會再在窗口中可見。

  • 經過給列表中的每一個條目分配爲「語義」 key,無限列表能夠更高效,由於框架將同步條目與匹配的語義key並所以具備類似(或相同)的可視外觀。 此外,語義上同步條目意味着在有狀態子widget中,保留的狀態將附加到相同的語義條目上,而不是附加到相同數字位置上的條目。

全局 Key

您可使用全局key來惟一標識子widget。全局key在整個widget層次結構中必須是全局惟一的,這與局部key不一樣,後者只須要在同級中惟一。因爲它們是全局惟一的,所以可使用全局key來檢索與widget關聯的狀態。

相關文章
相關標籤/搜索