dart flutter NoSuchMethodError:类'String'没有示例getter 'logo'

68bkxrlz  于 2023-10-13  发布在  Flutter
关注(0)|答案(3)|浏览(115)

我是新的Flutter,我有一个问题,我的Flutter代码的问题是
NoSuchMethodError:类'String'没有示例getter 'logo' Receiver:“{id:2,网络:MTN,折扣:2、logo: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,
                        ),
                      ],
                    ),
                  ],
                ),
              );
            },
          );
        }
      }),
);
8fq7wneg

8fq7wneg1#

您收到的错误意味着snapshot.data[1]是一个字符串,而不是您期望包含徽标的对象。

n6lpvg4x

n6lpvg4x2#

看起来像是你试图访问一个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]);
    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。
更好的处理方法是将jsonMap到自定义类。

class Provider {
  Provider({
    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 Provider.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 Provider(
      id: id,
      network: network,
      discount: discount,
      logo: logo,
    );
  }
}

您的列表视图将如下所示:

ListView.builder(
  itemCount: snapshot.data.length,
  itemBuilder: (BuildContext context, int index) {
    // Decoding the string to Map
    final Map<String, dynamic> decodedData = jsonDecode(snapshot.data[index]);
    
    // Mapping the Map to Provider object
    final itemData = Provider.fromJson(decodedData);
    
    return ListTile(
      title: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          SizedBox(
            width: 20,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              Text(
                itemData.logo, // Accessing logo from Provider object
                style: const TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: 20,
                  color: Colors.blue,
                ),
              ),
              Icon(
                Icons.more_horiz,
                color: Colors.blue,
              ),
            ],
          ),
        ],
      ),
    );
  },
);
rekjcdws

rekjcdws3#

正如您的错误消息中所提到的,snapshot.data返回一个String对象

"{id:2,network:MTN,折扣:2、logo:mtncard.png}"

在开头和结尾处加上引号。
字符串没有您试图访问的徽标字段。相反,您需要:
首先,使用 jsonDecode 解析String,将其转换为JSON对象

Import 'dart:convert'; 
  
final jsonObj = jsonDecode(snapshot.data());

现在你有两个选择:从jsonObj直接访问logo

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);
      }
}
  • 附加说明:* 将上面的代码粘贴到.dart文件中,命名为merchant.dart(或sth)。为了易于扩展,我建议将merchant.dart文件存储在模型文件夹中,位于lib文件夹lib>model>merchant.dart

最后,将JSON对象Map到Merchant类中,创建Merchant的示例

final Merchant merchant = Merchant.fromJson(jsonObj);
  • 您需要导入merchant.dart文件才能访问Merchant类和fromJson方法。*

现在您可以安全地访问徽标字段

final String logo = merchant.logo;

希望能帮上忙!

相关问题