抛出了另一个异常:NoSuchMethodError:在 null 上调用了方法“[]”。颤振中的错误登录api

时间:2021-03-12 10:07:45

标签: java api flutter dart

以下是错误代码,我遇到了一个错误,方法是在null上调用。请在此处帮助开发人员:

I/flutter (15897):{"status":"Ok","code":200,"authorization":"86f3d01a-150c-34d5-bb61-3ad7052e0248:oIX1qxHuYD2q6f3LkPSZisqBId"," "dWVOT3Y2TzRPV2t4UDVzckJaU0tSUT09","user":{"first_name":"mahar","last_name":"catur","email":"mahar.catur@gmai l.com","phone":"6285959640524"},"message":"登录成功","timestamp":"2021-03-12 07:41:21.72"} I/flutter (15897): 抛出另一个异常:NoSuchMethodError: The method '[]' was called on null.

This is an error code:
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:http/io_client.dart';
import 'package:device_info/device_info.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:selon_mart/Components/custom_surfix_icon.dart';
import 'package:selon_mart/Components/form_error.dart';
import 'package:flutter_bcrypt/flutter_bcrypt.dart';
import 'package:selon_mart/helper/keyboard.dart';
import 'package:selon_mart/Auth/login_navigator.dart';
import 'package:selon_mart/forgot_password/forgot_password_screen.dart';
import 'package:selon_mart/login_success/login_success_screen.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:http/http.dart' as http;
import 'package:selon_mart/util/api.dart';
import 'package:selon_mart/HomeOrderAccount/Home/UI/home.dart';

import 'scaffold_wrapper.dart';

import 'themes/colors.dart';
import 'themes/fonts.dart';

import 'package:selon_mart/Components/default_button.dart';
import 'package:selon_mart/contants.dart';
import 'package:selon_mart/size_config.dart';

class SignForm extends StatefulWidget {
  @override
  _SignFormState createState() => _SignFormState();
}

class _SignFormState extends State<SignForm> {
  final _formKey = GlobalKey<FormState>();
  String email;
  final usernameController = TextEditingController();
  final passwordController = TextEditingController();
  String passwordHash;
  bool remember = false;
  final List<String> errors = [];
  // final deviceTarget = nativeRuntime.instanceNamed('UIDevice');

  DeviceInfoPlugin deviceInfo =
  DeviceInfoPlugin(); // instantiate device info plugin
  AndroidDeviceInfo androidDeviceInfo;
  IosDeviceInfo iosDeviceInfo;
  String deviceIdAndroid = "";
  String deviceIdIos = "";

  bool password = true;

  void _toggle() {
    setState(() {
      password = !password;
    });
  }

  void getDeviceinfoAndroid() async {
    androidDeviceInfo =
    await deviceInfo.androidInfo; // instantiate Android Device Information
    setState(() {
      deviceIdAndroid = androidDeviceInfo.androidId;
    });
  }

  void getDeviceinfoIos() async {
    iosDeviceInfo =
    await deviceInfo.iosInfo; // instantiate Ios Device Information
    setState(() {
      deviceIdIos = iosDeviceInfo.identifierForVendor;
    });
  }

  Future<void> hash() async {
    _login();
  }


  void addError({String error}) {
    if (!errors.contains(error))
      setState(() {
        errors.add(error);
      });
  }

  void removeError({String error}) {
    if (errors.contains(error))
      setState(() {
        errors.remove(error);
      });
  }



  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formKey,
      child: Column(
        children: [
          buildEmailFormField(),
          SizedBox(height: getProportionateScreenHeight(30)),
          buildPasswordFormField(),
          SizedBox(height: getProportionateScreenHeight(30)),
          Row(
            children: [
              Checkbox(
                value: remember,
                activeColor: kPrimaryColor,
                onChanged: (value) {
                  setState(() {
                    remember = value;
                  });
                },
              ),
              Text("Remember me"),
            ],
          ),
          FormError(errors: errors),
          SizedBox(height: getProportionateScreenHeight(30)),
          Row (
            children: [
              GestureDetector(
                onTap: () =>
                    Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) => LoginNavigator())
                    ),
                child: Text("Login via phone",
                  style:  TextStyle(decoration: TextDecoration.underline),
                ),
              )
            ],
          ),
          FormError(errors: errors),
          SizedBox(height: getProportionateScreenHeight(30)),
          Row (
            children: [
              GestureDetector(
                onTap: () => Navigator.pushNamed(
                    context, ForgotPasswordScreen.routeName),
                child: Text(
                  "Forgot Password",
                  style: TextStyle(decoration: TextDecoration.underline),
                ),
              ),
            ],
          ),
          FormError(errors: errors),
          SizedBox(height: getProportionateScreenHeight(20)),
          buttonLogin(context),
        ],
      ),
    );
  }

  void _showLoading(String text) {
    showDialog(
      context: context,
      barrierDismissible: false,
      child: Dialog(
        child: Padding(
          padding: EdgeInsets.fromLTRB(25, 20, 25, 20),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              new CircularProgressIndicator(),
              new Padding(
                padding: EdgeInsets.all(20),
                child: Text(text),
              ),
            ],
          ),
        ),
      ),
    );
  }

  TextFormField buildPasswordFormField() {
    return TextFormField(
      controller: passwordController,
      obscureText: password,
      onChanged: (value) {
        if (value.isNotEmpty) {
          removeError(error: kPassNullError);
        } else if (value.length >= 8) {
          removeError(error: kShortPassError);
        }
        return null;
      },
      validator: (value) {
        if (value.isEmpty) {
          addError(error: kPassNullError);
          return "";
        } else if (value.length < 8) {
          addError(error: kShortPassError);
          return "";
        }
        return null;
      },
      decoration: InputDecoration(
        labelText: "Password",
        hintText: "Enter your password",
        // If  you are using latest version of flutter then lable text and hint text shown like this
        // if you r using flutter less then 1.20.* then maybe this is not working properly
        floatingLabelBehavior: FloatingLabelBehavior.always,
        suffixIcon: IconButton(
          color: Colors.black,
          onPressed: () {
            setState(() {
          _toggle();
            });
        },
          icon: password
            ? Icon(MdiIcons.eyeOffOutline)
              : Icon(MdiIcons.eyeOutline),
        ),
      ),
    );
  }

  Widget buttonLogin(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 25.0),
      child: FlatButton(
        onPressed: () {
          setState(() {
            _login();
          });
        },
        padding: EdgeInsets.all(0),
        child: Ink(
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(6),
            color: Colors.red,
          ),
          child: Container(
            alignment: Alignment.center,
            constraints:
            BoxConstraints(maxWidth: double.infinity, minHeight: 50),
            child: Text(
              "Masuk",
              style: ThemeFonts.textStyle600
                  .copyWith(fontSize: 18, color: Colors.white),
            ),
          ),
        ),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(6),
        ),
      ),
    );
  }

  TextFormField buildEmailFormField() {
    return TextFormField(
      keyboardType: TextInputType.emailAddress,
      controller: usernameController,
      onSaved: (newValue) => email = newValue,
      onChanged: (value) {
        if (value.isNotEmpty) {
          removeError(error: kEmailNullError);
        } else if (emailValidatorRegExp.hasMatch(value)) {
          removeError(error: kInvalidEmailError);
        }
        return null;
      },
      validator: (value) {
        if (value.isEmpty) {
          addError(error: kEmailNullError);
          return "";
        } else if (!emailValidatorRegExp.hasMatch(value)) {
          addError(error: kInvalidEmailError);
          return "";
        }
        return null;
      },
      decoration: InputDecoration(
        labelText: "Email",
        hintText: "Enter your email",
        floatingLabelBehavior: FloatingLabelBehavior.always,
        suffixIcon: CustomSurffixIcon(svgIcon: "assets/icons/Mail.svg"),
      ),
    );
  }

  Future<Null> _login() async {
    print("Login");
    try {
      // HttpClient client = new HttpClient();
      // client.badCertificateCallback = ((X509Certificate cert, String host, int port) => true);
      _showLoading("Please Wait...");
      SharedPreferences prefs = await SharedPreferences.getInstance();
      var dtUname = usernameController.text;
      var dtPass = passwordController.text;
      // final ioc = new HttpClient();
      // ioc.badCertificateCallback =
          // (X509Certificate cert, String host, int port) => true;
      // final http = new IOClient(ioc);

      // set up POST request arguments
      var headers = {"Content-Type": "application/json" ,"Accept": "application/json"};

      // make POST request
      final msg = jsonEncode({
        "email": dtUname,
        "password": dtPass,
        "device": "android"});

      return http.post(await Env().postLoginCustomer(), headers: headers,
          body: msg
      ).then((response) {
        print(response.body);
        final body = jsonDecode(response.body);

        if (body["code"] == "200" && body["status"] == "Ok") {
          prefs.setString("userid", body['data']['userid']);
          prefs.setString("email", body['data']['email']);
          prefs.setInt("password", body['data']['password']);
          setState(() {
            // Navigator.pop(context);
            Navigator.pushReplacement(
              context,
              MaterialPageRoute(
                builder: (context) => HomePage(),
              ),
            );
          });
        } else if (body["code"] == "404"){
          addError(error: kPassNullError);
        } else {
          setState(() {
            Navigator.pop(context);
          });
          showDialog(
            barrierDismissible: false,
            context: context,
            builder: (BuildContext context) {
              return AlertDialog(
                title: Text(
                  body['data']['message'],
                  style: ThemeFonts.textStyle500
                      .copyWith(fontSize: 16, color: Colors.black),
                ),
                // content: Text(body['data']),
                actions: <Widget>[
                  new RaisedButton(
                    child: Text('Ok'),
                    textColor: Colors.grey,
                    onPressed: () {
                      Navigator.pop(context);
                    },
                  ),
                ],
              );
            },
          );
        }
      }).catchError((error) {
        print(error);
      });
    } catch (e) {
      print(e);
    }
    return null;
  }
}

