如何在Flutter中从回调函数更改IconButton的图标 [英] How to change IconButton's icon from callback function in flutter

查看:1015
本文介绍了如何在Flutter中从回调函数更改IconButton的图标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的程序:


  • 按下计时器按钮,它将启动一个持续时间为10ms的计时器

  • 进度条保持增加到100%,然后取消计时器并将IconButton的图标更改为其他图标,例如Icon.timer_off

我尝试过:


  • 为IconButton设置一个键,然后尝试通过键查找对象,但未成功。

一般如何更改对象的属性?例如,按下按钮然后更改进度条颜色,还是结束计时器更改按钮的图标或标签?

How to change object's property in general? For example press button and then change progress bar color, or ending timer change button's icon or label?

这是完整代码:

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完全相同的情况很少见,因此请使用> =

Hold the value you want to change in State and change it with setState.
The exact same thing as 1 is rare, so use >=.

  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),

这篇关于如何在Flutter中从回调函数更改IconButton的图标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