Home > Software design >  Flutter type 'String' is not a subtype of type 'int?'
Flutter type 'String' is not a subtype of type 'int?'

Time:09-22

After successfully register user go to the OTP screen where I enter my OTP but after clicking on button I get this:

type 'String' is not a subtype of type 'int?'

Here is the full message

[log] type 'String' is not a subtype of type 'int?'
[log] #0      new User.fromJson (package:marketingo/model/register_response.dart:117:31)
#1      new Data.fromJson (package:marketingo/model/register_response.dart:47:50)
#2      new RegisterResponse.fromJson (package:marketingo/model/register_response.dart:26:50)
#3      _PinCodeState._confirmAccount.<anonymous closure> (package:marketingo/pages/otp/otp.dart:43:70)
<asynchronous suspension>

When I click on new Data.fromJson (package:marketingo/model/register_response.dart:47:50) it takes me to my model on line verificationCode: json["verification_code"], as it is of type int.

Here is my Model

RegisterResponse registerResponseFromJson(String str) => RegisterResponse.fromJson(json.decode(str));

String registerResponseToJson(RegisterResponse data) => json.encode(data.toJson());

class RegisterResponse {
  RegisterResponse({
    this.success,
    this.enMessage,
    this.arMessage,
    this.data,
    this.status,
  });

  bool? success;
  String? enMessage;
  String? arMessage;
  Data? data;
  int? status;

  factory RegisterResponse.fromJson(Map<String, dynamic> json) => RegisterResponse(
        success: json["success"],
        enMessage: json["en_message"],
        arMessage: json["ar_message"],
        data: json["data"] == null ? null : Data.fromJson(json["data"]),
        status: json["status"],
      );

  Map<String, dynamic> toJson() => {
        "success": success,
        "en_message": enMessage,
        "ar_message": arMessage,
        "data": data == null ? null : data!.toJson(),
        "status": status,
      };
}

class Data {
  Data({
    this.user,
  });

  User? user;

  factory Data.fromJson(Map<String, dynamic> json) => Data(
        user: json["user"] == null ? null : User.fromJson(json["user"]),
      );

  Map<String, dynamic> toJson() => {
        "user": user == null ? null : user!.toJson(),
      };
}

class User {
  User({
    this.firstName,
    this.username,
    this.email,
    this.type,
    this.address,
    this.roleId,
    this.verificationCode,
    this.verified,
    this.phone,
    this.mobile,
    this.lat,
    this.lon,
    this.categoryId,
    this.companyName,
    this.tradeLicense,
    this.field,
    this.workTime,
    this.facebook,
    this.linkedIn,
    this.instagram,
    this.whatsApp,
    this.updatedAt,
    this.createdAt,
    this.id,
    this.balance,
  });

  String? firstName;
  String? username;
  String? email;
  int? type;
  String? address;
  int? roleId;
  int? verificationCode;
  int? verified;
  String? phone;
  String? mobile;
  String? lat;
  String? lon;
  String? categoryId;
  String? companyName;
  String? tradeLicense;
  String? field;
  String? workTime;
  String? facebook;
  String? linkedIn;
  String? instagram;
  String? whatsApp;
  DateTime? updatedAt;
  DateTime? createdAt;
  int? id;
  List<dynamic>? balance;

  factory User.fromJson(Map<String, dynamic> json) => User(
        firstName: json["first_name"],
        username: json["username"],
        email: json["email"],
        type: json["type"],
        address: json["address"],
        roleId: json["role_id"],
        verificationCode: int.parse(json["verification_code"]),
        verified: json["verified"],
        phone: json["phone"],
        mobile: json["mobile"],
        lat: json["lat"],
        lon: json["lon"],
        categoryId: json["category_id"],
        companyName: json["company_name"],
        tradeLicense: json["trade_license"],
        field: json["field"],
        workTime: json["work_time"],
        facebook: json["facebook"],
        linkedIn: json["linkedIn"],
        instagram: json["instagram"],
        whatsApp: json["whatsApp"],
        updatedAt: json["updated_at"] == null ? null : DateTime.parse(json["updated_at"]),
        createdAt: json["created_at"] == null ? null : DateTime.parse(json["created_at"]),
        id: json["id"],
        balance: json["balance"] == null ? null : List<dynamic>.from(json["balance"].map((x) => x)),
      );

