flutter - Flutter 应用中的列表不响应触摸事件
问题描述
我正在尝试构建一个简单的应用程序,它应该计算两个按钮上的点击次数。我正在尝试使用一行图标来显示该计数。有两种类型的图标:icons.check和icons.close。这是我写的代码:
import 'package:flutter/material.dart';
void main() => runApp(Quizzler());
class Quizzler extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: Colors.grey.shade900,
body: SafeArea(
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 10.0),
child: QuizPage(),
),
),
),
);
}
}
class QuizPage extends StatefulWidget {
@override
_QuizPageState createState() => _QuizPageState();
}
class _QuizPageState extends State<QuizPage> {
List<Icon> scoreKeeper = [
Icon(
Icons.check,
color: Colors.green,
),
Icon(
Icons.close,
color: Colors.red,
),
Icon(
Icons.close,
color: Colors.red,
)
];
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Expanded(
flex: 5,
child: Padding(
padding: EdgeInsets.all(10.0),
child: Center(
child: Text(
'This is where the question text will go.',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 25.0,
color: Colors.white,
),
),
),
),
),
Expanded(
child: Padding(
padding: EdgeInsets.all(15.0),
child: FlatButton(
textColor: Colors.white,
color: Colors.green,
child: Text(
'True',
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
),
),
onPressed: () {
//The user picked true.
scoreKeeper.add(
Icon(
Icons.check,
color: Colors.green,
),
);
},
),
),
),
Expanded(
child: Padding(
padding: EdgeInsets.all(15.0),
child: FlatButton(
color: Colors.red,
child: Text(
'False',
style: TextStyle(
fontSize: 20.0,
color: Colors.white,
),
),
onPressed: () {
//The user picked false.
scoreKeeper.add(
Icon(
Icons.close,
color: Colors.red,
),
);
},
),
),
),
//TODO: Add a Row here as your score keeper
Row(
children: scoreKeeper,
)
],
);
}
}
当我按下这两个按钮时,列表记分员没有更新。它应该在屏幕底部呈现新图标,但在这种情况下,它不会增加。
谢谢你。
解决方案
您只需要setState
为每次更改添加 UI;
onPressed: () {
//The user picked false.
scoreKeeper.add(
Icon(
Icons.close,
color: Colors.red,
),
);
// notifiy changes to UI
setState((){});
},
推荐阅读
- python - 我想创建一个图表矩阵,从数据库中获取天线和通道列表的数据
- c# - 通过依赖注入获取 dbcontexts 背后的 10 多个剃须刀页面代码
- winapi - 如何优雅地终止可继承进程
- django - 与 DjangoItem 的 Scrapy 集成会产生错误
- excel - 如何在 VBA 中连接带有双引号和冒号的字符串?
- jupyter-notebook - Jupyter Lab 中有多个服务器?
- python - 从列表中抓取网站,解析全文,保存为 txt 文件 - Python
- javascript - 如何准确跟踪视频标签的当前时间?
- xamarin - Xamarin.Forms 项目中的“在当前上下文中找不到初始化组件”
- excel - 找不到变量时如何处理