构建期间调用了 Flutter 错误 setState() 或 markNeedsBuild()。当使用 Getx GetxController 更新时

发布于 2025-01-11 00:59:37 字数 6535 浏览 0 评论 0原文

我有一个 Counter 小部件,代码如下

import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:erp_app/icons/PlutusIcons.dart';

class Counter extends StatefulWidget {
  final int? value;
  final ValueChanged<int>? onValueChanged; 
  final int? maximum;
  final int? minimum;
  final double? buttonSize;
  final double? textSize;
  final bool? editable; 
  final TextEditingController? customTextController;

  Counter({
    Key? key,
    this.value,
    this.maximum,
    this.minimum,
    this.onValueChanged,
    this.buttonSize,
    this.textSize,
    this.editable,
    this.customTextController,
  }) : super(key: key);

  @override
  _CounterState createState() => _CounterState();
}

class _CounterState extends State<Counter> {
  int _currentValue = 0;
  TextEditingController _textController = TextEditingController();
  FocusNode _textFocusNode = FocusNode();

  @override
  void didUpdateWidget(covariant Counter oldWidget) {
    if (widget.value != null) {
      _currentValue = _verifyInputVal(widget.value!);
      _textController.text = _currentValue.toString();
      _notifyValueChange(_currentValue);
    }
    super.didUpdateWidget(oldWidget);
  }

  @override
  void initState() {
    
    if (widget.customTextController != null) {
      _textController = widget.customTextController!;
    }
   
    _handleFocusNodeEvent();

    int initValue = widget.value ?? 0;
    initValue = _verifyInputVal(initValue);
    _currentValue = initValue;
    _textController.text = initValue.toString();
    _notifyValueChange(initValue);
    super.initState();
  }


  @override
  void dispose() {
   
    if (widget.customTextController == null) {
      _textController.dispose();
    }

    _textFocusNode.dispose();
    super.dispose();
  }

  void _handleFocusNodeEvent() {
    _textFocusNode.addListener(() {
      if (_textFocusNode.hasFocus == false && widget.editable != null && widget.editable == true) {
        
        setState(() {
          _textController.text = _currentValue.toString();
        });
      }
    });
  }

  void _increase() {
    if (widget.maximum != null && _currentValue >= widget.maximum!) {
      return;
    }

    _currentValue += 1;
    _notifyValueChange(_currentValue);
    setState(() {
      _currentValue = _currentValue;
      _textController.text = _currentValue.toString();
    });
  }

  void _decrease() {
    if (widget.minimum != null && _currentValue <= widget.minimum!) {
      return;
    }

    _currentValue -= 1;
    _notifyValueChange(_currentValue);
    setState(() {
      _currentValue = _currentValue;
      _textController.text = _currentValue.toString();
    });
  }

  bool _increaseIsDisabled() {
    if (widget.maximum == null) {
      return false;
    }

   
    return widget.maximum != null && _currentValue >= widget.maximum!;
  }

  bool _decreaseIsDisabled() {
    if (widget.minimum == null) {
      return false;
    }

    
    return widget.minimum != null && _currentValue <= widget.minimum!;
  }

  
  int _verifyInputVal(int val) {
    int result = 0;
    int? minimum = widget.minimum;
    int? maximum = widget.maximum;

    if (minimum != null) {
      result = math.max(minimum, val);
    }
    if (maximum != null) {
      result = math.min(result, maximum);
    }

    return result;
  }

  void _notifyValueChange(int value) {
    widget.onValueChanged?.call(value);
  }

  void _inputOnChange(String val) {
    int? num = int.tryParse(val);
    if (num == null) {
      return;
    }

   
    _currentValue = _verifyInputVal(num);
    if (widget.onValueChanged != null) {
      widget.onValueChanged!(_currentValue);
    }

    setState(() {
      _currentValue = _currentValue;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Expanded(
            child: IconButton(
              constraints: BoxConstraints(
                minWidth: widget.buttonSize ?? 20.0,
                minHeight: widget.buttonSize ?? 20.0,
              ),
              color: _decreaseIsDisabled() ? Colors.black45 : Colors.blue,
              disabledColor: Colors.grey,
              onPressed: _decreaseIsDisabled() ? null : _decrease,
              icon: Icon(
                PlutusIcons.decrease,
                size: widget.buttonSize ?? 20.0,
              ),
            ),
          ),
          Container(
            padding: EdgeInsets.only(left: 5.0, right: 5.0),
            width: 80.0,
            child: TextFormField(
              keyboardType: TextInputType.number,
              controller: _textController,
              focusNode: _textFocusNode,
              onChanged: _inputOnChange,
              enabled: widget.editable ?? false,
              style: TextStyle(
                fontSize: widget.textSize,
              ),
              textAlign: TextAlign.center,
            ),
          ),
          Expanded(
            child: IconButton(
              constraints: BoxConstraints(
                minWidth: widget.buttonSize ?? 20.0,
                minHeight: widget.buttonSize ?? 20.0,
              ),
              color: _increaseIsDisabled() ? Colors.black45 : Colors.blue,
              disabledColor: Colors.grey,
              onPressed: _increaseIsDisabled() ? null : _increase,
              icon: Icon(
                PlutusIcons.plus,
                size: widget.buttonSize ?? 20.0,
              ),
            ),
          ),
        ],
      ),
    );
  }
}

