setter'msg ='在null上被调用

时间:2019-01-26 15:53:09

标签: dart flutter

我正在用Flutter向api发送请求,并将响应值保存在我的模型之一的实例中。但是我遇到一些奇怪的错误。您可以看到下面的代码和错误。我正在使用scoped_model进行状态管理。

import 'dart:convert';
import 'dart:async';
import 'dart:io';

import 'package:shared_preferences/shared_preferences.dart';
import 'package:scoped_model/scoped_model.dart';
import 'package:http/http.dart' as http;
import 'package:rxdart/subjects.dart';


class Patient {
  final String guid;
  final String phone;
  final String token;
  final String name;
  final String lastName;

  Patient({@required this.guid, @required this.phone, @required this.token , @required this.name , @required this.lastName });
}

class RTN {
   String msg = '';
   String success = 'false';
   String guid ='';
   String srcPath ='';
   String thumbPath ='';
   dynamic obj ='';

  RTN(
      {@required this.msg,
      @required this.guid,
      @required this.obj,
      @required this.srcPath,
      @required this.success,
      @required this.thumbPath});
}



class MainModel extends Model with Connected, PatientModel, UtilityModel {
}

mixin Connected on Model {
  List<Doctor> _doctor = [];
  Patient _authenticatedPatient;
  bool _isLoading = false;
  RTN _rtn;
  RTN get rtn{
    return _rtn;
  }

  List<Doctor> get allDrs {
    return List.from(_doctor);
  }
}

