【发布时间】:2019-05-09 23:32:45
【问题描述】:
我只是想学习flutter,flutter演示代码中有一段代码,你在创建一个新的flutter项目时得到的,我不明白:
标题:新文本(widget.title)
我不明白小部件的来源,因为它没有声明、定义或初始化。它指的是这个文本:
home: new MyHomePage(title: 'Flutter Demo Home Page')
但是为什么,它与上下文有关?如果它是预定义的,我可以如何以及在哪里使用它。 由于 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.
);
}
}
【问题讨论】:
-
[Mod:我不能“评论”——没有足够的代表,但我认为这种赞赏确实值得公开表达。如果必须删除,也许您可以代表我将其发布在 cmets 中。] 感谢您提出这个问题和答案。我有同样的问题,并立即怀疑谷歌搜索,这个想法可能不受网络搜索的影响。然后我认为“小部件对象”有一个机会的幽灵(即使考虑到小部件对象这不太可能:)