Flutter中无法修复'String'不是'bool'子类型错误求助
问题
我想根据传入OtherProfile类的connectionStatus布尔参数,条件渲染按钮上的文本。直接使用true或false常量时代码能正常运行,但使用该变量就会触发'String'不是'bool'子类型的错误。
相关代码
OtherProfile 组件代码
import 'package:flutter/material.dart'; class OtherProfile extends StatelessWidget { final bool connectionStatus; //Connected, request pending etc const OtherProfile( {super.key, required this.connectionStatus, }); @override Widget build(BuildContext context) { return Container( decoration: const BoxDecoration( color: Color(0xFFFFF0E6) ), child: Center( child: Column( children: [ // 顶部留白 const SizedBox( height: 90.0, ), // 内容间距 const SizedBox( height: 24.0, ), // 主按钮区域 Row( mainAxisAlignment: MainAxisAlignment.center, children: [ SizedBox( width: 152, height: 31, child: ElevatedButton( style: ButtonStyle( backgroundColor: MaterialStateProperty.all<Color>(Colors.black), ), onPressed: () {}, // ------------ 问题所在 --------------- child: connectionStatus ? const Text("CONNECTED") : const Text("CONNECT"), ), ), ], ), ], ), ), ); } }
跳转至该页面的 ListTile onTap 代码
onTap: () async { // 跳转到用户主页 // print(users.users); String receiverId = users.users[index]["name"]; print(receiverId); String receiverUserName = users.users[index]["username"]; String receiverFullName = users.users[index]["name"]; String receiverProfileImg = users.users[index]["profile_image"]; bool receiverConnectionStatus = false; int receiverNConnections = 45; Navigator.push( context, MaterialPageRoute(builder: (context) => OtherProfile( userName: receiverUserName, fullName: receiverFullName, profileImage: receiverProfileImg, connectionStatus: receiverConnectionStatus, nConnections: receiverNConnections) ) ); },
解决方案
1. 转换数据源字段类型
你贴出的onTap代码里手动赋值了布尔值,但实际业务场景中你大概率是直接从users.users[index]读取connectionStatus字段,而该字段的实际类型是字符串(比如"true"或"false"),而非布尔值,这就导致参数类型不匹配触发错误。
解决方法是将字符串转换为布尔值:
// 假设数据源中connectionStatus是字符串类型 bool receiverConnectionStatus = users.users[index]["connectionStatus"] == "true";
2. 校验构造函数参数一致性
确认OtherProfile构造函数中connectionStatus的类型确实是bool,没有误写为String。同时检查调用构造函数时的参数名称是否拼写正确,避免因参数名错误传入了其他字符串类型参数。
3. 添加断言提前排查问题
可以在OtherProfile的构造函数中添加断言,开发阶段快速定位参数类型问题:
const OtherProfile({ super.key, required this.connectionStatus, }) : assert(connectionStatus is bool, "connectionStatus 必须是布尔类型");
内容的提问来源于stack exchange,提问作者Soccerball123
相关产品推荐
相关产品推荐