mixin PatientModel on Connected {
  PublishSubject<bool> _patientSubject = PublishSubject();

  Patient get patient {
    return _authenticatedPatient;
  }

  PublishSubject<bool> get patientSubject {
    return _patientSubject;
  }

  Future<Map<String, dynamic>> authenticateFirst(String phone) async {
    try{
    _isLoading = true;
    notifyListeners();
    final Map<String, dynamic> authFirstData = {
      'Phone': phone,
    };
    http.Response response;
    response = await http.post(
      'http://guffy.ir/Auth/RegisterOne',
      body: json.encode(authFirstData),
      headers: {'Content-Type': 'application/json'},
    );

    final Map<String, dynamic> responseData = json.decode(response.body);
    print(responseData);
    bool hasError = true;
    String message = '';
    print(responseData);
    if (responseData.containsKey("guid")) {
       hasError = false;
      rtn.msg = responseData["msg"];
      rtn.guid = responseData["guid"];
      rtn.obj = responseData["obj"];
      rtn.srcPath = responseData["srcPath"];
      rtn.success = responseData["success"];
      rtn.thumbPath = responseData["thumbPath"];
      message = rtn.msg;
      _authenticatedPatient = Patient(
        guid: responseData["guid"],
        phone: phone,
        token: null,
        name: null,
        lastName: null,
      );
      // _patientSubject.add(true);
      final SharedPreferences prefs = await SharedPreferences.getInstance();
      prefs.setString('token', '');
      prefs.setString('patientPhone', phone);
      prefs.setString('patientGuid', responseData['guid']);
      prefs.setString('name', '');
      prefs.setString('lastName', '');
    }
    _isLoading = false;
    notifyListeners();
    return {'success': !hasError, 'message': message};
  }
  catch(error){
    _isLoading = false;
    print(error);
  }}
  Future<Map<String, dynamic>> authenticateSecond(String phone) async {
    _isLoading = true;
    notifyListeners();
    final Map<String, dynamic> authFirstData = {
      'Phone': phone,
    };
    http.Response response;
    response = await http.post(
      'http://guffy.ir/Auth/RegisterOne',
      body: json.encode(authFirstData),
      headers: {'Content-Type': 'application/json'},
    );

    final Map<String, dynamic> responseData = json.decode(response.body);
    print(responseData);
    bool hasError = true;
    String message = '';
    print(responseData);
    if (responseData.containsKey('guid')) {
      hasError = false;
      message = responseData['msg'];
      _authenticatedPatient = Patient(
        guid: responseData['guid'],
        phone: phone,
        token: null,
        name: null,
        lastName: null,
      );
      // _patientSubject.add(true);
      final SharedPreferences prefs = await SharedPreferences.getInstance();
      prefs.setString('token', null);
      prefs.setString('patientPhone', phone);
      prefs.setString('patientGuid', responseData['guid']);
      prefs.setString('name', null);
      prefs.setString('lastName', null);
    }
    _isLoading = false;
    notifyListeners();
    return {'success': !hasError, 'message': message};
  }
    Future<Map<String, dynamic>> authenticateThird(String phone) async {
    _isLoading = true;
    notifyListeners();
    final Map<String, dynamic> authThirdData = {
      'Phone': phone,
    };
    http.Response response;
    response = await http.post(
      'http://guffy.ir/Auth/RegisterOne',
      body: json.encode(authThirdData),
      headers: {'Content-Type': 'application/json'},
    );

    final Map<String, dynamic> responseData = json.decode(response.body);
    print(responseData);
    bool hasError = true;
    String message = '';
    print(responseData);
    if (responseData.containsKey('guid')) {
      hasError = false;
      message = responseData['msg'];
      _authenticatedPatient = Patient(
        guid: responseData['guid'],
        phone: phone,
        token: null,
        name: null,
        lastName: null,
      );
      _patientSubject.add(true);
      final SharedPreferences prefs = await SharedPreferences.getInstance();
      prefs.setString('token', null);
      prefs.setString('patientPhone', phone);
      prefs.setString('patientGuid', responseData['guid']);
      prefs.setString('name', null);
      prefs.setString('lastName', null);
    }
    _isLoading = false;
    notifyListeners();
    return {'success': !hasError, 'message': message};
  }
  void autoAuthenticate() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    final String name = prefs.getString('name');
    final String lastName = prefs.getString('lastName');
    if (name != '' && lastName != '') {
      final String patientPhone = prefs.getString('patientPhone');
      final String patientGuid = prefs.getString('patientGuid');
      final String token = prefs.getString('token');
      _authenticatedPatient =
          Patient(guid: patientGuid, phone: patientPhone, token: token , name: name , lastName: lastName);
      _patientSubject.add(true);
      notifyListeners();
    }
  }

  void logout() async {
    _authenticatedPatient = null;
    _patientSubject.add(false);
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.remove('token');
    prefs.remove('PatientEmail');
    prefs.remove('PatientId');
  }
}
mixin UtilityModel on Connected {
  bool get isLoading {
    return _isLoading;
  }
}

这是我从api得到的响应:

{msg: کد ارسال شد, success: true, guid: 15dde915-d752-4bf1-90ad-49872868af35, srcPath: null, thumbPath: null, obj: null}

这是我得到的错误:

I/flutter (10151): NoSuchMethodError: The setter 'msg=' was called on null.
I/flutter (10151): Receiver: null
I/flutter (10151): Tried calling: msg="کد ارسال شد"
E/flutter (10151): [ERROR:flutter/shell/common/shell.cc(184)] Dart Error: Unhandled exception:
E/flutter (10151): NoSuchMethodError: The method '[]' was called on null.
E/flutter (10151): Receiver: null
E/flutter (10151): Tried calling: []("success")
E/flutter (10151): #0      Object.noSuchMethod (dart:core/runtime/libobject_patch.dart:50:5)
E/flutter (10151): #1      _AuthOnePageState._submitForm (package:restt/pages/authone.dart:93:27)
E/flutter (10151): <asynchronous suspension>

2 个答案:

答案 0 :(得分:1)

该错误表示您尝试访问空对象上的字段msg,这很可能是以下行:

rtn.msg = responseData["msg"];

您只需要在使用它之前实例化该对象:

RTN _rtx;
RTN get rtn {
    if (_rtn == null) {
        _rtx = RTN(); // Instantiate the object if its null.
    }
    return _rtn;
}

答案 1 :(得分:0)

初始化类就足够了

RTN _rtx = RTN();