【问题标题】:Flutter GetX displaying data from JSON APIFlutter GetX 显示来自 JSON API 的数据
【发布时间】:2021-10-17 10:03:31
【问题描述】:

错误:需要一个“响应”类型的值,但得到一个“RxList”类型的值

如何将 json 粘贴到现有的 RXList 元素中。 感谢您的帮助。 我认为问题在于响应是 Json 并且我想填写普通文本。 我希望任何人都可以帮助我。

Json 中的 API 响应:

[
  {
    "_id": "60f2f01bf42d421c3514bc58",
    "number": 88595949,
    "manufacturer": "Buderus",
    "cost": 4250,
    "createdAt": "2021-07-17T14:58:35.487Z",
    "updatedAt": "2021-07-17T14:58:35.487Z",
    "__v": 0
  },
  {
    "_id": "60f2f2792be4c91cfc2e36f2",
    "number": 88595949,
    "manufacturer": "Junker",
    "cost": 4250,
    "createdAt": "2021-07-17T15:08:41.741Z",
    "updatedAt": "2021-07-17T15:08:41.741Z",
    "__v": 0
  },
 
]


machine.dart:

```
class Machine {
  final int id;
  final int machineNumber;
  final String manufacturer;
  final int cost;

  Machine(
      {required this.id,
      required this.machineNumber,
      required this.manufacturer,
      required this.cost});
} ```

machine_controller.dart:

import 'package:get/state_manager.dart';
import 'package:myapp/models/machine.dart';

class MachineController extends GetxController {
  var machines = RxList<Machine>();

  @override
  void onInit() {
    super.onInit();
    fetchMachines();
  }

  void fetchMachines() async {
    var serverResponse = [
      Machine(
          id: 1, machineNumber: 7892836, manufacturer: "junker", cost: 1660),
      Machine(
          id: 2, machineNumber: 8358937, manufacturer: "reishauer", cost: 1640),
      Machine(id: 3, machineNumber: 7632575, manufacturer: "grob", cost: 1650),
      Machine(id: 4, machineNumber: 1298188, manufacturer: "anger", cost: 1660)
    ];

    machines.value = serverResponse;
  }
} ```





【问题讨论】:

  • 如果您从 API 获取数据,请参考我的回答 hereherehere 希望对您有所帮助

标签: json flutter dio flutter-getx


【解决方案1】:

对我来说,我通常是这样的。 |

型号

import 'dart:convert';

List<Machine> machineFromJson(String str) => List<Machine>.from(json.decode(str).map((x) => Machine.fromJson(x)));

String machineToJson(List<Machine> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Machine {
    Machine({
        this.id,
        this.number,
        this.manufacturer,
        this.cost,
        this.createdAt,
        this.updatedAt,
        this.v,
    });

    final String id;
    final int number;
    final String manufacturer;
    final int cost;
    final DateTime createdAt;
    final DateTime updatedAt;
    final int v;

    factory Machine.fromJson(Map<String, dynamic> json) => Machine(
        id: json["_id"] == null ? null : json["_id"],
        number: json["number"] == null ? null : json["number"],
        manufacturer: json["manufacturer"] == null ? null : json["manufacturer"],
        cost: json["cost"] == null ? null : json["cost"],
        createdAt: json["createdAt"] == null ? null : DateTime.parse(json["createdAt"]),
        updatedAt: json["updatedAt"] == null ? null : DateTime.parse(json["updatedAt"]),
        v: json["__v"] == null ? null : json["__v"],
    );

    Map<String, dynamic> toJson() => {
        "_id": id == null ? null : id,
        "number": number == null ? null : number,
        "manufacturer": manufacturer == null ? null : manufacturer,
        "cost": cost == null ? null : cost,
        "createdAt": createdAt == null ? null : createdAt.toIso8601String(),
        "updatedAt": updatedAt == null ? null : updatedAt.toIso8601String(),
        "__v": v == null ? null : v,
    };
}

然后对于 api 示例,我使用 dio 从 api 获取数据

    import 'package:dio/dio.dart' as dio;

 class Service {

    static yourService() async{
    
      var response = await dio.get('url');
      if(response.statusCode == 200){
       return Machine.fromJson(response.data);
    }else{
      //do something for error
    }
    
    }
}

控制器的下一个是

  class MachineController extends GetxController {
    
     final listMachine = List<Machine>().obs;
     // if null safety or flutter 2 above is []<Machine>.obs;
        @override
  void onInit() async {
     yourFunctionCall();
    super.onInit();
  }

   void yourFunctionCall() async{
     try{
       var list = await Service.yourService();
       if(list != null){
       // if iterable data use listMachine.addAll(list);
       // or listMachine.assignAll(list);
       //if not iterable use listMachine.add(list);
        listMachine.assign(list);
    }
 }finally{
     }
   }
    
    }

这就是我希望它帮助我以你的 json 响应为例。

【讨论】:

    猜你喜欢
    • 2022-01-13
    • 1970-01-01
    • 2022-12-23
    • 2021-10-03
    • 2021-06-20
    • 2021-06-04
    • 1970-01-01
    • 2021-12-15
    • 1970-01-01
    相关资源
    最近更新 更多