  Map<String, dynamic> toJson() => {
        "first_name": firstName,
        "username": username,
        "email": email,
        "type": type,
        "address": address,
        "role_id": roleId,
        "verification_code": verificationCode,
        "verified": verified,
        "phone": phone,
        "mobile": mobile,
        "lat": lat,
        "lon": lon,
        "category_id": categoryId,
        "company_name": companyName,
        "trade_license": tradeLicense,
        "field": field,
        "work_time": workTime,
        "facebook": facebook,
        "linkedIn": linkedIn,
        "instagram": instagram,
        "whatsApp": whatsApp,
        "updated_at": updatedAt == null ? null : updatedAt!.toIso8601String(),
        "created_at": createdAt == null ? null : createdAt!.toIso8601String(),
        "id": id,
        "balance": balance == null ? null : List<dynamic>.from(balance!.map((x) => x)),
      };
}

Updated

When I tried @Ivo answer int.parse(json["verification_code"]) then it given me this type 'int' is not a subtype of type 'String?'

Even I try to enter wrong OTP still I'm getting this.

Here is my code

My api for confirm Account

   static Future<http.Response> confirmAccount(String userName, String verificationCode) async {
    var url = Uri.parse('${baseUrl}confirmAccount');
    var response = await http.post(url, body: {
      "username": userName,
      "verification_code": verificationCode,
    });
    return response;
  }

Here is I'm calling my api

class PinCode extends StatefulWidget {
  final String userName;

  const PinCode(this.userName, {Key? key}) : super(key: key);

  @override
  State<PinCode> createState() => _PinCodeState();
}

class _PinCodeState extends State<PinCode> {
  TextEditingController otpController = TextEditingController();

