# 11.有状态Widget初始化重写&链式调用&排序

### 前言

前文我们通过联系人页面聊到了断言的使用，本文将继续结合该场景了机更多 `Flutter` 开发小技巧。

### 初始化方法重写

对于一个 StatefulWidget 我们如果需要在其初始化的时候进行一些操作的话，可以通过重写 `initState()` 来达到效果。

```
class _ContactsPageState extends State<ContactsPage> {

  @override
  void initState() {
    super.initState();

    // 添加数据
    _contacts
        .addAll(friendsData);

    _systems
        .addAll(friendsHeaderData);
  }

  ...
}
```

### 链式调用

在 `iOS` 开发中，比如使用 `SnapKit` 进行UI控件约束布局的时候，我们经常会用到这样的`链式调用`，非常爽。

```
make.leading.trailing.top.equalToSuperview()
```

其实在 Flutter 开发中我们也可以使用类似的写法：

```
@override
  void initState() {
    super.initState();

    // 链式调用 多次添加元素
    _contacts
      ..addAll(friendsData)
      ..addAll(friendsData);

    _systems.addAll(friendsHeaderData);
  }
```

### 排序

在上面可以看到 `..addAll(friendsData)` 这样连续进行了调用。那么是否可以做的更多呢？

通常联系人列表我们会进行按字母排序，这里通过链式调用进行尝试：

```
@override
  void initState() {
    super.initState();
    _contacts
      ..addAll(friendsData)
      ..addAll(friendsData)
      ..sort((a, b) {
        if (a.indexLetter == null || b.indexLetter == null) {
          return 0;
        }
        return a.indexLetter!.compareTo(b.indexLetter!);
      });
    _systems.addAll(friendsHeaderData);
  }
```

#### 和 Swift sort 的不同

这里你可能会发现，这里的 `sort` 函数和 `Swift` 的略有不同，内部回调的返回值不是 `bool` 而是 `int` 。

结合函数头文件注释我们可以了解更多：

````
  /// Sorts this list according to the order specified by the [compare] function.
  ///
  /// The [compare] function must act as a [Comparator].
  /// ```dart
  /// var numbers = ['two', 'three', 'four'];
  /// // Sort from shortest to longest.
  /// numbers.sort((a, b) => a.length.compareTo(b.length));
  /// print(numbers);  // [two, four, three]
  /// ```
  /// The default [List] implementations use [Comparable.compare] if
  /// [compare] is omitted.
  /// ```dart
  /// List<int> nums = [13, 2, -11];
  /// nums.sort();
  /// print(nums);  // [-11, 2, 13]
  /// ```
  /// In that case, the elements of the list must be [Comparable] to
  /// each other.
  ///
  /// A [Comparator] may compare objects as equal (return zero), even if they
  /// are distinct objects.
  /// The sort function is not guaranteed to be stable, so distinct objects
  /// that compare as equal may occur in any order in the result:
  /// ```dart
  /// var numbers = ['one', 'two', 'three', 'four'];
  /// numbers.sort((a, b) => a.length.compareTo(b.length));
  /// print(numbers);  // [one, two, four, three] OR [two, one, four, three]
  /// ```
  void sort([int compare(E a, E b)?]);
````

#### 简略写法

这里的排序函数可以在条件比较简单的情况下可以简写，提高编码效率

**未简写**

```
sort((a, b) {
  if (a.indexLetter == null || b.indexLetter == null) {
    return 0;
  }
  return a.indexLetter!.compareTo(b.indexLetter!);
});
```

**简写**

```
sort( (a, b) => a.indexLetter.compareTo(b.indexLetter) );
```

> 头文件注释中有这样简写说明，平时多阅读注释，可以帮助我们写出更有语言特色风格的代码哦～


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ryukiedev.gitbook.io/wiki/flutter/11.-tong-guo-lian-xi-ren-lie-biao-kan-you-zhuang-tai-widget-chu-shi-hua-yu-lian-shi-tiao-yong.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
