我只是想学习 flutter,flutter 演示代码中有一段代码,是您在创建新的 flutter 项目时得到的,我不明白:
标题:新文本(widget.title)
我不明白小部件来自哪里,因为它没有被声明、定义或初始化。它指的是这个文本:
home: new MyHomePage(title: 'Flutter 演示主页')
但是为什么,这与上下文有关吗?如果它是预定义的,我可以如何以及在哪里使用它。 由于 flutter 中的所有内容都是 Widget,因此很难向 Google 询问这个问题。
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
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),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
最佳答案
MyHomePage
具有最终字段 title
,您可以在构造函数中声明该字段 - MyHomePage(title: 'Flutter Demo Home Page')``_MyHomePageState
- 这是有状态小部件的状态。在每种状态下,您都可以使用 widget
来获取 StatefulWidget
关于widget - 尝试理解 flutter 演示代码中的小部件对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53682423/