string - 如何解决flutter错误String不是int类型的子类型
问题描述
我正在尝试学习颤振来开发移动应用程序。通过 github,我下载了登录系统的示例项目。这里是;
https://github.com/vemarav/auth_flow
在这个示例中,我使用我的 api 更改了 api 和端点,并且我得到了这个响应;
{status: 1, message: User login successfully, data: {user_id: 3, name: user_name, email_id: user@email.com, password: *****, image: http://image.url, address: New York, office_address: Charleston & Huff, Mountain View, CA 94043, USA, live_lat: 41.2695887, live_long: -73.0302559, role: 2, status: 1, approval_status: 1, created_at: 1545317082, mobile: 0905375933055, referral_code: CKM676, user_referral_code: , gender: 1, city: new york, country: usa, updated_at: 1545317082, device_type: device_type, device_id: device_id, device_token: device_token, latitude: 37.4207325, longitude: -122.08313869999999, i_card: http://image.url, country_code: , mobile_no: , bank_name: , account_no: , ifsc_code: , account_holder_name: }}
但在 auth_utils.dart 页面响应后,我已将其修改为我的要求。进行此更改后,它看起来像这样。
var user = response['user'];
prefs.setInt(userIdKey, user['user_id']);
prefs.setString(nameKey, user['name']);
在这些更改之后,我收到此错误;
Unhandled Exception: type 'String' is not a subtype of type 'int'.
也许这很容易,但我是颤振/飞镖的新手,对我来说有点复杂。
我试图将响应转换为 int (也许是 string ),但之后我得到了这个错误;
The method 'setInt' was called on null
感谢您的回复
- - - - - - - -编辑 - - - - - - - -
我检查了两个 api 的响应,我的响应与 github 中的源代码之间存在差异。github 响应上的代码是int,我的响应是string。这就是为什么我尝试用它来解析它;
prefs.setInt(userIdKey, int.parse(user['user_id']));
在这些代码之后,我得到了这些错误
Unhandled Exception: NoSuchMethodError: The method 'setInt' was called on null.
Receiver: null
Tried calling: setInt("user_id", 3)
但它不是空的
现在我已经测试了prefs.setString(nameKy, user['name'])
,这给出了同样的错误。但它也不是空的。
解决方案
您必须setInt
在调用此方法之前输入 null in , handle 。
试试看
prefs.setInt('userIdKey', user['user_id'] != null ? user['user_id'] : 0);
或者
prefs.setInt('userIdKey', user['user_id'] ?? 0);
推荐阅读
- java - Keycloak: Send AdminEvent from custom Endpoint (SPI)
- selenium - xcodebuild 以代码“65”和信号“null”退出
- go - 如何在 terraform 提供程序中获取资源名称
- javascript - 如何处理 NestJS 中的 TypeORM 错误?
- kotlin - 如何避免 kotlin Exposed 上的 N+1 查询问题。(当通过 DAO 的 Reference.id.value 字段获取值时)
- firebase - 使用像 Socket.io 这样的 Firebase?
- python - from_tensor_slices 返回一个空对象
- java - 无法连接到远程 apache ignite 节点
- ruby-on-rails - 由于 ArgumentError,ruby net-scp 文件夹复制递归失败:未知指令:“0664 13508
- python - 使用测试事件运行 aws lambda 上传文件(python)