,我在 GetxPage 中使用此小部件


class page extends StatelessWidget {
  Widget build(BuildContext context) {
    return GetBuilder<PageLogic>(
        init: PageLogic(), 
        logic => Counter(
          editable: true,
          value: logic.systemStockNum,
          buttonSize: 28.0,
          minimum: 0,
          onValueChanged: logic.handleCounterChange,
    ));
  }
}

,我将 valueChanged 回调传递到 Counter 小部件中,然后当 ChangeHandler 调用时,我将更改我的 GetxController 属性并更新

class PageLogic extends GetxController {
  int currentValue = 0;

  void handleCounterChange(int value) {
    currentValue = value;
    update();
  }
}

,然后发出错误,如何错误要解决吗?为什么会出现错误?

i have a Counter widget the code like this

import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:erp_app/icons/PlutusIcons.dart';

class Counter extends StatefulWidget {
  final int? value;
  final ValueChanged<int>? onValueChanged; 
  final int? maximum;
  final int? minimum;
  final double? buttonSize;
  final double? textSize;
  final bool? editable; 
  final TextEditingController? customTextController;

  Counter({
    Key? key,
    this.value,
    this.maximum,
    this.minimum,
    this.onValueChanged,
    this.buttonSize,
    this.textSize,
    this.editable,
    this.customTextController,
  }) : super(key: key);

  @override
  _CounterState createState() => _CounterState();
}

class _CounterState extends State<Counter> {
  int _currentValue = 0;
  TextEditingController _textController = TextEditingController();
  FocusNode _textFocusNode = FocusNode();

  @override
  void didUpdateWidget(covariant Counter oldWidget) {
    if (widget.value != null) {
      _currentValue = _verifyInputVal(widget.value!);
      _textController.text = _currentValue.toString();
      _notifyValueChange(_currentValue);
    }
    super.didUpdateWidget(oldWidget);
  }

  @override
  void initState() {
    
    if (widget.customTextController != null) {
      _textController = widget.customTextController!;
    }
   
    _handleFocusNodeEvent();

    int initValue = widget.value ?? 0;
    initValue = _verifyInputVal(initValue);
    _currentValue = initValue;
    _textController.text = initValue.toString();
    _notifyValueChange(initValue);
    super.initState();
  }


  @override
  void dispose() {
   
    if (widget.customTextController == null) {
      _textController.dispose();
    }

    _textFocusNode.dispose();
    super.dispose();
  }

  void _handleFocusNodeEvent() {
    _textFocusNode.addListener(() {
      if (_textFocusNode.hasFocus == false && widget.editable != null && widget.editable == true) {
        
        setState(() {
          _textController.text = _currentValue.toString();
        });
      }
    });
  }

  void _increase() {
    if (widget.maximum != null && _currentValue >= widget.maximum!) {
      return;
    }

    _currentValue += 1;
    _notifyValueChange(_currentValue);
    setState(() {
      _currentValue = _currentValue;
      _textController.text = _currentValue.toString();
    });
  }

  void _decrease() {
    if (widget.minimum != null && _currentValue <= widget.minimum!) {
      return;
    }

    _currentValue -= 1;
    _notifyValueChange(_currentValue);
    setState(() {
      _currentValue = _currentValue;
      _textController.text = _currentValue.toString();
    });
  }

  bool _increaseIsDisabled() {
    if (widget.maximum == null) {
      return false;
    }

   
    return widget.maximum != null && _currentValue >= widget.maximum!;
  }

  bool _decreaseIsDisabled() {
    if (widget.minimum == null) {
      return false;
    }

    
    return widget.minimum != null && _currentValue <= widget.minimum!;
  }

  
  int _verifyInputVal(int val) {
    int result = 0;
    int? minimum = widget.minimum;
    int? maximum = widget.maximum;

    if (minimum != null) {
      result = math.max(minimum, val);
    }
    if (maximum != null) {
      result = math.min(result, maximum);
    }

    return result;
  }

