flutter - 按下按钮后更新文本 - 在 Flutter 中
问题描述
我目前正在研究随机辛普森剧集生成器。
我希望用户在按下一个按钮后获得一个随机季节和一个随机剧集。目前“onpressed”启动了一个名为“randomEpisode”的函数。在那里,季节和剧集是随机挑选的。
现在我不知道如何更新显示季节和剧集的文本。
import 'package:flutter/material.dart';
import 'dart:math';
class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
Random random = new Random();
int season = 0;
int episode = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.yellow,
body: SafeArea(
child: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/Loading.jpg'),
fit: BoxFit.fitWidth,
),
),
child: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
SizedBox(height: 40.0),
Text(
'Season: $season ',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 50.0,
letterSpacing: 2.0,
color: Colors.black,
),
),
SizedBox(height: 10.0),
Text(
'Episode: $episode',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 50.0,
color: Colors.black,
),
),
SizedBox(height: 40.0),
RaisedButton(
onPressed: () => randomEpisode(),
color: Colors.blue,
elevation: 5,
child: const Text('Random',
style: TextStyle(
fontSize: 20,
color: Colors.black,
)),
),
]),
),
),
),
);
}
randomEpisode() {
List<int> numberepisodes = [
13,
22,
24,
22,
22,
25,
25,
25,
25,
23,
22,
21,
22,
22,
22,
21,
22,
22,
20,
21,
23,
22,
22,
22,
22,
22,
22,
22,
21,
23,
22,
];
Random random = new Random();
int season;
int episode;
int maxseason;
int maxepisode;
//_changeEpisode();
print('numberepisodes: $numberepisodes');
maxseason = numberepisodes.length;
print('maxseason $maxseason');
season =
1 + random.nextInt(numberepisodes.length - 1);
print('season $season');
maxepisode = numberepisodes[season - 1];
print('maxepisodes $maxepisode');
episode =
1 + random.nextInt(numberepisodes[season - 1] - 1);
print('Season: $season , Episode: $episode');
}
}
解决方案
randomEpisode()
从方法中删除以下局部变量
int season;
int episode;
并在方法结束时调用以下randomEpisode()
方法。
setState(() {});
推荐阅读
- python - 无法在 PySide2 上使用 ApplicationWindow (QML)
- ruby-on-rails-3 - 使用 ruby 脚本的 DynamoDB 表描述
- sql - 根据另一个表中的条件显示表中的列
- .net - 不能 .loadby sos mscorwks 或 .loadby sos clr
- excel - Excel 2010 - 使用数据验证和逻辑的多个下拉菜单
- json - 如何在scala中过滤嵌套列表和地图
- sql - 在 MS SQL 中的大小写问题
- python - Python:从包含 python 字典/元组的字符串创建字典
- angularjs - 是否可以从网页调用 TeamViewer.exe 以远程连接到主机和直通密码详细信息?
- java - 如何在硒中每10秒截屏一次?