> For the complete documentation index, see [llms.txt](https://ryukiedev.gitbook.io/wiki/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ryukiedev.gitbook.io/wiki/flutter/03.-zhuang-tai-guan-li.md).

# 03.状态管理

### 前言

Flutter 的渲染模式是 增量渲染 ，当一部分有变化的时候就将原先的替换掉。所以页面元素没有必要拥有状态。但是这样对于时机开发并不友好，尤其对于数据驱动的复杂的页面。

这样就出现了 `有状态的Widget` ：数据逻辑与渲染逻辑拆分开来，数据保留，页面增量渲染。

### StatefulWidget

在我们需要可变数据驱动的Widget时，需要两个重要的部分：由数据驱动渲染。

![1](/files/IzeQ4iTfxSm6s9KclqZO)

```
import 'package:flutter/material.dart';

// 渲染逻辑
class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _MyStateDataSource();
  }
}

// 数据逻辑
class _MyStateDataSource extends State<MyStatefulWidget> {
  int _clickCount = 0;

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.red,
      child: FloatingActionButton(
        child: Text("$_clickCount"),
        onPressed: () {
          setState(() {// 触发状态改变，重新渲染
            _clickCount += 1;
          });
        },
      ),
    );
  }
}
```

### 增量渲染

你可能会想，改动一个小数据整个Widget都重新渲染，效率是不是很低啊？

不用担心这里采用的是增量渲染，通过树状的结构实现只修改使用到对应数据的叶子Widget。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://ryukiedev.gitbook.io/wiki/flutter/03.-zhuang-tai-guan-li.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
