我创建了一个简单的屏幕,它接受字母列表并将它们呈现在网格中。我有一个带有随机播放方法的按钮,可以随机播放此列表。在我的构建方法中,我看到状态正在使用新列表进行更新,并且每次按下按钮时都会打印出一个随机列表,但屏幕不会改变。
class _LetterContainerState extends State<LetterContainer> {
List<String> _letters = ['D', 'A', 'B', 'C', 'E', 'F', 'G', 'H'];
void shuffle() {
var random = new Random();
List<String> newLetters = _letters;
for (var i = newLetters.length - 1; i > 0; i--) {
var n = random.nextInt(i + 1);
var temp = newLetters[i];
newLetters[i] = newLetters[n];
newLetters[n] = temp;
}
setState(() {
_letters = newLetters;
});
}
@override
Widget build(BuildContext context) {
print('LETTERS');
print(_letters);
List<LetterTile> letterTiles =
_letters.map<LetterTile>((letter) => new LetterTile(letter)).toList();
return new Column(
children: <Widget>[
new FlatButton(onPressed: shuffle, child: new Text("Shuffle")),
new Container(
color: Colors.amberAccent,
constraints: BoxConstraints.expand(height: 200.0),
child: new GridView.count(
crossAxisCount: 4,
mainAxisSpacing: 4.0,
crossAxisSpacing: 4.0,
children: letterTiles,
))
],
);
}
}
EDIT:
import 'package:flutter/material.dart';
class Vowels {
static const values = ['A', 'E', 'I', 'O', 'U'];
static bool isVowel(String letter) {
return values.contains(letter.toUpperCase());
}
}
class LetterTile extends StatefulWidget {
final String value;
final bool isVowel;
LetterTile(value)
: value = value,
isVowel = Vowels.isVowel(value);
@override
_LetterTileState createState() => new _LetterTileState(this.value);
}
class _LetterTileState extends State<LetterTile> {
_LetterTileState(this.value);
final String value;
@override
Widget build(BuildContext context) {
Color color = Vowels.isVowel(this.value) ? Colors.green : Colors.deepOrange;
return new
Card(
color: color,
child: Padding(
padding: EdgeInsets.all(8.0),
child: Text(
this.value,
style: TextStyle(fontSize: 40.0, color: Colors.white)
)
)
);
}
}