【问题标题】:NoSuchMethodError: Class 'Result' has no instance getter 'length'NoSuchMethodError:类“结果”没有实例获取器“长度”
【发布时间】:2021-02-01 21:01:50
【问题描述】:

有人可以解释什么是错的吗?以及如何解决它。

类 'Result' 没有实例 getter 'length'。 接收方:“结果”实例 尝试调用:长度

我已成功从 API 获取一些数据。当我将此数据传递给promotions_page.dart时

我收到此错误,我知道我做错了什么,但我无法弄清楚。 请问我可以帮忙吗?

**promotions_page.dart**

    class _PromotionsPageState extends State<PromotionsPage> {
      Future<Result> _promotionsResultsData;
    
      @override
      void initState() {
        _promotionsResultsData = PromotionApi().fetchPromotions();
    
        super.initState();
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Container(
            margin: EdgeInsets.symmetric(horizontal: 10.0, vertical: 20.0),
            child: ListView(
              physics: PageScrollPhysics(),
              children: [
                Column(
                  children: [
                    Container(
                      child: FutureBuilder(
                        future: _promotionsResultsData,
                        builder: (context, snapshot) {
                          if (snapshot.hasData) {
                            print('we have got something');
                            return GridView.builder(
                              padding: EdgeInsets.zero,
                              gridDelegate:
                                  SliverGridDelegateWithFixedCrossAxisCount(
                                childAspectRatio: (45 / 35),
                                crossAxisCount: 1,
                              ),
                              shrinkWrap: true,
                              physics: ScrollPhysics(),
                              itemCount: snapshot.data.length, // this line was throwing the error TO fix this it has to be
this snapshot.data.result.length
                              itemBuilder: (BuildContext context, int index) =>
                                  PromotionCard(
                                id: snapshot.data[index]['id'],
                                title: snapshot.data[index]['title'],
                                description: snapshot.data[index]['description'],
                                image: snapshot.data[index]['image'],
                              ),
                            );
                          } else {}
                          return Center(
                            child: Text(
                              "Loading ...",
                              style: TextStyle(
                                  fontWeight: FontWeight.w900, fontSize: 30.0),
                            ),
                          );
                        },
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        );
      }
    }

**promotion-api.dart**
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:project_dev_1/models/promotions_model.dart';

class PromotionApi {
  static const key = {
    'APP-X-RESTAPI-KEY': "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  };

  static const API = 'http://111.111.11.1/projectrest';

  Future<Result> fetchPromotions() async {
    final response = await http.get(API + '/promotion/all', headers: key);
    var results;

    if (response.statusCode == 200) {
      var responseData = response.body;
      var jsonMap = json.decode(responseData);

      results = Result.fromJson(jsonMap);
    }
    return results;
  }
}


**w_promotino_card.dart widget**
import 'package:flutter/material.dart';
import 'package:buffet_dev_1/pages/promotion_details.dart';

class PromotionCard extends StatelessWidget {
  final String id;
  final String title;
  final String description;
  final String image;

  PromotionCard({this.id, this.title, this.description, this.image}) {
    print(id + title + image);
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => Navigator.push(
        context,
        MaterialPageRoute(
          builder: (_) => PromotionDetails(
            promotions: null,
          ),
        ),
      ),
      child: Container(
        width: MediaQuery.of(context).size.width,
        height: 200.0,
        margin: EdgeInsets.fromLTRB(0.0, 20.0, 0.0, 10.0),
        padding: EdgeInsets.zero,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: null,
            alignment: Alignment.topCenter,
          ),
          borderRadius: BorderRadius.circular(10.0),
          border: Border.all(
            width: 1.5,
            color: Colors.grey[300],
          ),
        ),
        child: Container(
          width: MediaQuery.of(context).size.width,
          margin: EdgeInsets.zero,
          child: Padding(
            padding: EdgeInsets.fromLTRB(10, 170.0, 10.0, 10.0),
            child: Text(
              title,
              style: TextStyle(
                fontSize: 16.0,
                fontFamily: 'BuffetRegular',
              ),
            ),
          ),
        ),
      ),
    );
  }
}

【问题讨论】:

  • 它准确地告诉你出了什么问题。您正在尝试调用 snapshot.data.length,但 Result 没有 length 属性。
  • 好的,要解决这个问题,请执行此 snapshot.data.result.length ?
  • 不知道 Result 或传入的 JSON 是什么样子,我不能说。
  • 我修好了。但是当我将数据传递给 PromotionCard([...]) 。它没有显示任何内容。但是我打印出 snapshot.data.result[index].image 我可以看到数据调试控制台
  • 我用 Card 小部件替换了整个容器,仍然没有显示数据,但我可以在调试控制台中看到它。我已经更新了我的代码

标签: flutter dart


【解决方案1】:

如果您的Result 仍然与one of your previous questions 相同:

class Result {
  Result({
    this.code,
    this.result,
  });

  final int code;
  final List<Promotions> result;

  factory Result.fromJson(Map<String, dynamic> json) => Result(
        code: json["Code"],
        result: List<Promotions>.from(
            json["Result"].map((x) => Promotions.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "Code": code,
        "Result": List<dynamic>.from(result.map((x) => x.toJson())),
      };
}

那么,是的,Result 类没有实例 getter length

您可能希望从snapshot.data.result 而不是snapshot.data 构建您的网格:

GridView.builder(
  padding: EdgeInsets.zero,
  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
    [...]
    itemCount: snapshot.data.result.length,
    itemBuilder: (BuildContext context, int index) => PromotionCard([...]),
  ),
);

【讨论】:

  • 谢谢蒂埃里,我已经修复了它现在我遇到了与 ui 卡不同的问题。
【解决方案2】:

有时这个错误是由于输入错误导致的
如果你想像下面这样调用int foo,你会得到这个错误:

$ int foo;
$ foooooo=1;

NoSuchMethodError: Class 'Result' has no instance getter 'foooooo'

所以如果你有这个错误,你应该检查 var foooooofoo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-09
    • 1970-01-01
    • 2021-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多