Created
February 8, 2020 13:43
-
-
Save AlexKenbo/6e18d012af4bf0cb1d9c312d3590da07 to your computer and use it in GitHub Desktop.
When to use keys, part 2 - statefull
This file contains hidden or 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'; | |
import 'dart:math'; | |
void main() { | |
runApp(new MaterialApp(home: PositionedTiles())); | |
} | |
class PositionedTiles extends StatefulWidget { | |
@override | |
State<StatefulWidget> createState() => PositionedTilesState(); | |
} | |
class PositionedTilesState extends State<PositionedTiles> { | |
List<Widget> tiles = [ | |
StatefulColorfulTile(key: UniqueKey()), // попробуй убрать key: UniqueKey() | |
StatefulColorfulTile(key: UniqueKey()), // попробуй убрать key: UniqueKey() | |
]; | |
@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<StatefulColorfulTile> { | |
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))); | |
} | |
} | |
class UniqueColorGenerator { | |
UniqueColorGenerator(); | |
var randomGenerator = Random(); | |
List<Color> _listColors = [ | |
Colors.pinkAccent, | |
Colors.brown, | |
Colors.green, | |
Colors.purple, | |
Colors.yellow | |
]; | |
Color getColor() { | |
return _listColors[randomGenerator.nextInt(4)]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment