'Resut' 类型的值不能从函数 'fetchPromotions' 返回,因为它的返回类型为 Future<List<Promotions>>

时间:2021-02-01 18:34:27

标签: flutter dart

我正在从 API 获取一些数据,该 API 返回一个 Json 数组,promotions_model.dart 执行所有解析,但出现此错误。

错误-- 无法从函数“fetchPromotions”返回“Result”类型的值,因为它的返回类型为“Future”。

有人可以告诉我我在这里做错了什么。谢谢

**promotions_model.dart**
import 'dart:convert';

Result resultFromJson(String str) => Result.fromJson(json.decode(str));

String resultToJson(Result data) => json.encode(data.toJson());

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())),
      };
}

class Promotions {
  Promotions({
    this.id,
    this.title,
    this.description,
    this.image,
  });

  final String id;
  final String title;
  final String description;
  final String image;

  factory Promotions.fromJson(Map<String, dynamic> json) => Promotions(
        id: json["id"],
        title: json["title"],
        description: json["description"],
        image: json["image"],
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "title": title,
        "description": description,
        "image": image,
      };
}


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

const key = {
  'APP-X-RESTAPI-KEY': "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
};

const API = 'http://111.111.11.1/project';

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

  if (response.statusCode == 200) {
    return resultFromJson(response.body); // This line is causing the error
  } else {
    print(response.statusCode);
  }
}

2 个答案:

答案 0 :(得分:0)

return resultFromJson(response.body);

这一行返回一个 Result,而不是一个 List<Promotion>

答案 1 :(得分:0)

错误说得很清楚。它需要 Result 作为返回类型。 你可以这样,

Result fetchPromotions() async {
  final response = await http.get(API + '/promotion/all', headers: key);
  Result result = null;
  if (response.statusCode == 200) {
    result = resultFromJson(response.body); // This line is causing the error
  } else {
    print(response.statusCode);
  }
  return result;
}

希望你有想法。