  void _notifyValueChange(int value) {
    widget.onValueChanged?.call(value);
  }

  void _inputOnChange(String val) {
    int? num = int.tryParse(val);
    if (num == null) {
      return;
    }

   
    _currentValue = _verifyInputVal(num);
    if (widget.onValueChanged != null) {
      widget.onValueChanged!(_currentValue);
    }

    setState(() {
      _currentValue = _currentValue;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Expanded(
            child: IconButton(
              constraints: BoxConstraints(
                minWidth: widget.buttonSize ?? 20.0,
                minHeight: widget.buttonSize ?? 20.0,
              ),
              color: _decreaseIsDisabled() ? Colors.black45 : Colors.blue,
              disabledColor: Colors.grey,
              onPressed: _decreaseIsDisabled() ? null : _decrease,
              icon: Icon(
                PlutusIcons.decrease,
                size: widget.buttonSize ?? 20.0,
              ),
            ),
          ),
          Container(
            padding: EdgeInsets.only(left: 5.0, right: 5.0),
            width: 80.0,
            child: TextFormField(
              keyboardType: TextInputType.number,
              controller: _textController,
              focusNode: _textFocusNode,
              onChanged: _inputOnChange,
              enabled: widget.editable ?? false,
              style: TextStyle(
                fontSize: widget.textSize,
              ),
              textAlign: TextAlign.center,
            ),
          ),
          Expanded(
            child: IconButton(
              constraints: BoxConstraints(
                minWidth: widget.buttonSize ?? 20.0,
                minHeight: widget.buttonSize ?? 20.0,
              ),
              color: _increaseIsDisabled() ? Colors.black45 : Colors.blue,
              disabledColor: Colors.grey,
              onPressed: _increaseIsDisabled() ? null : _increase,
              icon: Icon(
                PlutusIcons.plus,
                size: widget.buttonSize ?? 20.0,
              ),
            ),
          ),
        ],
      ),
    );
  }
}

and i use this widget in my GetxPage


class page extends StatelessWidget {
  Widget build(BuildContext context) {
    return GetBuilder<PageLogic>(
        init: PageLogic(), 
        logic => Counter(
          editable: true,
          value: logic.systemStockNum,
          buttonSize: 28.0,
          minimum: 0,
          onValueChanged: logic.handleCounterChange,
    ));
  }
}

i pass a valueChanged callback into the Counter widget and then when the changeHandler call, i will change my GetxController property and update

class PageLogic extends GetxController {
  int currentValue = 0;

  void handleCounterChange(int value) {
    currentValue = value;
    update();
  }
}

and then the error is emit, how the error to resolved? and why the error is rasied?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

南烟 2025-01-18 00:59:37

这意味着即使初始小部件已经加载,您也尝试刷新页面。

为了防止在构建方法已经在进行期间调用 setState,您可以在调用 setState 之前检查您的初始小部件是否已正确安装。为此,只需通过 if 语句包装您的 setState ,如下所示:

 if(mounted){
   setState((){

   });
}

It means you are try to refresh the page even while the initial widget is already loading.

To prevent calling setState during build method is already in progress, you can check whether your initial widget is mounted properly before calling setState. For doing that just wrap your setState by if statement like this :

 if(mounted){
   setState((){

   });
}
巾帼英雄 2025-01-18 00:59:37

如果某些方法会重建某些正在渲染的小部件,则您无法调用 initState 内的方法。

要解决这个问题,您应该使用控制器中的 onReady 方法。

您应该将所有变量移至控制器类。

class PageLogic extends GetxController {

  int currentValue = 0;
  // move all your veriables here (TextEditingControllers, all)


  @override
  void onReady(){

   make you logic for initialization here
   

   super.onReady();
  }


  void handleCounterChange(int value) {
    currentValue = value;
    update();
  }



}

检索控制器并在页面内使用

final pageLogic = PageLogin();

You cannot call methods inside initState if some method would rebuild some widgets that are being rendered.

To solved that you should use onReady method from the controller.

You should move all your variables to the controller class.

class PageLogic extends GetxController {

  int currentValue = 0;
  // move all your veriables here (TextEditingControllers, all)


  @override
  void onReady(){

   make you logic for initialization here
   

   super.onReady();
  }


  void handleCounterChange(int value) {
    currentValue = value;
    update();
  }



}

Retrieve the controller and use inside your page

final pageLogic = PageLogin();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文