NoSuchMethodError: Class 'Result' 没有实例 getter 'length'

时间:2021-02-01 21:01:50

标签: flutter dart

有人可以解释一下有什么问题吗?以及如何修复它。

“Result”类没有实例获取器“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',
              ),
            ),
          ),
        ),
      ),
    );
  }
}

2 个答案:

答案 0 :(得分:0)

如果您的 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([...]),
  ),
);

答案 1 :(得分:0)

有时这个错误是由于打字错误引起的
如果你想像下面那样调用 int foo ,你会得到这个错误:

$ int foo;
$ foooooo=1;

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

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