Reputation: 95
I'm just trying to learn flutter and there's a piece of code in the flutter demo code, that you get when creating a new flutter project, that i don't understand :
title: new Text(widget.title)
I don't understand where widget comes from, as it is nowhere declared, defined or initialized. It refers to this Text:
home: new MyHomePage(title: 'Flutter Demo Home Page')
but why, has it something to do with context? And if its something predefined, how and where can i use it. As everything in flutter is a Widget it's hard to ask Google for that problem.
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.
);
}
}
Upvotes: 3
Views: 1876
Reputation: 29438
MyHomePage
has final field title
, which you declare in constructor - MyHomePage(title: 'Flutter Demo Home Page')``_MyHomePageState
- it's a state of stateful widget. In every state you can use widget
to get your StatefulWidget
Upvotes: 5