Last active
September 27, 2019 17:02
-
-
Save MariaMelnik/78cf0ba41b3d871fc0ba2e9ef38ba44a to your computer and use it in GitHub Desktop.
flutter: why passing something with State constructor not the best idea
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
void main() => runApp(MyApp()); | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
theme: ThemeData( | |
primarySwatch: Colors.blue, | |
), | |
home: MyHomePage(), | |
); | |
} | |
} | |
class MyHomePage extends StatefulWidget { | |
@override | |
_MyHomePageState createState() => _MyHomePageState(); | |
} | |
class _MyHomePageState extends State<MyHomePage> { | |
Color color = Colors.blue; | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: Text("Why not state constructor"), | |
), | |
body: Center( | |
child: Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: <Widget>[ | |
MyAwesomeWidget( | |
color: color, | |
), | |
RaisedButton( | |
onPressed: _changeColor, | |
child: Text("set red color"), | |
) | |
], | |
), | |
), | |
); | |
} | |
void _changeColor() { | |
setState(() { | |
color = Colors.red; | |
}); | |
} | |
} | |
class MyAwesomeWidget extends StatefulWidget { | |
final Color color; | |
MyAwesomeWidget({Key key, this.color}) : super(key: key) { | |
print("MyAwesomeWidget constructor called with color: ${color}"); | |
} | |
_MyAwesomeWidgetState createState() => _MyAwesomeWidgetState(color); | |
} | |
class _MyAwesomeWidgetState extends State<MyAwesomeWidget> { | |
Color color; | |
_MyAwesomeWidgetState(this.color); | |
@override | |
Widget build(BuildContext context) { | |
return Container( | |
height: 100.0, | |
width: 100.0, | |
color: color ?? Colors.blue, | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment