Flutter,FutureBuilder快照错误:类型'int'不是类型'String'的子类型

时间:2019-07-10 22:45:43

标签: flutter dart xmlhttprequest

当我尝试从Post获取数据时,我因此错误而失败。

enter image description here

似乎nodeid变量被视为int类型。 所以我在下面这样尝试过

 factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
      nodeid: nodeid.toString(),

但是它不起作用。

这是下面的完整代码。

import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

Future<Post> fetchPost() async {
  var params = {                              // Request를 위한 parameters 만듦.
    //TODO 서비스키 UTF-8 encoding이 필요함.
    "ServiceKey": utf8.encode('t8iGBTBFQc5nMq9ytuMZQ7jxR8ZMzohG%2F5o0i80f%2BehjFhMpkADfArAvFk%2BjHsPMFFEThQgejzujdpfou%2FDWng%3D%3D'),
    "cityCode": Uri.encodeFull("25"),
    "nodeId": Uri.encodeFull("DJB8001793ND"),
  };

  Uri uri = Uri.parse('http://openapi.tago.go.kr/openapi/service/ArvlInfoInqireService/getSttnAcctoArvlPrearngeInfoList'); // URI 지정.
  final newURI = uri.replace(queryParameters: params); // queryParameters를 넣어 URI를 다시 만듦.

  final response = await http.get(
    newURI,
    headers: {
      "Accept": "application/json", // The server is returning you XML, but you are trying to parse that as if it is JSON.
    },
  );

  /*
  final responseJson = jsonDecode(response.body);
  debugPrint('$responseJson'); //
  print('$responseJson'); //{response: {header: {resultCode: 99, resultMsg: SERVICE KEY IS NOT REGISTERED ERROR.}}}
  print(Uri.encodeFull("DJB8001793ND")); //I/flutter ( 7299): DJB8001793ND
  */
  //return Post.fromJson(responseJson);

  if (response.statusCode == 200) {
    // If server returns an OK response, parse the JSON.
    return Post.fromJson(jsonDecode(response.body));
  } else {
    // If that response was not OK, throw an error.
    throw Exception('Failed to load post');
  }
}

class Post { 
  final String nodeid;
  //final String nodenm;
  //final int arrtime;
  //final int routeno;

  Post({
    this.nodeid, 
    //this.nodenm,
    //this.arrtime,
    //this.routeno
  });

  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
      nodeid: json['nodeid'],
      //nodenm: json['nodenm'],
      //arrtime: json['arrtime'],
      //routeno: json['routeno'],
    );
  }
}

void main() => runApp(MyApp(post: fetchPost()));

class MyApp extends StatelessWidget {
  final Future<Post> post; 
  MyApp({Key key, this.post}) : super(key: key);


  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Fetch Data Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Fetch Data Example'),
        ),
        body: Center(
          child: FutureBuilder<Post>(
            future: post,
            builder: (context, snapshot) {
              if (snapshot.hasData) { // 만약에 Post에서 데이터가 존재한다면
                return Text(snapshot.data.nodeid); // 데이터 스냅샷을 보여준다.
              } else if (snapshot.hasError) {        // << I got an error from here.  
                return Text("${snapshot.error}");
              }
              // By default, show a loading spinner.
              return CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}

这是XML文件。

enter image description here

有什么我想念的吗?

2 个答案:

答案 0 :(得分:0)

如果服务器向您返回XML,则设置标记不会更改数据类型。

第二,我认为api无法正常工作。

<?xml version="1.0" encoding="UTF-8"?>
<response>
   <header>
      <resultCode>99</resultCode>
      <resultMsg>SERVICE KEY IS NOT REGISTERED ERROR.</resultMsg>
   </header>
</response>

我尝试查看https://tago.go.kr/自己找到该API以获得更多信息。但这是韩文。

处理原始问题。

如果api返回的数据是XML格式的数据。没什么大不了的,尽管您可以将其转换为JSON,然后照常进行。

import 'package:xml2json/xml2json.dart'; // add this line
...
Xml2Json xml2json = new Xml2Json();  //Make an instance.

// Response is in xml, parse using xml2json
xml2json.parse(response.body);

var jsondata = xml2json.toGData(); 
// now we have data in json format 

// and are ok to continue
var data = json.decode(jsondata);
// data is json do what you need to
...

答案 1 :(得分:0)

          if (snapshot.hasData) { // 만약에 Post에서 데이터가 존재한다면
            return Text(snapshot.data.nodeid); // 데이터 스냅샷을 보여준다.
          } else if (snapshot.hasError) {        // << I got an error from here.  
            return Text("${snapshot.error}");
          }

您的类型未更改为字符串。更改为:

          if (snapshot.hasData) { // 만약에 Post에서 데이터가 존재한다면
            return Text(snapshot.data.nodeid.toString()); // 데이터 스냅샷을 보여준다.
          } else if (snapshot.hasError) {        // << I got an error from here.  
            return Text("${snapshot.error}");
          }