如何解决“ [错误:方法'[]'在null上调用。E / flutter(18386):接收器:null” flutter

时间:2019-09-10 10:42:49

标签: exception flutter null flutter-layout unhandled

import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'Models/UserData.dart';

class LoginScreen extends StatefulWidget {
  static const String id = '/login_screen';

  @override
  State<StatefulWidget> createState() {
    return _LoginPageState();
  }
}

class _LoginPageState extends State<LoginScreen> {

  static var url = "url";

  static BaseOptions options = BaseOptions(
      baseUrl: url,
      responseType: ResponseType.plain,
      connectTimeout: 30000,
      receiveTimeout: 30000,
      validateStatus: (code) {
        if (code >= 200) {
          return true;
        }
      });

  static Dio dio = Dio(options);

  GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  TextEditingController _emailController = TextEditingController();

  TextEditingController _passwordController = TextEditingController();

  UserData userData;

  @override
  void initState() {
    SystemChrome.setEnabledSystemUIOverlays([]);
    userData = UserData();
    super.initState();
  }

  Future<Map<String, dynamic>> _loginUser(String email, String password, String version) async {
    try {
      Options options = Options(
        contentType: ContentType.parse('application/json'),
      );

      final Response response = await dio.post<Map<String, dynamic>>(url + '/users/login',
          data: {'login': _emailController, 'pwd': _passwordController, 'version' :'2.0'}, options: options);

      print(url + '/users/login');

      if (response.statusCode == 200 || response.statusCode == 201) {
        return json.decode(response.data);
      } else if (response.statusCode == 401) {
        throw Exception("Incorrect Email/Password");
      } else
        throw Exception('Authentication Error');
    } on DioError catch (exception) {
      if (exception == null ||
          exception.toString().contains('SocketException')) {
        throw Exception("Network Error");
      } else if (exception.type == DioErrorType.RECEIVE_TIMEOUT ||
          exception.type == DioErrorType.CONNECT_TIMEOUT) {
        throw Exception(
            "Could'nt connect, please ensure you have a stable network.");
      } else {
        return null;
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    bool _isLoading = false;
    String version = '2.0';
    bool _obscureText = true;

    return Scaffold(
      body: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            Container(
              width: MediaQuery
                  .of(context)
                  .size
                  .width,
              height: MediaQuery
                  .of(context)
                  .size
                  .height / 2.5,
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter,
                  colors: [Colors.white, Colors.white],
                ),
                borderRadius: BorderRadius.only(
                  bottomLeft: Radius.circular(90),
                ),
              ),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Spacer(),
                  Align(
                    alignment: Alignment.center,
                    child: Image.asset('assets/logo.png'),
                  ),
                  Spacer(),
                  Align(
                    alignment: Alignment.bottomRight,
                    child: Padding(
                      padding: const EdgeInsets.only(bottom: 32, right: 32),
                      child: Text(
                        'Customer App',
                        style: TextStyle(color: Colors.red, fontSize: 18),
                      ),
                    ),
                  ),
                ],
              ),
            ),
            Container(
              color: Colors.white,
              height: MediaQuery
                  .of(context)
                  .size
                  .height / 1,
              width: MediaQuery
                  .of(context)
                  .size
                  .width,
              padding: EdgeInsets.only(top: 20),
              child: Column(
                children: <Widget>[
                  Container(
                    width: MediaQuery
                        .of(context)
                        .size
                        .width / 1.2,
                    height: 45,
                    padding:
                    EdgeInsets.only(top: 2, left: 16, right: 16, bottom: 2),
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.all(Radius.circular(50)),
                        color: Colors.white,
                        boxShadow: [
                          BoxShadow(color: Colors.red, blurRadius: 5)
                        ]),
                    child: TextField(
                      controller: _emailController,
                      decoration: InputDecoration(
                        errorText: _isLoading ? 'Value Can\'t Be Empty' : null,
                        border: InputBorder.none,
                        icon: Icon(
                          Icons.email,
                          color: Colors.red,
                        ),
                        hintText: 'Email',
                      ),
                      keyboardType: TextInputType.emailAddress,
                    ),
                  ),
                  const SizedBox(
                    width: 42.0,
                    height: 20.0,
                  ),
                  Container(
                    width: MediaQuery
                        .of(context)
                        .size
                        .width / 1.2,
                    height: 45,
                    padding:
                    EdgeInsets.only(top: 2, left: 16, right: 16, bottom: 2),
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.all(Radius.circular(50)),
                        color: Colors.white,
                        boxShadow: [
                          BoxShadow(color: Colors.red, blurRadius: 8)
                        ]),
                    child: TextField(
                      obscureText: _obscureText,
                      controller: _passwordController,
                      inputFormatters: [LengthLimitingTextInputFormatter(10)],
                      decoration: InputDecoration(
                        border: InputBorder.none,
                        icon: Icon(
                          Icons.lock_open,
                          color: Colors.red,
                        ),
                        hintText: 'Password',
                      ),
                      keyboardType: TextInputType.text,
                    ),
                  ),
                  Container(
                    height: 45,
                    margin: EdgeInsets.only(top: 22),
                    width: MediaQuery
                        .of(context)
                        .size
                        .width / 1.2,
                    decoration: BoxDecoration(
                        color: Colors.red,
                        borderRadius: BorderRadius.all(Radius.circular(50))),
                    child: Center(
                      child: InkWell(
                        onTap: () async {
                          FocusScope.of(context).requestFocus(new FocusNode());
                          setState(() => _isLoading = true,);
                          Navigator.of(context)
                                .pushReplacementNamed('/home_screen');
                          var res = await _loginUser(
                              _emailController.text, _passwordController.text,version);
                          final UserData users = UserData.fromJson(res);
                          List<Map> items = json.decode("response.body");
                          List<UserData> listOfDesig = items.map((json) => UserData.fromJson(json)).toList();
                          if (listOfDesig != null) {
                            Navigator.of(context)
                                .pushReplacementNamed('/home_screen');
                          } else {
                            Scaffold.of(context).showSnackBar(
                                SnackBar(content: Text("Wrong email")));
                          }
                        },
                        child: Text(
                          'Login'.toUpperCase(),
                          style: TextStyle(
                              color: Colors.white, fontWeight: FontWeight.bold),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
            Align(
              alignment: Alignment.center,
              child: Padding(
                padding: const EdgeInsets.only(top: 20, right: 0),
                child: Text(
                  'Forgot Password ?',
                  style: TextStyle(color: Colors.grey),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
class UserData {
  String customerid;
  String profileid;
  String branch;
  String bookername;
  String emailid;
  String mobileno;
  int cutofftime;
  String ppnames;
  String paymenttype;
  String usertype;
  int ptopCutoffTime;
  String designation;
  String designationid;

  UserData({
    this.customerid,
    this.profileid,
    this.branch,
    this.bookername,
    this.emailid,
    this.mobileno,
    this.cutofftime,
    this.ppnames,
    this.paymenttype,
    this.usertype,
    this.ptopCutoffTime,
    this.designation,
    this.designationid,
  });

  factory UserData.fromJson(Map<String, dynamic> json) => UserData(
    customerid: json["customerid"],
    profileid: json["profileid"],
    branch: json["branch"],
    bookername: json["bookername"],
    emailid: json["emailid"],
    mobileno: json["mobileno"],
    cutofftime: json["cutofftime"],
    ppnames: json["ppnames"],
    paymenttype: json["paymenttype"],
    usertype: json["usertype"],
    ptopCutoffTime: json["ptopCutoffTime"],
    designation: json["designation"],
    designationid: json["designationid"],
  );
}

这是我的Flutter代码,是我的新手。

错误消息-

  

[ERROR:flutter / lib / ui / ui_dart_state.cc(148)]未处理的异常:   NoSuchMethodError:方法'[]'在null上调用。电子/颤振   (18386):接收方:空E / flutter(18386):尝试调用:    E / flutter(18386):#0 Object.noSuchMethod   (dart:core-patch / object_patch.dart:50:5)E / flutter(18386):#1
  新的UserData.fromJson   (包装:/Models/UserData.dart:33:21)

4 个答案:

答案 0 :(得分:0)

似乎您在致电UserData.fromJson(Map<String, dynamic> json)时发送了null。致电json != null

之前检查是否UserData.fromJson

答案 1 :(得分:0)

我看到您的代码的方式

 @override
 void initState() {
SystemChrome.setEnabledSystemUIOverlays([]);
userData = UserData(); //What cause the error. 
super.initState();
 }

为什么?因为您没有从服务器获取到UserData类后就将其放入值。如果身份验证有效,请尝试从服务器收集数据。与UserData.fromJson(json.decode(response.body));

此处不是使用Dio,而是使用http,但请尝试通过您之前的代码将其转换为Dio。

     Future<UserData> getUserData() async{

  final SharedPreferences prefs = await SharedPreferences.getInstance();
  String email = prefs.getString('Email');
 String session = prefs.getString('session');

  var map = new Map<String, String>();
  map["email"] = email;
  map["sesscode"] = session;

   var response = await http.post(new API().userdata, body: map);
    var convertDataToJson = json.decode(response.body);
  UserData usdata = UserData .fromJson(convertDataToJson); //THis solve your error

  return usdata ;
  }

答案 2 :(得分:0)

如果您使用的是Google API,则不应限制API密钥。那是我的错编码愉快

答案 3 :(得分:0)

如果您使用的是未初始化的类变量,则会发生此错误。 在使用天气之前,请检查您是否已初始化所有变量。