您好,
下面的代码示例取自我们在flutter中创建新项目的时间。
问题:
按下_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),
),
);
}
}
答案 0 :(得分:0)
Flutter将确定需要重新创建或重建哪些小部件,并仅重新创建/重建这些小部件。
请参阅 https://www.youtube.com/watch?v=dkyY9WCGMi0&t=171s 有关窗口小部件(以及基础元素和渲染框)的更详细说明。