1

E/flutter (32633): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: NoSuchMethodError: The getter 'statusCode' was called on null. E/flutter (32633): Receiver: null E/flutter (32633): Tried calling: statusCode E/flutter (32633): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5) E/flutter (32633): #1 APIService.createCustomer E/flutter (32633): #2 _SignupPageState._formUI.

    class APIService {
  Future<bool> createCustomer(CustomerModel model) async {
    var authToken = base64.encode(
      utf8.encode(Config.key + ':' + Config.sceret),
    );

    bool ret = false;
    Dio dio = Dio();
    if (Platform.isAndroid) {
      (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
          (client) {
        client.badCertificateCallback =
            (X509Certificate cert, String host, int port) => true;
        return client;
      };
    }

    try {
      var response = await Dio().post(Config.url + Config.customerURL,
          data: model.toJson(),
          options: new Options(headers: {
            HttpHeaders.authorizationHeader: 'Basic $authToken',
            HttpHeaders.contentTypeHeader: 'application/json'
          }));

      if (response.statusCode == 201) {
        ret = true;
      }
    } on DioError catch (e) {
      if (e.response.statusCode == 404) {
        ret = false;
      } else {
        ret = false;
      }
    }
    return ret;
  }
}



    class SignupPage extends StatefulWidget {
  @override
  _SignupPageState createState() => _SignupPageState();
}

class _SignupPageState extends State<SignupPage> {
  APIService apiService;
  CustomerModel model;
  GlobalKey<FormState> globalKey = GlobalKey<FormState>();
  bool hidePassword = true;
  bool isApiCallProcess = false;

  @override
  void initState() {
    apiService = new APIService();
    model = new CustomerModel();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.red,
        automaticallyImplyLeading: true,
        title: Text('Sign Up'),
      ),
      body: ProgressHUD(
          child: Form(
            key: globalKey,
            child: _formUI(),
          ),
          inAsyncCall: isApiCallProcess,
          opacity: 0.3),
    );
  }

  Widget _formUI() {
    return SingleChildScrollView(
      child: Padding(
        padding: EdgeInsets.all(10.00),
        child: Container(
          child: Align(
            alignment: Alignment.topLeft,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                FormHelper.fieldLabel('First Name'),
                FormHelper.textInput(
                  context,
                  model.firstName,
                  (value) => {
                    this.model.firstName = value,
                  },
                  onValidate: (value) {
                    if (value.toString().isEmpty) {
                      return 'Please enter First Name.';
                    }
                    return null;
                  },
                ),
                FormHelper.fieldLabel('Last Name'),
                FormHelper.textInput(
                  context,
                  model.lastName,
                  (value) => {
                    this.model.lastName = value,
                  },
                  onValidate: (value) {
                    return null;
                  },
                ),
                FormHelper.fieldLabel('Email Id'),
                FormHelper.textInput(
                  context,
                  model.email,
                  (value) => {
                    this.model.email = value,
                  },
                  onValidate: (value) {
                    if (value.toString().isEmpty) {
                      return 'Please enter Email id.';
                    }
                    if (value.isNotEmpty && !value.toString().isValidEmail()) {
                      return 'Please enter valid email id';
                    }
                    return null;
                  },
                ),
                FormHelper.fieldLabel('Password'),
                FormHelper.textInput(
                  context,
                  model.password,
                  (value) => {
                    this.model.password = value,
                  },
                  onValidate: (value) {
                    if (value.toString().isEmpty) {
                      return 'Please enter Password.';
                    }
                    return null;
                  },
                  obscureText: hidePassword,
                  suffixIcon: IconButton(
                    onPressed: () {
                      setState(() {
                        hidePassword = !hidePassword;
                      });
                    },
                    color: Theme.of(context).accentColor.withOpacity(0.4),
                    icon: Icon(
                      hidePassword ? Icons.visibility_off : Icons.visibility,
                    ),
                  ),
                ),
                SizedBox(
                  height: 20,
                ),
                Center(
                  child: FormHelper.saveButton(
                    'Register',
                    () {
                      if (validateAndSave()) {
                        print(model.toJson());
                        setState(() {
                          isApiCallProcess = true;
                        });
                        apiService.createCustomer(model).then(
                          (ret) {
                            setState(() {
                              isApiCallProcess = false;
                            });

                            if (ret) {
                              FormHelper.showMessage(
                                context,
                                'WooCommerce App',
                                'Registration Successfull',
                                'Ok',
                                () {
                                  Navigator.of(context).pop();
                                },
                              );
                            } else {
                              FormHelper.showMessage(
                                context,
                                'WooCommerce App',
                                'Email Id already registered.',
                                'Ok',
                                () {
                                  Navigator.of(context).pop();
                                },
                              );
                            }
                          },
                        );
                      }
                    },
                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }

  bool validateAndSave() {
    final form = globalKey.currentState;
    if (form.validate()) {
      form.save();
      return true;
    }
    return false;
  }
}
Aziz
  • 11
  • 3
  • Have you tried to check the API using another software like Postman? – Filipe Piletti Plucenio Nov 17 '20 at 02:59
  • Hi, yes API is working in Postman (OAuth 1.0), but when i am posting data in sign in form, i am getting "StatusCode" error. below are my confing.dart file. class Config { static String key = 'ck_389f7130c9cb72caeb2d9acb76de61b79c2af623'; static String sceret = 'cs_d0a66c70e0a6b1309c84d694dc159a428e900623'; static String url = 'http://10.0.2.2:80/wordpress_new/wp-json/wc/v3/'; static String customerURL = 'customers'; } – Aziz Nov 17 '20 at 03:16
  • Seems the response is null. If you look here(https://pub.dev/packages/dio#dioerror-scheme), there is a case of Dio' response null. In flutter, most nosuchmethod errors are when null is used(https://stackoverflow.com/questions/62895099/flutter-unhandled-exception-nosuchmethoderror-the-getter-id-was-called-on-n). – sh.seo Nov 17 '20 at 07:21
  • 1
    Does this answer your question? [What is a NoSuchMethod error and how do I fix it?](https://stackoverflow.com/questions/64049102/what-is-a-nosuchmethod-error-and-how-do-i-fix-it) – nvoigt Nov 17 '20 at 11:18

1 Answers1

1

The error NoSuchMethodError: The getter 'statusCode' was called on null points to the statusCode was called on a null method. The likely cause of this issue was from response being null.

I suggest initializing response first with var response = Response();, then try using String interpolation for the URL, '${Config.url}${Config.customerURL}' instead of using the + operator.

var response = Response();
try {
  response = await Dio().post('${Config.url}${Config.customerURL}',
      data: model.toJson(),
      options: new Options(headers: {
        HttpHeaders.authorizationHeader: 'Basic $authToken',
        HttpHeaders.contentTypeHeader: 'application/json'
      }));

    // ...
  } on DioError catch (e) {
    // ...
  }
}
Omatt
  • 8,564
  • 2
  • 42
  • 144