java - 引发了另一个异常:NoSuchMethodError:在 null 上调用了方法“[]”。颤动中的错误登录api
问题描述
以下是错误代码,我遇到了一个错误,方法是在 null 上调用。请在这里帮助开发人员:
I/flutter (15897): {"status":"Ok","code":200,"authorization":"86f3d01a-150c-34d5-bb61-3ad7052e0248:oIX1qxHuYD2q6f3LkPSZisxEpTP1atCQSqKwcT/ugBI=","userid":"dWVOT3Y2TzRPV209UzckJUTV" ,"用户":{"first_name":"mahar","last_name":"catur","email":"mahar.catur@gmai l.com","电话":"6285959640524"},"消息": "登录成功","timestamp":"2021-03-12 07:41:21.72"} I/flutter (15897): 另一个异常被抛出: NoSuchMethodError: 方法 '[]' 在 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创建一个登录系统,回调已经在但是方法错误,我可以帮助你吗?
解决方案
尝试改变这个
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);
},
),
],
);
}
}
推荐阅读
- javascript - 在将 API 数据传递到组件方面需要帮助
- jquery - 如何使用 jquery 在引导时间选择器中禁用过去的时间
- reactjs - 如何在reactjs中的cellrenderer中添加模态
- c# - C# 在哈希中存储和检索对象属性
- python-3.x - 如何以 UTF-8 格式打开 HTML 文件进行解析?
- r - 如何使用另一个数据框根据多个条件过滤数据框
- react-native - 我在使用 react-navigation 在 tab-navigator 中制作 stack-navigator 时遇到问题
- docker - 日志文件保存在 docker 容器中的什么位置以及如何复制它?
- java - StringDate to Date 在 java 中 SimpleDateFormat 中的不同时间出现
- c# - .NET 核心中的 gRPC 和分布式事务