dart - 如何从flutter中的回调函数更改IconButton的图标
问题描述
我有简单的程序:
- 按下定时器按钮,它将启动一个持续时间为 10 毫秒的定时器
- 进度条一直增长到100%,然后取消定时器,将IconButton的图标换成其他图标,例如Icon.timer_off
我试过了:
- 为 IconButton 设置一个键,然后尝试通过一个键找到对象,但没有成功。
一般如何更改对象的属性?例如按下按钮然后更改进度条颜色,或结束计时器更改按钮的图标或标签?
这是完整的代码:
import 'package:flutter/material.dart';
import 'dart:async';
void main() {
runApp(new MaterialApp(
home: new MyApp(),
));
}
class MyApp extends StatefulWidget {
@override
_State createState() => new _State();
}
class _State extends State<MyApp>
{
double _value = 0.0;
void _onPressed(){
new Timer.periodic(new Duration(milliseconds: 10), (timer) {
setState((){
if (_value == 1){
timer.cancel();
_value = 0.0;
return;
}
_value += 0.01;
});
});
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Test Timer'),
),
body: new Container(
padding: new EdgeInsets.all(32.0),
child: new Center(
child: new Column(
children: <Widget>[
new IconButton(icon: new Icon(Icons.timer), onPressed: _onPressed),
new Container(
padding: new EdgeInsets.all(32.0),
child: new LinearProgressIndicator(
value: _value,
valueColor: new AlwaysStoppedAnimation<Color>(Colors.green),
),
),
new Container(
padding: new EdgeInsets.all(32.0),
child: new CircularProgressIndicator(
value: _value,
),
)
],
),
)
),
);
}
}
解决方案
将要更改的值保存在 State 中并使用 更改setState
。
与 1 完全相同的东西很少见,所以使用>=
.
IconData iconData = Icons.timer;
void _onPressed(){
new Timer.periodic(new Duration(milliseconds: 10), (timer) {
setState((){
if (_value >= 1){
timer.cancel();
_value = 0.0;
iconData = Icons.timer_off;
return;
}
_value += 0.01;
});
});
}
并使用价值。
new IconButton(icon:Icon(iconData), onPressed: _onPressed),
推荐阅读
- php - 调整图像的宽度和高度
- rust - 无法理解 Rust 中 Vector 的行为
- r - 如何将动物园对象列表转换为数据框?
- azure - 将多个用户更新到 ADGroup
- excel - 有没有办法让 worksheetfunction.randbetween 在一段时间内工作?
- javascript - 正则表达式不匹配具有 10 个连续数字的字符串。数字可以用空格分隔。所有其他字符串都返回一个匹配项
- django - Django Forms - 如何将复选框链接到布尔字段
- php - 如何在 laravel DB::table 查询中 preg_replace 内容?
- ios - 忽略 IOS 中设置的设计时间约束
- c++ - C++ - 什么影响调用堆栈的顺序?