Last active
September 16, 2019 05:31
-
-
Save efortuna/9f53be93276137b9de9ca4ed9eacad11 to your computer and use it in GitHub Desktop.
A demonstration of the proper key placement (at the top of your widget tree) in scenarios that require keys.
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
void main() => runApp(new MaterialApp(home: PositionedTiles())); | |
class PositionedTiles extends StatefulWidget { | |
@override | |
State<StatefulWidget> createState() => PositionedTilesState(); | |
} | |
class PositionedTilesState extends State<PositionedTiles> { | |
List<Widget> tiles = [ | |
Padding( | |
// Place the keys at the *top* of the tree of the items in the collection. | |
key: UniqueKey(), | |
padding: const EdgeInsets.all(8.0), | |
child: StatefulColorfulTile(), | |
), | |
Padding( | |
key: UniqueKey(), | |
padding: const EdgeInsets.all(8.0), | |
child: StatefulColorfulTile(), | |
), | |
]; | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
body: Row(children: tiles), | |
floatingActionButton: FloatingActionButton( | |
child: Icon(Icons.sentiment_very_satisfied), onPressed: swapTiles), | |
); | |
} | |
swapTiles() { | |
setState(() { | |
tiles.insert(1, tiles.removeAt(0)); | |
}); | |
} | |
} | |
class StatefulColorfulTile extends StatefulWidget { | |
StatefulColorfulTile({Key key}) : super(key: key); | |
@override | |
ColorfulTileState createState() => ColorfulTileState(); | |
} | |
class ColorfulTileState extends State<ColorfulTile> { | |
Color myColor; | |
@override | |
void initState() { | |
super.initState(); | |
myColor = UniqueColorGenerator.getColor(); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Container( | |
color: myColor, | |
child: Padding( | |
padding: EdgeInsets.all(70.0), | |
)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If anyone is following Emily's tutorial https://medium.com/flutter/keys-what-are-they-good-for-13cb51742e7d
Here's the final main.dart file
change the
dart import 'package:flutter_web/material.dart';
toimport 'package:flutter/material.dart';
if your on the modbile