颤振计时器问题

时间:2020-10-15 12:14:14

标签: flutter dart time timer

我实现了一个Timer,但是它似乎并没有在正确的持续时间之后调用callback()函数,它从几秒钟后调用回调开始,并且每次调用回调时都会加快速度。 例如5秒-> callback(),4秒-> callback(),2-> callback(),0.3秒-> callback()...

我希望有一个计时器,可以在每秒之后减小int的值。

当前代码-ViewModel:

 ' Load Omniglot dataset ' 
# load the training data
(ds_train, ds_test), ds_info = tfds.load(name='Omniglot', split=['train', 'test'], with_info=True)


# Convert labels to numpy arrays for manipulation
train_labels = np.array([[glyph["alphabet"].numpy() for glyph in ds_train]])    


# Convert images to numpy arrays for manipulation
train_images = np.array([glyph["image"].numpy()[:, :, 0] for glyph in ds_train])    


# Re-shape images for input layer
train_images = train_images.reshape(train_images.shape[0], train_images.shape[1], train_images.shape[2], 3)

代码-查看:

  void displayCountdown(Item item) {
    timer = Timer.periodic(const Duration(seconds: 1), (Timer _timer) => {
      if (lead.remainingTime >= 1) {
        item.remainingTime = item.remainingTime -= 1,
        notifyListeners(),
      }else {
        print('out of time'),
        _timer.cancel(),
        notifyListeners(),
      }
    });
  }

1 个答案:

答案 0 :(得分:0)

我不知道为什么它不起作用,但是我找到了一个可行的替代方法。

首先,我为倒计时创建一个吸气剂。 其次,当我拿到物品时,我将每个计时器设置在我的吸气器中。 第三,我用我的getter值创建我的计时器。 第四,在视图中,将吸气剂称为当前图块的索引。

std::string out_s;
// for non-C++11 use just the
// for (int i = 0 ; i < s.size() ; i++)
for (const auto& ch: s)
    if (!checkVowels(ch))
        out_s += ch;
s = out_s;

以下是该视图的代码:

...
  List<int> get countDowns => _durations;
  List<int> _durations = [];

  List<Item> items = [];
...

  Future getItems() async {
    setState(ViewState.Busy);
    final response = await _api.getItems();
    if (response is SuccessState) {
      items = response.value;
      for (var item in items) {
        _durations.add(item.remainingTime);
      }
      displayCountdowns();
    } else if (response is ErrorState) {
      String error = response.msg;
      print('Error $error');
    } else {
      print('Error');
    }
    setState(ViewState.Idle);
  }
...
  void displayCountdowns() {
    for (var countDown in _durations) {
      Timer.periodic(const Duration(seconds: 1), (timer) { 
        countDown -= 1000;
        _durations[0] = countDown;
        notifyListeners();
      });
    }
  }