对空值使用 Null 检查运算符的 debounce 方法的颤振异常

时间:2021-05-23 21:05:23

标签: flutter debounce

我在使用 onChanged 时调用了 debounce 方法以减少对 API 的调用次数。 实际上,如果我在页面上,我会在搜索栏中记录一些内容,我会得到结果,我可以毫无错误地返回。 但是,如果我在页面上,然后按返回按钮,则会收到此错误:

The following _CastError was thrown while finalizing the widget tree:
Null check operator used on a null value
#0      Debounce.dispose
package:drawer/…/share/debounce.dart:17  -> void dispose() => _timer!.cancel();
#1      _HistoriquePageState.dispose
package:drawer/…/pages/historique_page.dart:26 -> _debounce.dispose();

这是我的代码:

class _HistoriquePageState extends State<HistoriquePage> {
  final _debounce = Debounce();
  DateTimeRange? dateRange;
  String searchedValue = "";
  Post? user;

  @override
  void dispose() {
    _debounce.dispose();
    super.dispose();
  }

  void _sendSearch(String value) {
    _debounce.run(() {
      setState(() {
        searchedValue = value;
      });
    });
  }

  @override
  Widget build(BuildContext context) => Scaffold(
......
......
onChanged: _sendSearch
...
...
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

class Debounce {
  final int milliseconds;
  late VoidCallback action;
  Timer? _timer;

  Debounce({this.milliseconds = 500});

  void run(VoidCallback action) {
    if (_timer?.isActive != null) _timer!.cancel();
    _timer = Timer(Duration(milliseconds: this.milliseconds), action);
  }

  void dispose() => _timer!.cancel();
}

所以正如我所说,只有当我没有录制一些东西来抛出 _sendSearch 并且我按下返回时才会出现问题。 如果我录了一些东西,我回去就不会出错。

颤振版本:2.2.0

0 个答案:

没有答案