繁体   English   中英

Flutter 关于重用有状态小部件和更新 state 的问题

[英]Flutter issue on reusing stateful widget and updating state

我有这个繁忙的按钮逻辑,在 api 调用中,我可以通过在网络请求事件中加载指示器来替换小部件,直到它完成。

_BusyButtonState buttonState;

class BusyButton extends StatefulWidget {
  final onTap, text;
  BusyButton({Key key, this.text, this.onTap});
  @override
  _BusyButtonState createState() {
    buttonState = _BusyButtonState();
    return buttonState;
  }
}

class _BusyButtonState extends State<BusyButton> {
  bool isBusy = false;
  void notLoading() {
    setState(() {
      isBusy = false;
    });
  }

  void loading() {
    setState(() {
      isBusy = true;
    });
  }

  @override
  Widget build(BuildContext context) {
    return isBusy
        ? CircularProgressIndicator(
            valueColor: AlwaysStoppedAnimation(Colors.blue),
            strokeWidth: 1.5,
          )
        : RaisedButton(
            color: Colors.blue,
            child:
                Text('${widget.text}', style: TextStyle(color: Colors.white)),
            onPressed: widget.onTap);
  }
}

我有listview builder,我在每个项目上使用此按钮将项目的状态从活动更改为非活动,反之亦然。

BusyButton(
  key: UniqueKey(),
  text: active?"Inactive":"Active"
  onTap: () {
      sendToServer(active?true:false)
   },
)

sendToServer(bool active) async{
try {
      updateState.loading();
      var response = await CallApi().putData(
          {"active": active.toString()}, "url");
      if (response.data['success']) {
        updateState.notLoading();
        print("done");
      } else {
        updateState.notLoading();
        print("error");
      }
    } catch (e) {
      updateState.notLoading();
      print(e);
    }
}

但是当我尝试按下按钮时,如果网络请求成功但加载指示器出现在列表视图中的某个随机按钮上,它会起作用。 它还会在请求失败时引发以下错误。

E/flutter (25919): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: setState() called after dispose(): _OutlinedButtonState#971b3(lifecycle state: defunct, not mounted)

我该如何解决这个问题?

尝试使用 setState。

BusyButton(
      key: UniqueKey(),
      text: active?"Inactive":"Active"
      onTap: () {
         setState(){
          sendToServer(active?true:false)
         }
       },
    )

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM