我是 flutter 新手,我的 flutter 代码有问题 问题是
NoSuchMethodError:类“String”没有实例 getter 'logo' 接收器:“{id:2,网络:MTN,折扣:2,徽标:mtncard.png}”
我的代码是
Future<List<dynamic>> LoadData() async {
final name = await Hive.box<dynamic>('my_db');
final result = name.values.toList();
print(result);
//print result is gotten perfectly from hive box
return name.values.toList();
}
SizedBox(
height: 500,
child: FutureBuilder<List<dynamic>>(
future: LoadData(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.data == null) {
return const Center(
child: Text('loading'),
);
} else {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
SizedBox(
width: 20,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text(
snapshot.data[1].logo.toString(),
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20,
color: Colors.blue,
),
),
Icon(
Icons.more_horiz,
color: Colors.blue,
),
],
),
],
),
);
},
);
}
}),
);
您收到的错误意味着
snapshot.data[1]
是一个字符串,而不是您期望包含徽标的对象。
您似乎正在尝试访问 String 对象上的属性徽标。
您尝试访问的字符串是
"{id: 2, network: MTN, discount: 2, logo: mtncard.png}"
,它似乎是 Map 对象的字符串表示形式。在尝试访问 Map 对象的属性之前,将此字符串解析为 Map 对象。您的列表视图应反映以下内容:
import 'dart:convert';
ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
final itemData = jsonDecode(snapshot.data[index].replaceAll(RegExp(r'(\w+):'), '"$1":'));
return ListTile(
title: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
SizedBox(
width: 20,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text(
itemData['logo'].toString(),
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20,
color: Colors.blue,
),
),
Icon(
Icons.more_horiz,
color: Colors.blue,
),
],
),
],
),
);
},
);
在上面,我们将字符串解码为 Map,并使用正则表达式来确保映射中的键被正确引用,这就像 JSON 的要求。
如错误消息中所述,snapshot.data 返回一个 String 对象
“{id:2,网络:MTN,折扣:2,徽标:mtncard.png}”
开头和结尾都加引号。
字符串没有您尝试访问的徽标字段。相反,您需要:
首先,使用 jsonDecode
解析字符串,将其转换为 JSON 对象Import 'dart:convert';
final jsonObj = jsonDecode(snapshot.data());
现在你有两个选择: 直接从jsonObj访问徽标
final logo = jsonObj['logo']
或者,更长但类型安全的方式,通过创建一个类,例如命名为 Merchant,指定字段名称和 fromJson 工厂方法
class Merchant {
Merchant({required this.id, required this.network, required this.discount, required this.logo});
final String id;
final String network;
final int discount;
final String logo;
factory Merchant.fromJson(Map<String, dynamic> data) {
final id = data['id'] as String;
final network = data['network'] as String;
final discount = int.parse(data['discount'])
final logo = data['logo'] as String;
return Merchant(id: id, network: network, discount: discount, logo: logo);
}
}
将 JSON 对象映射到 Merchant 类中以创建 Merchant 的实例
final Merchant merchant = Merchant.fromJson(jsonObj);
现在您可以安全地访问徽标字段了
final String logo = merchant.logo;
希望有帮助!