The getter 'data' was called on null.

来源:3-6 hi_net统一异常和返回处理与Adapter模式设计

慕先生4316985

2021-12-24

图片描述

import 'package:bibilili/http/core/hi_adapter.dart';
import 'package:bibilili/http/core/hi_error.dart';
import 'package:bibilili/http/core/mock_adapter.dart';
import 'package:bibilili/http/request/base_request.dart';


class HiNet{
  HiNet._();
  static HiNet _instance;
  static HiNet getInstance(){
    _instance= HiNet._();
    return _instance;
  }
  Future fire(BaseRequest request) async {
   HiNetResponse response;
    var error;
    try{
      response = await send(request);
    } on HiNetError catch(e){
      error = e;
      response=e.data;
      printLog(e.message);
    } catch(e){
      //其他异常
      error = e;
      printLog(e);
    }

    if(response==null){
      printLog(error);
    }

    var result = response.data;
    printLog(result);

    var status = response.statusCode;
    switch(status){
      case 200:
        return result;
      case 401:
        throw NeedLogin();
      case 403:
        throw NeedAuth(request.toString(),data: result);
      default:
        throw HiNetError(status, result.toString(),data:result);
    }
  }

  Future<dynamic> send<T>(BaseRequest request) async {
    printLog("url:${request.url()}");
    ///使用Mock发送请求
    HiNetAdapter adapter=MockAdapter();
    return adapter.send(request);
  }
  void printLog(log){
    print("hi_net:${log.toString()}");
  }
}
写回答

1回答

CrazyCodeBoy

2021-12-27

第30当response为空的时候加个 return
或者做下空安全适配,可参考下这块的实现:https://git.imooc.com/coding-487/fa-net/src/master/lib/http/core/hi_net.dart#L24

0
0

Flutter高级进阶实战-仿哔哩哔哩-掌握Flutter高阶技能

一次性掌握Flutter高阶技能+商业级复杂项目架构设计与开发方案

1723 学习 · 870 问题

查看课程