NoSuchMethodError:在null上调用getter'firstName',接收方:null

时间:2020-07-02 14:57:50

标签: json flutter dart flutter-layout flutter-dependencies

您好,我正在尝试使用条形码扫描仪扫描个人的记录。条形码带来的结果就是该个人的ID。因此,我将ID附加到一个链接,该链接会将我带到该人员的详细信息页面,我可以在其中查看详细信息,但是在扫描后立即出现此错误。

NoSuchMethodError: the getter 'firstName' was called on null. Receiver: null. 

这是我第一个关于扑动的项目,我需要帮助。

这是我的条形码扫描屏幕:

import 'dart:async';
import 'package:erg_app/ProfilePage.dart';
import 'package:erg_app/Anchors.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:barcode_scan/barcode_scan.dart';
import 'package:erg_app/Animations/FadeAnimation.dart';
import 'package:flutter/services.dart';

void main() {
  runApp(MaterialApp(
    debugShowCheckedModeBanner: false,
    home: StartScanPage(),
  ));
}

class StartScanPage extends StatefulWidget {
  @override
  StartScanPageState createState() {
    return new StartScanPageState();
  }
}

class StartScanPageState extends State<StartScanPage> {
  String result = "Bio Data:";

  Future _scanQR() async {
    try {
      String qrResult = await BarcodeScanner.scan();
      print(qrResult);
      
      Navigator.of(context).push(
        MaterialPageRoute(
          builder: (context) => ProfilePage(result: qrResult),
        ),
      );
      // setState(() {
      //   result = qrResult;
      // });
    } on PlatformException catch (ex) {
      if (ex.code == BarcodeScanner.CameraAccessDenied) {
        setState(() {
          result = "Camera permission was denied";
        });
      } else {
        setState(() {
          result = "Unknown Error $ex";
        });
      }
    } on FormatException {
      setState(() {
        result = "You pressed the back button before scanning anything";
      });
    } catch (ex) {
      setState(() {
        result = "Unknown Error $ex";
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Container(
          width: double.infinity,
          height: MediaQuery.of(context).size.height,
          padding: EdgeInsets.symmetric(horizontal: 30, vertical: 50),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Column(
                children: <Widget>[
                  FadeAnimation(
                      1,
                      Text(
                        "Verify Farmer",
                        style: TextStyle(
                            fontWeight: FontWeight.bold, fontSize: 30),
                      )),
                  SizedBox(
                    height: 20,
                  ),
                  FadeAnimation(
                      1.2,
                      Text(
                        "Automatic identity verification which enables you to verify each farmer applicant",
                        textAlign: TextAlign.center,
                        style: TextStyle(color: Colors.grey[700], fontSize: 15),
                      )),
                ],
              ),
              FadeAnimation(
                  1.4,
                  Container(
                    height: MediaQuery.of(context).size.height / 3,
                    decoration: BoxDecoration(
                        image: DecorationImage(
                            image:
                                AssetImage('assets/images/illustration1.png'))),
                  )),
              Column(
                children: <Widget>[
                  FadeAnimation(
                      1.5,
                      MaterialButton(
                        color: Colors.green,
                        minWidth: double.infinity,
                        height: 60,
                        onPressed: _scanQR,
                        shape: RoundedRectangleBorder(
                            side: BorderSide(color: Colors.green),
                            borderRadius: BorderRadius.circular(50)),
                        child: Text(
                          "Start Scan",
                          style: TextStyle(
                              color: Colors.white,
                              fontWeight: FontWeight.w600,
                              fontSize: 18),
                        ),
                      )),
                  SizedBox(
                    height: 20,
                  ),
                  FadeAnimation(
                      1.6,
                      Container(
                        // padding: EdgeInsets.only(top: 3, left: 3),
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(50),
                            border: Border(
                              bottom: BorderSide(color: Colors.green),
                              top: BorderSide(color: Colors.green),
                              left: BorderSide(color: Colors.green),
                              right: BorderSide(color: Colors.green),
                            )),
                        child: MaterialButton(
                          minWidth: double.infinity,
                          height: 60,
                          onPressed: () {
                            Navigator.push(
                                context,
                                MaterialPageRoute(
                                    builder: (context) => AnchorsPage()));
                          },
                          color: Colors.white,
                          elevation: 0,
                          shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(50)),
                          child: Text(
                            "Cancel",
                            style: TextStyle(
                                // color: Colors.white,
                                fontWeight: FontWeight.w600,
                                fontSize: 18),
                          ),
                        ),
                      ))
                ],
              )
            ],
          ),
        ),
      ),
    );
  }
}

