首页 文章

setState()重新呈现特定的Widget . 需要代码修复

提问于
浏览
0

Hi,

下面的代码示例取自我们在flutter中创建新项目时的情况 .

Question:

_MyHomePageState 将在按下 _incrementCounter 后立即重新呈现 . 这将重新渲染appBar,body和FloatingActionButton(构建方法,这是昂贵的) . 我对吗?如果正确,唯一应该重新渲染的是带有文本的正文 . 如何分离仅需要重新渲染的窗口小部件?意味着在下面的代码中分离无状态和有状态 . 我希望你明白我的观点?

谢谢

import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Flutter Hot reload'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

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

  @override
  Widget build(BuildContext context) {

    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: new Center(
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new Text(
              'You have pushed the button this many times:',
            ),
            new Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
      floatingActionButton: new FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: new Icon(Icons.add),
      ),
    );
  }
}

1 回答

  • 0

    Flutter将确定需要重新创建或重建哪些小部件,并仅重新创建/重建这些小部件 .

    IIRC,在每个setState()(或动画节拍或其他重新渲染)上,Flutter遍历Widget树并比较每个Widget树分支的前后状态 . 只有在状态实际发生更改时才会重建有状态窗口小部件,并且只会重新创建无状态窗口小部件 . 因此,在您的情况下,重建了_MyHomePageState,但只重新创建了第二个Text小部件 .

    有关窗口小部件(以及基础元素和渲染框)的更详细说明,请参见https://www.youtube.com/watch?v=dkyY9WCGMi0&t=171s .

相关问题