首页 > 解决方案 > 如何从flutter中的回调函数更改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,
                  ),
                )
              ],
            ),
          )
      ),
    );
  }
}

标签: dartflutter

解决方案


将要更改的值保存在 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),

推荐阅读