  void _confirmAccount() async {
    var connectivityResult = await (Connectivity().checkConnectivity());
    if (connectivityResult == ConnectivityResult.wifi || connectivityResult == ConnectivityResult.mobile) {
      Utils.showLoader(context);
      ApiCall.confirmAccount(widget.userName, otpController.text).then((value) async {
        if (value.statusCode == 200) {
          if (json.decode(value.body)['success'] != null) {
            if (json.decode(value.body)['success']) {
              try {
                RegisterResponse registerResponse = RegisterResponse.fromJson(json.decode(value.body));
              } catch (error, stackTrace) {
                log(error.toString());
                log(stackTrace.toString());
              }
              Get.offAll(() => const BottomNav());
            } else {
              Utils.hideLoader(context);
              if (Get.put(AppController()).isEnglish()) {
                Utils.flushBarErrorMessage(jsonDecode(value.body)["en_message"], context);
              } else {
                Utils.flushBarErrorMessage(jsonDecode(value.body)["ar_message"], context);
              }
            }
          } else {
            Utils.flushBarErrorMessage(jsonDecode(value.body)["error"], context);
          }
        } else {
          Utils.hideLoader(context);
          Utils.flushBarErrorMessage(LanguageStringKeys.instance.invalidData.tr, context);
        }
        Utils.hideLoader(context);
      }).catchError((onError) {
        Utils.hideLoader(context);
        debugPrint(onError.toString());
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return BackgroundImage(
      image: const AssetImage('assets/images/mainBg.png'),
      child: Scaffold(
        backgroundColor: Colors.transparent,
        appBar: PreferredSize(preferredSize: Size.fromHeight(Dimensions.height56), child: const AppBarMain()),
        body: Center(
          child: SingleChildScrollView(
            physics: const BouncingScrollPhysics(),
            child: Padding(
              padding: EdgeInsets.symmetric(horizontal: Dimensions.width20),
              child: Column(
                children: [
                  Container(
                    width: Dimensions.width130,
                    height: Dimensions.height130,
                    decoration: const BoxDecoration(color: Colors.white, shape: BoxShape.circle),
                    child: Icon(Icons.lock, size: Dimensions.height80, color: AppColors.fIconsAndTextColor),
                  ),
                  SizedBox(height: Dimensions.height20),
                  SmallText(
                      text: 'Please check your email for a message with your '
                          'code\nyour code is 4 numbers long',
                      size: Dimensions.font18,
                      color: Colors.white),
                  SizedBox(height: Dimensions.height20),
                  PinCodeTextField(
                    appContext: context,
                    keyboardType: TextInputType.number,
                    length: 4,
                    textStyle: const TextStyle(color: Colors.white),
                    animationType: AnimationType.none,
                    controller: otpController,
                    cursorColor: Colors.white,
                    onChanged: (value) {},
                    pinTheme: PinTheme(
                      shape: PinCodeFieldShape.box,
                      selectedColor: Colors.white,
                      borderRadius: BorderRadius.circular(Dimensions.radius10),
                      fieldHeight: Dimensions.height50,
                      fieldWidth: Dimensions.width50,
                      inactiveColor: Colors.white,
                      activeColor: Colors.white,
                    ),
                    onCompleted: (value) {},
                  ),
                  SizedBox(height: Dimensions.height20),
                  ElevatedButton(
                    onPressed: () {
                      _confirmAccount();
                    },
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.white,
                      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(Dimensions.radius10)),
                      minimumSize: Size.fromHeight(Dimensions.height40),
                    ),
                    child: const BigText(text: 'Submit', color: Colors.grey),
                  ),
                  SizedBox(height: Dimensions.height10),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      SmallText(text: LanguageStringKeys.instance.didNotGetCode.tr, size: Dimensions.font18, color: Colors.white),
                      TextButton(
                        onPressed: () {},
                        child: SmallText(text: LanguageStringKeys.instance.resend.tr, color: Colors.white, size: 18),
                      )
                    ],
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}

After press on button app crash

enter image description here

CodePudding user response:

OTP is in String but u are assigning String To int which is not possible you can do this instead

int otp = int.parse('Your OTP here');

Thank you

CodePudding user response:

It's parsing Error, Verification Code is int? datatype & Your OTP is in String. Parse your OTP in int? first & then do the rest of your code

int.parse(your otp);

CodePudding user response:

It looks like the phone response is an int and you are trying to get it by string.

as in your error message, it says your error at 117 lines that's means:

  factory User.fromJson(Map<String, dynamic> json) => User(
        firstName: json["first_name"],
        username: json["username"],
        email: json["email"],
        type: json["type"],
        address: json["address"],
        roleId: json["role_id"],
        verificationCode: int.parse(json["verification_code"]),
        verified: json["verified"],
        phone: json["phone"],  //  <-- here
        mobile: json["mobile"],
        lat: json["lat"],
        lon: json["lon"],
        categoryId: json["category_id"],
        companyName: json["company_name"],
        tradeLicense: json["trade_license"],
        field: json["field"],
        workTime: json["work_time"],
        facebook: json["facebook"],
        linkedIn: json["linkedIn"],
        instagram: json["instagram"],
        whatsApp: json["whatsApp"],
        updatedAt: json["updated_at"] == null ? null : DateTime.parse(json["updated_at"]),
        createdAt: json["created_at"] == null ? null : DateTime.parse(json["created_at"]),
        id: json["id"],
        balance: json["balance"] == null ? null : List<dynamic>.from(json["balance"].map((x) => x)),
      );

and to solve this just convert it to String like:

phone: json["phone"].toString(),
  • Related