Flutter 封装请求方法类时使用了工厂构造函数的单例模式,在调试时为了按需控制请求打印日志,最好的方法就是往请求体中传参数控制,可是想了好久都不晓得怎么个传参法,后来查看 GitHub 时得到了解决方法,具体如下。

class NetUtil {
  static final NetUtil _instance = NetUtil._internal();
  static bool showLog = false;

  factory NetUtil([bool isShowLog = false]) {
    showLog = isShowLog;
    return _instance;
  }

  NetUtil._internal() {
    if (showLog) {
      // 省略无关代码
    }
  }

  Future get(String url) async {}

  Future post(String url) async {}
}

main() {
  // 调用
  NetUtil(true).get('');
}

参考

https://gist.github.com/theburningmonk/6401183#gistcomment-2903680

相关文章:

  • 2021-05-30
  • 2022-12-23
  • 2021-11-14
  • 2021-07-17
  • 2021-10-27
  • 2021-10-18
  • 2022-01-15
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-05-28
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-01
相关资源
相似解决方案