在颤动中删除 textField 侦听器

问题描述

如何禁用/删除颤振中 textField 的控件侦听器,我使用的是 3 个 textField一个简单的数学连接.. (textField1 + textField2 = textField3) & (textField1 - textField3 = textField2)... 我需要更改 textField3 的值并保持 textField2 的值不变?。现在的情况是这样的

enter image description here

这是我的代码

@override
  void initState() {
    super.initState();
    _focus.addListener(() {
      if (_focus.hasFocus) {
        _finalValue.clear();
      }
    });
    _focuseLocity.addListener(() {
      if (_focuseLocity.hasFocus) {
        veLocityEditingController.clear();
      }
    });
    textEditingController.addListener(() => setState(() {}));
    veLocityEditingController.addListener(() => setState(() {
          totalCalculated();
        }));
    _finalValue.addListener(() => setState(() {
          totalCalculated();
        }));
  }

  @override
  void dispose() {
    super.dispose();
    veLocityEditingController.removeListener(() {
      totalCalculated();
    });
    textEditingController.removeListener(() {
      totalCalculated();
    });
    _finalValue.removeListener(() {
      totalCalculated();
    });
  }

  String totalCalculated() {
    airFlowText = textEditingController.text;
    veLocityText = veLocityEditingController.text;
    finalText = _finalValue.text;

    if (airFlowText != '' && veLocityText != '' && !_focus.hasFocus) {
      sam = (int.parse(airFlowText) + int.parse(veLocityText)).toString();
      lastVeLocityValue = veLocityText;
      _finalValue.value = _finalValue.value.copyWith(
        text: sam.toString(),);
    }
    if (airFlowText != '' && finalText != null && !_focuseLocity.hasFocus) {
      sam = (int.parse(airFlowText) - int.parse(finalText)).toString();
      veLocityEditingController.value =
          veLocityEditingController.value.copyWith(
        text: sam.toString(),);
    }
    return sam;
  }

解决方法

为了删除监听器,您必须提供该函数的确切实例。在您的代码中,您每次都在创建新函数,因此 Dart 并没有真正看到它们是“相等的”。

确保您使用相同实例的最简单方法是将您的函数作为状态方法。

  void _onVelocityChanged() {
    setState(() {
      totalCalculated();
    });
  }

  @override
  void initState() {
    super.initState();
    velocityEditingController.addListener(_onVelocityChanged);
    // ...
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    velocityEditingController.removeListener(_onVelocityChanged);
  }

另请注意,与其删除 dispose 上的侦听器,不如调用 TextEditingControllers 上的 dispose,这会有效地删除侦听器。