我只是想学习Flutter,在Flutter演示代码中有一段代码,是在创建新的Flutter项目时得到的,我不理解:
标题:新文本(widget.title)
我不了解小部件的来源,因为它没有声明,定义或初始化。它指的是此文本:
首页:新的MyHomePage(标题:“ Flutter演示首页”)
但是为什么与上下文有关?如果它是预定义的,我将如何以及在何处使用它。 由于一切都是小工具,因此很难向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.
);
}
}
答案 0 :(得分:1)
MyHomePage
具有最后一个字段title
,您在构造函数中声明了该字段-MyHomePage(title: 'Flutter Demo Home Page')``_MyHomePageState
-这是有状态小部件的状态。在每种状态下,您都可以使用widget
来获取您的StatefulWidget