这是“用户详细信息”屏幕

import 'package:erg_app/StartScan.dart';
import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';
import 'package:erg_app/models/farmer_model.dart';
import 'package:erg_app/api/farmers_services.dart';



class ProfilePage extends StatefulWidget {
  final String result;
  ProfilePage({this.result});

  @override
  _ProfilePageState createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {

  FarmersService get fromersService => GetIt.I<FarmersService>();

  String errorMessage;
  FarmerClass farmer;

  @override
  void initState() {

    fromersService.getFarmer(widget.result)
      .then((response) {
       
        if (response.error) {
          errorMessage = response.errorMessage ?? 'An error occurred';
        }
        farmer = response.data;
      });
    
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: new Center(
              child: new Text('Farmers Data', textAlign: TextAlign.left)),
          iconTheme: IconThemeData(color: Colors.white),
          backgroundColor: Colors.green,
          leading: new IconButton(
            icon: new Icon(Icons.assignment_ind),
            onPressed: () {},
          ),
        ),
        // backgroundColor: Colors.green[50],
        body: Container(
          child: ListView(
            children: <Widget>[
              Container(
                margin: EdgeInsets.only(top: 20),
              ),
              CircleAvatar(
                radius: 80,
                backgroundColor: Colors.grey,
                // backgroundImage: AssetImage('assets/images/user.png'),
              ),
              Text(
               farmer.firstName ?? 'An error occurred',
                style: TextStyle(
                  fontFamily: 'SourceSansPro',
                  fontSize: 25,
                ),
                textAlign: TextAlign.center,
              ),
              Text(
                'Welcome',
                style: TextStyle(
                  fontSize: 20,
                  fontFamily: 'SourceSansPro',
                  color: Colors.green[400],
                  letterSpacing: 2.5,
                ),
                textAlign: TextAlign.center,
              ),
              Container(
                margin: EdgeInsets.only(top: 20),
              ),
              SizedBox(
                height: 20.0,
                width: 200,
                child: Divider(
                  color: Colors.teal[100],
                ),
              ),
              Text(
                'Farmer Details',
                textAlign: TextAlign.center,
              ),
              Card(
                color: Colors.white,
                margin: EdgeInsets.symmetric(vertical: 10.0, horizontal: 25.0),
                child: ListTile(
                  leading: Text(
                    'BVN:',
                    style: TextStyle(
                      fontSize: 20,
                      fontFamily: 'SourceSansPro',
                      color: Colors.green[700],
                      letterSpacing: 2.5,
                    ),
                  ),
                  title: Text(
                    farmer.bvn ,
                    style: TextStyle(fontFamily: 'BalooBhai', fontSize: 20.0),
                  ),
                ),
              ),
              Card(
                color: Colors.white,
                margin: EdgeInsets.symmetric(vertical: 10.0, horizontal: 25.0),
                child: ListTile(
                  leading: Text(
                    'ID:',
                    style: TextStyle(
                      fontSize: 20,
                      fontFamily: 'SourceSansPro',
                      color: Colors.green[700],
                      letterSpacing: 2.5,
                    ),
                  ),
                  title: Text(
                    farmer.applicationId,
                    style: TextStyle(fontFamily: 'BalooBhai', fontSize: 20.0),
                  ),
                ),
              ),
              Card(
                color: Colors.white,
                margin: EdgeInsets.symmetric(vertical: 10.0, horizontal: 25.0),
                child: ListTile(
                  leading: Text(
                    'Appicant ID:'?? 'An error occurred',
                    style: TextStyle(
                      fontSize: 20,
                      fontFamily: 'SourceSansPro',
                      color: Colors.green[700],
                      letterSpacing: 2.5,
                    ),
                  ),
                  title: Text(
                    "p.appliId",
                    style: TextStyle(fontFamily: 'BalooBhai', fontSize: 20.0),
                  ),
                ),
              ),
              Card(
                color: Colors.white,
                margin: EdgeInsets.symmetric(vertical: 10.0, horizontal: 25.0),
                child: ListTile(
                  leading: Text(
                    'State/LGA:',
                    style: TextStyle(
                      fontSize: 20,
                      fontFamily: 'SourceSansPro',
                      color: Colors.green[700],
                      letterSpacing: 2.5,
                    ),
                  ),
                  title: Text(
                    "p.state",
                    style: TextStyle(fontFamily: 'BalooBhai', fontSize: 20.0),
                  ),
                ),
              ),
              Card(
                color: Colors.white,
                margin: EdgeInsets.symmetric(vertical: 10.0, horizontal: 25.0),
                child: ListTile(
                  leading: Text(
                    'Farm Size:',
                    style: TextStyle(
                      fontSize: 20,
                      fontFamily: 'SourceSansPro',
                      color: Colors.green[700],
                      letterSpacing: 2.5,
                    ),
                  ),
                  title: Text(
                    "p.farmsize",
                    style: TextStyle(fontFamily: 'BalooBhai', fontSize: 20.0),
                  ),
                ),
              ),
              Card(
                color: Colors.white,
                margin: EdgeInsets.symmetric(vertical: 10.0, horizontal: 25.0),
                child: ListTile(
                  leading: Text(
                    'Geo Coord.:',
                    style: TextStyle(
                      fontSize: 20,
                      fontFamily: 'SourceSansPro',
                      color: Colors.green[700],
                      letterSpacing: 2.5,
                    ),
                  ),
                  title: Text(
                    "p.geocord",
                    style: TextStyle(fontFamily: 'BalooBhai', fontSize: 20.0),
                  ),
                ),
              ),
              Divider(),
              
              Divider(),
              Container(
                margin: EdgeInsets.only(top: 20, bottom: 30),
                child: Center(
                  child: RaisedButton(
                    padding: EdgeInsets.fromLTRB(80, 10, 80, 10),
                    color: Colors.green,
                    child: Text(
                      "Complete",
                      style: TextStyle(
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                          fontSize: 14),
                    ),
                    onPressed: () {
                      Navigator.of(context).push(MaterialPageRoute(
                          builder: (context) => StartScanPage()));
                    },
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(50),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}


我的http服务类:

import 'dart:convert';
import 'package:http/http.dart'
    as http; // add the http plugin in pubspec.yaml file.
import 'package:erg_app/models/farmer_model.dart';
import 'package:erg_app/models/api_response.dart';


class FarmersService {
  Future<APIResponse<FarmerClass>> getFarmer(String bvn) {
    final queryParameters = {
      'Bvn': bvn,
    };
    final url = new Uri.http(
        'api.ergagro.com:112', '/CheckDailyStockTakingStatus', queryParameters);

    return http
        .get(url, headers: {'Content-Type': 'application/json'}).then((data) {
      if (data.statusCode == 200) {
        final jsonData = json.decode(data.body);
        print('Data Received');
        return APIResponse<FarmerClass>(data: FarmerClass.fromJson(jsonData));
      }
      return APIResponse<FarmerClass>(
          error: true, errorMessage: 'An error occured');
    }).catchError((_) => APIResponse<FarmerClass>(
            error: true, errorMessage: 'An error occured'));
  }
}

型号:

// To parse this JSON data, do
//
//     final farmer = farmerFromJson(jsonString);

import 'dart:convert';

Farmer farmerFromJson(String str) => Farmer.fromJson(json.decode(str));

String farmerToJson(Farmer data) => json.encode(data.toJson());

class Farmer {
  Farmer({
    this.statusCode,
    this.message,
    this.success,
    this.farmer,
  });

  int statusCode;
  String message;
  bool success;
  FarmerClass farmer;

  factory Farmer.fromJson(Map<String, dynamic> json) => Farmer(
        statusCode: json["StatusCode"],
        message: json["Message"],
        success: json["Success"],
        farmer: FarmerClass.fromJson(json["Farmer"]),
      );

  Map<String, dynamic> toJson() => {
        "StatusCode": statusCode,
        "Message": message,
        "Success": success,
        "Farmer": farmer.toJson(),
      };
}

class FarmerClass {
  FarmerClass({
    this.oid,
    this.applicationId,
    this.bvn,
    this.firstName,
    this.middleName,
    this.lastName,
    this.fullName,
    this.gender,
    this.dateOfBirth,
    this.phoneNo,
    this.lga,
    this.state,
    this.provider,
    this.anchor,
    this.polygon,
    this.size,
    this.farmImage,
    this.signature,
    this.landDocument,
    this.maritalStatus,
    this.project,
    this.nokFirstName,
    this.nokSurname,
    this.nokOtherName,
    this.nokPhone,
    this.nokBvn,
    this.address,
    this.spouseName,
    this.spouseBvn,
    this.relationship,
    this.season,
    this.propertySize,
    this.propertyOwner,
    this.photoPath,
    this.anchorAcronym,
    this.logoUrl,
    this.bank,
    this.bankLogoUrl,
    this.photoUrl,
  });

  int oid;
  String applicationId;
  String bvn;
  String firstName;
  String middleName;
  String lastName;
  String fullName;
  String gender;
  DateTime dateOfBirth;
  String phoneNo;
  String lga;
  String state;
  String provider;
  String anchor;
  String polygon;
  double size;
  dynamic farmImage;
  dynamic signature;
  dynamic landDocument;
  dynamic maritalStatus;
  String project;
  String nokFirstName;
  String nokSurname;
  String nokOtherName;
  String nokPhone;
  dynamic nokBvn;
  String address;
  String spouseName;
  dynamic spouseBvn;
  String relationship;
  dynamic season;
  dynamic propertySize;
  String propertyOwner;
  String photoPath;
  String anchorAcronym;
  String logoUrl;
  String bank;
  String bankLogoUrl;
  String photoUrl;

  factory FarmerClass.fromJson(Map<String, dynamic> json) => FarmerClass(
        oid: json["Oid"],
        applicationId: json["ApplicationId"],
        bvn: json["Bvn"],
        firstName: json["FirstName"],
        middleName: json["MiddleName"],
        lastName: json["LastName"],
        fullName: json["FullName"],
        gender: json["Gender"],
        dateOfBirth: DateTime.parse(json["DateOfBirth"]),
        phoneNo: json["PhoneNo"],
        lga: json["Lga"],
        state: json["State"],
        provider: json["Provider"],
        anchor: json["Anchor"],
        polygon: json["Polygon"],
        size: json["Size"].toDouble(),
        farmImage: json["FarmImage"],
        signature: json["Signature"],
        landDocument: json["LandDocument"],
        maritalStatus: json["MaritalStatus"],
        project: json["Project"],
        nokFirstName: json["NokFirstName"],
        nokSurname: json["NokSurname"],
        nokOtherName: json["NokOtherName"],
        nokPhone: json["NokPhone"],
        nokBvn: json["NokBvn"],
        address: json["Address"],
        spouseName: json["SpouseName"],
        spouseBvn: json["SpouseBvn"],
        relationship: json["Relationship"],
        season: json["Season"],
        propertySize: json["PropertySize"],
        propertyOwner: json["PropertyOwner"],
        photoPath: json["PhotoPath"],
        anchorAcronym: json["AnchorAcronym"],
        logoUrl: json["LogoUrl"],
        bank: json["Bank"],
        bankLogoUrl: json["BankLogoUrl"],
        photoUrl: json["PhotoUrl"],
      );

  Map<String, dynamic> toJson() => {
        "Oid": oid,
        "ApplicationId": applicationId,
        "Bvn": bvn,
        "FirstName": firstName,
        "MiddleName": middleName,
        "LastName": lastName,
        "FullName": fullName,
        "Gender": gender,
        "DateOfBirth": dateOfBirth.toIso8601String(),
        "PhoneNo": phoneNo,
        "Lga": lga,
        "State": state,
        "Provider": provider,
        "Anchor": anchor,
        "Polygon": polygon,
        "Size": size,
        "FarmImage": farmImage,
        "Signature": signature,
        "LandDocument": landDocument,
        "MaritalStatus": maritalStatus,
        "Project": project,
        "NokFirstName": nokFirstName,
        "NokSurname": nokSurname,
        "NokOtherName": nokOtherName,
        "NokPhone": nokPhone,
        "NokBvn": nokBvn,
        "Address": address,
        "SpouseName": spouseName,
        "SpouseBvn": spouseBvn,
        "Relationship": relationship,
        "Season": season,
        "PropertySize": propertySize,
        "PropertyOwner": propertyOwner,
        "PhotoPath": photoPath,
        "AnchorAcronym": anchorAcronym,
        "LogoUrl": logoUrl,
        "Bank": bank,
        "BankLogoUrl": bankLogoUrl,
        "PhotoUrl": photoUrl,
      };
}

我的get_it类

class APIResponse<T> {
  T data;
  bool error;
  String errorMessage;

  APIResponse({this.data, this.errorMessage, this.error = false});
}

请有人帮我吗?

0 个答案:

没有答案