【问题标题】:Flutter update progressbar from nested classFlutter 从嵌套类更新进度条
【发布时间】:2022-11-28 16:40:13
【问题描述】:

我想从嵌套类更新进度条的值。

我将回调传递给 foo 函数,期望它会在每次计数器迭代时用 setState() 更新我的进度条。

问题:进度条仅在foo 功能完全完成后才会更新。我想问题出在事件循环的某个地方......

主屏幕:

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  double _progressBarVal = 0;
  final Counter _counter = Counter();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Column(
        children: [
          TextButton(
            onPressed: () {
              _counter.foo((val) {
                setState(() {
                  _progressBarVal = val;
                });
              });
            },
            child: const Text('Press me'),
          ),
          LinearProgressIndicator(
            value: _progressBarVal,
          ),
        ],
      ),
    );
  }
}

计数器类:

class Counter {
  void foo(Function(double val) barCallback) {
    for (int i = 0; i <= 10; ++i) {
      barCallback(i / 10);
      debugPrint('Val is ${i / 10}');
      sleep(const Duration(seconds: 1));
    }
  }
}

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    使用 Future.delayed而不是sleep

    class Counter {
      void foo(Function(double val) barCallback) async {
        for (int i = 0; i <= 10; ++i) {
          barCallback(i / 10);
          debugPrint('Val is ${i / 10}');
          await Future.delayed(const Duration(seconds: 1));
        }
      }
    }
    
    

    【讨论】:

    • 谢谢。这解决了我的问题,但我在那里添加了 sleep() 只是为了举例。我不希望在我的真实项目中出现sleep()。我已经测试了await Future.delayed(const Duration(seconds: 0));,它也有效。我想知道这是否是做这些事情的好方法?
    • 为此,我可能更喜欢 Teen<double> 和 AnimationController
    猜你喜欢
    • 1970-01-01
    • 2015-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-08
    • 1970-01-01
    • 1970-01-01
    • 2017-08-23
    相关资源
    最近更新 更多