Skip to content

Instantly share code, notes, and snippets.

@kcoder666
Created March 29, 2021 15:32
Show Gist options
  • Save kcoder666/481a9eb6c534905df120b388bb3e4f52 to your computer and use it in GitHub Desktop.
Save kcoder666/481a9eb6c534905df120b388bb3e4f52 to your computer and use it in GitHub Desktop.
Flutter Key Example
import 'dart:math';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class UniqueColorGenerator {
static const _kColorChoices = <Color>[
Colors.red,
Colors.blue,
Colors.green,
Colors.amber,
Colors.black,
Colors.brown,
Colors.cyan,
Colors.indigo,
Colors.lime,
Colors.orange,
Colors.pink,
Colors.teal,
Colors.yellow,
];
static final _r = Random();
static Color getColor() {
return _kColorChoices[_r.nextInt(_kColorChoices.length)];
}
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Global Key Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: PositionedTiles(),
);
}
}
class PositionedTiles extends StatefulWidget {
@override
State<StatefulWidget> createState() => PositionedTilesState();
}
class PositionedTilesState extends State<PositionedTiles> {
final key1 = UniqueKey();
final key2 = UniqueKey();
bool reversed = false;
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Row(
children: [
StatefulColorfulTile(
key: reversed ? key2 : key1,
index: 1,
),
StatefulColorfulTile(
key: reversed ? key1 : key2,
index: 2,
),
],
),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.sentiment_very_satisfied),
onPressed: swapTiles,
),
);
}
swapTiles() {
setState(() {
reversed = !reversed;
});
}
}
class StatelessColorfulTile extends StatelessWidget {
final myColor = UniqueColorGenerator.getColor();
@override
Widget build(BuildContext context) {
return Container(
color: myColor,
child: Padding(padding: EdgeInsets.all(70.0)),
);
}
}
class StatefulColorfulTile extends StatefulWidget {
final int index;
const StatefulColorfulTile({Key key, this.index}) : 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),
child: Text(
'${widget.index}',
style: Theme.of(context)
.textTheme
.headline1
.copyWith(color: Colors.white, fontWeight: FontWeight.bold),
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment