【问题标题】:Hello, I'm trying to figure out how factory constructor working in dart你好,我想弄清楚工厂构造函数是如何在飞镖中工作的
【发布时间】:2021-02-16 17:03:28
【问题描述】:

我从 flutter.dev 获取了代码,它使用工厂从互联网上获取数据。

import 'dart:convert';

Future<Album> fetchAlbum() async {
  final response = await http.get('https://jsonplaceholder.typicode.com/albums/1');

  if (response.statusCode == 200) {
    // If the server did return a 200 OK response,
    // then parse the JSON.
    return Album.fromJson(jsonDecode(response.body));
  } else {
    // If the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load album');
  }
}

class Album {
  final int userId;
  final int id;
  final String title;

  Album({this.userId, this.id, this.title});

  factory Album.fromJson(Map<String, dynamic> json) {
    return Album(
      userId: json['userId'],
      id: json['id'],
      title: json['title'],
    );
  }
}

我曾尝试在我的代码中重复它,但它不起作用。我很困惑为什么它不起作用,因为我做的和例子一样。

Future<Album> fetchAlbum() {

  Map<String, dynamic> map = {
    "photo": "another data",
    "id": "dsiid1dsaq",
  };

  return Album.fromJson(map);
}

class Album {

  String photo;
  String id;

  Album({this.photo, this.id});

  factory Album.fromJson(Map<String, dynamic> json) {
    return Album(
      photo: json['photo'],
      id: json['id'],
    )`
  }
}

它告诉我:“无法从函数 'fetchAlbum' 返回类型为 'Album' 的值,因为它的返回类型为 'Future'。”

【问题讨论】:

    标签: json flutter dart factory


    【解决方案1】:

    希望对你有帮助。

    Future<Album> fetchAlbum() async {
    
      Map<String, dynamic> map = {
        "photo": "another data",
        "id": "dsiid1dsaq",
      };
    
      return Album.fromJson(map);
    }
    

    或者像这样

    Album fetchAlbum() {
    
      Map<String, dynamic> map = {
        "photo": "another data",
        "id": "dsiid1dsaq",
      };
    
      return Album.fromJson(map);
    }
    

    【讨论】:

      【解决方案2】:

      问题不在于factory 构造函数本身。问题是您将函数fetchAlbum 声明为Future&lt;Album&gt; 类型,而实际上它只返回一个同步Album...

      Flutter 文档中的示例返回类型为Future&lt;T&gt;,因为它在处理网络请求时使用了asyncawait 关键字,因此它返回Future

      变化:

      Album fetchAlbum() {
      
        Map<String, dynamic> map = {
          "photo": "another data",
          "id": "dsiid1dsaq",
        };
      
        return Album.fromJson(map);
      }
      

      【讨论】:

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