Reputation: 20178
Below is the definition of a Stateful Widget and its associated state. As we can see, color
has been defined in YellowBird
and can be accessed in _YellowBirdState
via the widget
object.
My question is with respect to this, how do we decide where (Widget class or State class) to define the attributes? For example, color
could have been defined in _YellowBirdState
directly. For now, I am deciding this based on whether I have to access the attributes from outside. For example, considering the example below, if I need to access the attribute color
from outside, then I define it in the Widget class.
class YellowBird extends StatefulWidget {
const YellowBird({ Key? key }) : super(key: key);
var color = 0xFFFFE306;
@override
State<YellowBird> createState() => _YellowBirdState();
}
class _YellowBirdState extends State<YellowBird> {
@override
Widget build(BuildContext context) {
return Container(color: Color(widget.color));
}
}
Upvotes: 0
Views: 87
Reputation: 3572
One reason to create the attributes in the widget class is to pass values from outside. In your example you could pass the color dynamically.
class YellowBird extends StatefulWidget {
Color color;
YellowBird(this.color, {Key? key}) : super(key: key);
@override
State<YellowBird> createState() => _YellowBirdState();
}
class _YellowBirdState extends State<YellowBird> {
@override
Widget build(BuildContext context) {
return Container(color: widget.color);
}
}
Now you can create your widget with different colors
YellowBird(Colors.green)
YellowBird(Colors.red)
Upvotes: 1