谁能帮忙,我想用api在flutter中创建一个登录系统,回调已经在但是方法错误,我可以帮你吗?

1 个答案:

答案 0 :(得分:1)

试试改变这个

else if (body["code"] == "404"){
          addError(error: kPassNullError);
        } else {
          setState(() {
            Navigator.pop(context);
          });
          showDialog(
            barrierDismissible: false,
            context: context,
            builder: (BuildContext context) {
              return AlertDialog(
                title: Text(
                  body['data']['message'],
                  style: ThemeFonts.textStyle500
                      .copyWith(fontSize: 16, color: Colors.black),
                ),
                // content: Text(body['data']),
                actions: <Widget>[
                  new RaisedButton(
                    child: Text('Ok'),
                    textColor: Colors.grey,
                    onPressed: () {
                      Navigator.pop(context);
                    },
                  ),
                ],
              );
            },

为此

else {
  if(body["code"] == "404"){
     addError(error: kPassNullError);
  } else {
     setState(() {
        Navigator.pop(context);
      });
      showDialog(
        barrierDismissible: false,
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text(
              body['data']['message'],
              style: ThemeFonts.textStyle500
                  .copyWith(fontSize: 16, color: Colors.black),
            ),
            // content: Text(body['data']),
            actions: <Widget>[
              new RaisedButton(
                child: Text('Ok'),
                textColor: Colors.grey,
                onPressed: () {
                  Navigator.pop(context);
                },
              ),
            ],
          );
  }
}