【问题标题】:Http.get returns nullHttp.get 返回 null
【发布时间】:2019-04-16 17:49:36
【问题描述】:

我在从服务器 API 获取数据时遇到问题。结果返回一个空值。谁能帮我解决它?谢谢你,非常感谢。

class TrackingPage extends StatefulWidget {
  @override
  _TrackingPageState createState() => _TrackingPageState();
}

class _TrackingPageState extends State<TrackingPage> {
  _fetchPost() {
    API.fetchPost().then((response) {
      setState(() {
        return Cargo.fromJson(response.body);
      });
    });
  }

  initState() {
    super.initState();
    _fetchPost();
  }

  dispose() {
    super.dispose();
  }

  Widget _trackingpg() {
    return Container(
        child: FutureBuilder<Cargo>(
      future: _fetchPost(),
      builder: (context, snapshot) {
        Text(snapshot.data.status);
      },
    ));
  }
}

这是我的 API 类

class API{
  static Future fetchPost(){
    var url = baseUrl;
    return http.get(url);
  }
}

PODO 类

Cargo cargoFromJson(String str) {
  final jsonData = json.decode(str);
  return Cargo.fromJson(jsonData);
}

String cargoToJson(Cargo data) {
  final dyn = data.toJson();
  return json.encode(dyn);
}

class Cargo {
  String cargoClass;
  String cargoId;
  String type;
  String status;
  List<TemperatureReading> temperatureReadings;

  Cargo({
    this.cargoClass,
    this.cargoId,
    this.type,
    this.status,
    this.quantity,
    this.origin,
    this.temperatureReadings,
  });

  factory Cargo.fromJson(Map<String, dynamic> json) => new Cargo(
    cargoClass: json["\u0024class"],
    cargoId: json["cargoId"],
    type: json["type"],
    status: json["status"],
    temperatureReadings: new List<TemperatureReading>.from(
        json["temperatureReadings"]
            .map((x) => TemperatureReading.fromJson(x))),

  );

  Map<String, dynamic> toJson() => {
    "\u0024class": cargoClass,
    "cargoId": cargoId,
    "type": type,
    "status": status,
    "temperatureReadings":
    new List<dynamic>.from(temperatureReadings.map((x) => x.toJson())),

  };
}

class TemperatureReading {
  String temperatureReadingClass;
  double centigrade;
  String cargo;
  String transactionTimestamp;

  TemperatureReading({
    this.temperatureReadingClass,
    this.centigrade,
    this.cargo,
    this.transactionTimestamp,
  });

  factory TemperatureReading.fromJson(Map<String, dynamic> json) =>
      new TemperatureReading(
        temperatureReadingClass: json["\u0024class"],
        centigrade: json["centigrade"].toDouble(),
        cargo: json["cargo"],
        transactionTimestamp: json["transactionTimestamp"],
      );

  Map<String, dynamic> toJson() => {
    "\u0024class": temperatureReadingClass,
    "centigrade": centigrade,
    "cargo": cargo,
    "transactionTimestamp": transactionTimestamp,
  };
}

它表明“在 null 上调用了 getter 'status'。 收件人:空" Json 文件是嵌套列表格式。在这种情况下,我试图获取字符串“status”,但没有成功。

【问题讨论】:

  • 阅读FutureBuilder 文档-提示:你不能无条件使用snapshot.data.*
  • 您是否阅读过FutureBuilder 文档?他们甚至展示了一些示例代码,你看到了吗?如果有,还有什么不清楚的地方?
  • 对不起先生,我只是一个新手。
  • 因此,如果您是新手,则必须阅读文档的次数越多 - 您是否尝试过我提到的示例代码?
  • 感谢您的建议。我能够得到响应,但我无法对其进行解码。

标签: dart flutter


【解决方案1】:

我做了这样的事情。如果可行,您可以尝试一下,那会很棒。

Cargo parsePosts(String responseBody) {

  var myClass = Cargo.fromJson(jsonDecode(responseBody));
  for (var result in myClass.data.toList()) {
    print('result');
    print(result?.id);
  }
  return myClass;
}

Future<Cargo> fetchPosts(http.Client client) async {
  final response = await client.get(
     'base_url',
      headers: {
        "Authorization":
            "if any"
      });
  print(response.body);
  // compute function to run parsePosts in a separate isolate
  return compute(parsePosts, response.body);
}

class HomePage extends StatelessWidget {
  final String title;

  HomePage({Key key, this.title}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: FutureBuilder<Cargo>(
        future: fetchPosts(http.Client()),
        builder: (context, snapshot) {
          if (snapshot.hasError) print(snapshot.error);

          return snapshot.hasData
              ? ListViewPosts(posts: snapshot.data)
              : Center(child: CircularProgressIndicator());
        },
      ),
    );
  }
}

class ListViewPosts extends StatelessWidget {
  final Cargo posts;

  ListViewPosts({Key key, this.posts}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child:Text(posts.status)
    );
  }
}

【讨论】:

  • 但是“状态”不是一个列表。 json 文件是嵌套列表格式。有关系吗?
  • class Cargo { String cargoClass;字符串货号;字符串类型;字符串状态;整数数量;原产地; List 温度读数;列出 gpsReadings;列表 topleReadings; List luxReadings;布尔温度违规; bool topple违规;布尔框打开;国际临时计数; bool previousViolation;字符串合约;字符串装运;字符串智能容器; CargoLoadedClass cargoPacked; CargoLoadedClass cargoLoaded; CargoLoadedClass cargoReceived;
  • 我已经编辑了我的答案。如果它有效或有任何错误,请回复
  • 计算函数未定义。并且没有为“货物”类定义吸气剂“数据”。这些是我遇到的问题。
  • 代替'data',你可以写你想展示的东西
猜你喜欢
  • 2017-05-10
  • 2019-11-13
  • 1970-01-01
  • 2014-08-12
  • 2020-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-19
相关资源
最近更新 更多