You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter登录报错:type 'int' is not a subtype of type 'String' 求助

登录报错:type 'int' is not a subtype of type 'String'

我多次尝试登录,但终端始终报错“type 'int' is not a subtype of type 'String'”,该问题已困扰我3天,尝试多种方法仍无法解决,特此求助。

相关代码文件

user_model.dart

class UserModel {
  int id, nik;
  String password, token;

  UserModel(
      {required this.id,
      required this.nik,
      required this.password,
      required this.token});

  factory UserModel.fromJson(Map<String, dynamic> json) {
    return UserModel(
        id: int.parse(json['id']),
        nik: int.parse(json['nik']),
        password: json['password'],
        token: json['token']);
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'nik': nik,
      'password': password,
      'token': token,
    };
  }
}

auth_service.dart

import 'dart:convert';
import 'package:techsolution/model/user_model.dart';
import 'package:http/http.dart' as http;

class AuthService {
  Uri url = Uri.parse('http://192.168.1.28:8000/api/login');

  Future<UserModel> login({
    int nik = 0,
    String password = '',
  }) async {
    var headers = {'Content-Type': 'application/json'};
    var body = jsonEncode({
      'nik': nik,
      'password': password,
    });

    var response = await http.post(
      url,
      headers: headers,
      body: body,
    );

    if (response.statusCode == 200) {
      var data = jsonDecode(response.body)['data'];
      UserModel user = UserModel.fromJson(data['user']);
      user.token = data['token'];

      return user;
    } else {
      if (response.statusCode == 422) {
        throw Exception('Required Data');
      }
      throw Exception('Data is Wrong');
    }
  }
}

auth_provider.dart

import 'package:flutter/material.dart';
import 'package:techsolution/model/user_model.dart';
import 'package:techsolution/service/auth_service.dart';

class AuthProvider with ChangeNotifier {
  late UserModel _user;

  UserModel get user => _user;
  set user(UserModel user) {
    _user = user;
    notifyListeners();
  }

  Future<bool> login({
    int nik = 0, 
    String password = '',
  }) async {
    try {
      UserModel user = await AuthService().login(nik: nik, password: password);
      _user = user;
      return true;
    } catch (e) {
      print(e);
      return false;
    }
  }
}

login.dart(视图部分)

AuthProvider authProvider = Provider.of<AuthProvider>(context);
handleLogin() async {
  if (await authProvider.login(
      nik: int.parse(nikController.text),
      password: passwordController.text)) {
    await Future.delayed(const Duration(seconds: 1));
    if (context.mounted) return;
    Navigator.pushNamed(context, '/home');
  }
}

问题原因及解决方案

错误根源在UserModel.fromJson方法里:后端返回的id和nik本身就是整数类型,但你调用了int.parse()方法——这个方法要求传入字符串类型,把整数直接传进去就触发了类型不匹配错误。

修改user_model.dart里的fromJson工厂方法,去掉多余的int.parse(),直接强转类型即可:

factory UserModel.fromJson(Map<String, dynamic> json) {
  return UserModel(
      id: json['id'] as int,
      nik: json['nik'] as int,
      password: json['password'],
      token: json['token']);
}

如果后端返回的id/nik有可能是字符串格式的数字(比如"123"),可以加个判断兼容两种情况:

factory UserModel.fromJson(Map<String, dynamic> json) {
  return UserModel(
      id: json['id'] is String ? int.parse(json['id']) : json['id'] as int,
      nik: json['nik'] is String ? int.parse(json['nik']) : json['nik'] as int,
      password: json['password'],
      token: json['token']);
}

内容的提问来源于stack exchange,提问作者Asadin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 07:32:04