【问题标题】:How to change IconButton's icon from callback function in flutter如何从flutter中的回调函数更改IconButton的图标
【发布时间】:2019-02-22 00:46:12
【问题描述】:

我有简单的程序:

  • 按下定时器按钮,它将启动一个持续时间为 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,
                  ),
                )
              ],
            ),
          )
      ),
    );
  }
}

【问题讨论】:

    标签: dart flutter


    【解决方案1】:

    在State中保持你想要改变的值,用setState改变它。
    与 1 完全相同的东西很少见,所以请使用&gt;=

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

    【讨论】:

    • 谢谢,保存iconData是最简单的方法!
    猜你喜欢
    • 2021-02-01
    • 2022-01-25
    • 2021-07-14
    • 2018-12-05
    • 2021-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多