我有一个简单的程序:
我尝试过:
一般如何更改对象的属性?例如,按下按钮然后更改进度栏颜色,还是结束计时器更改按钮的图标或标签?
这是完整的代码:
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,
),
)
],
),
)
),
);
}
}
答案 0 :(得分:0)
在状态中保留要更改的值,然后用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),