Last active
October 4, 2019 14:03
-
-
Save icatalud/0f1481f8dfcfa3ff7d00eabf25a29bd7 to your computer and use it in GitHub Desktop.
Example dynamic widget
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
class ColorBox extends DynamicWidget { | |
final int id; | |
ColorBox(this.id, {Key key}) : super(key: key); | |
initDyn() { | |
dyn[#color] = randomColor(); | |
dyn[#textColor] = contrastColor(dyn[#color]); | |
dyn[#clicks] = 0; | |
} | |
@override | |
Widget build(BuildContext context) { | |
int clicks = dyn[#clicks]; | |
return RaisedButton( | |
child: floop[#selectedBoxId] == id | |
? Opacity( | |
opacity: 1 - transition(2000, key: id), | |
child: Text( | |
'$clicks', | |
style: TextStyle( | |
color: dyn[#textColor], | |
fontSize: 26, | |
), | |
)) | |
: null, | |
color: dyn[#color], | |
onPressed: () { | |
dyn[#clicks] = ++clicks; | |
final switchMode = clicks % 4 == 0; | |
floop[#useRepeatingGrid] ^= switchMode; | |
floop[#selectedBoxId] = switchMode ? null : id; | |
floop[#totalClicks]++; | |
Transitions.restart(key: id); | |
// Note that floop[#widgets] is copied into a new list prior to | |
// shuffling. This is because when [List] instances are stored in an | |
// [ObservedMap], they are copied and stored as unmodifiable lists. | |
floop[#widgets] = floop[#widgets].toList()..shuffle(); | |
}, | |
); | |
} | |
} | |
class ColoredGrid extends FloopWidget { | |
@override | |
void initContext(BuildContext context) { | |
floop[#totalClicks] = 0; | |
floop[#useRepeatingGrid] = true; | |
createRandomColorBoxList(); | |
} | |
createRandomColorBoxList() { | |
floop[#selectedBoxId] = null; | |
final baseWidgets = List.generate(4, (i) => ColorBox(i)..forceInit()); | |
floop[#widgets] = List.generate(50, (i) => baseWidgets[i % 4])..shuffle(); | |
} | |
@override | |
Widget build(BuildContext context) { | |
final int clicks = floop[#totalClicks]; | |
return Scaffold( | |
appBar: AppBar( | |
title: Text('Total clicks: ${clicks}'), | |
), | |
body: floop[#useRepeatingGrid] | |
? GridView.count( | |
crossAxisCount: 5, | |
children: floop[#widgets].cast<Widget>(), | |
) | |
: GridView.count( | |
crossAxisCount: 4, | |
children: List.generate( | |
20, | |
(i) => ColorBox(clicks - i, key: ValueKey(clicks - i)), | |
), | |
), | |
floatingActionButton: FloatingActionButton( | |
child: Icon(Icons.replay), | |
onPressed: () { | |
createRandomColorBoxList(); | |
floop[#useRepeatingGrid] = | |
!floop[#useRepeatingGrid] || clicks % 2 == 0; | |
; | |
}, | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment