【发布时间】:2021-08-11 05:24:22
【问题描述】:
我想按一个按钮并从我的列表中选择一个随机字符串以显示在屏幕上的某个位置。
当前,构建器中的 convoTopic 变量正在运行错误。
感谢任何帮助!
以下是我截断的代码:
final List<String> ConvoTopics = [
'blah blah',
'black sheep',
'balh bath'
];
class ConvoPage extends StatefulWidget {
@override
_ConvoPageState createState() => _ConvoPageState();
}
class _ConvoPageState extends State<ConvoPage>
@override
Widget build(BuildContext context) {
void generateConvoTopic() {
final _random = Random();
var convoTopic = ConvoTopics[_random.nextInt(ConvoTopics.length)];
print(convoTopic);
}
return Scaffold(
backgroundColor: Color(0xff04072E),
appBar: AppBar(
title: Text('Convo', style: TextStyle(color: Colors.white)),
backgroundColor: Color(0xff04072E),
),
body: SafeArea(
child: SingleChildScrollView(
child: Column(children: <Widget>[
Container(
child: Align(
alignment: Alignment.center,
child: Text(convoTopic,
),
// where randomized string appears
),
),
ElevatedButton(
onPressed: () async {
generateConvoTopic();
},
// button's function is to randomize convo topic
child: Container(
child: Text('Get Convo'),
),
),
:
:
:
【问题讨论】:
-
在
_ConvoPageState中定义convoTopic的初始值,然后当你生成一个新的convoTopic时你必须调用setState来重建build方法。
标签: string list flutter random