Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
281 views
in Technique[技术] by (71.8m points)

flutter - Error while parsing data from http GET Request in Dart

I'm relativly new to Flutter, and I'm currently trying to get Posts from a Wordpress website. In a previous Project, I had a function for that, but now it does not work anymore.

Heres the Function (I replaced the url):

Future<List<Artikel>> fetchArticelList(int artikel) async{
  print("Loading Articels");
  try {
    final response = await http.get(
      'https://WORDPRESSURL/wp-json/wp/v2/posts?_embed&per_page=' + artikel.toString(), 
      headers: {"Accept":"application/json"},
    );
    if (response.statusCode == 200) {
      List<Artikel> artikel = json.decode(response.body)
          .cast<Map<String, dynamic>>()
          .map<Artikel>((json) => Artikel.fromJson(json))
          .toList();
      return artikel;
    } else {
      throw Exception("Error");
    }
  } catch(e){
    throw Exception(e.toString());
  }
}

This is the Error:

E/flutter (10158): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: Exception: Exception: NoSuchMethodError: The method '[]' was called on null.
E/flutter (10158): Receiver: null
E/flutter (10158): Tried calling: [](0)

I ran it with a Debuger, and i found out that it fails in line 7 with the ".toList();" (It's in a Seperate line so i could test it with the Debuger, thats not whats causing the Error). As I said, I'm relativly new to Flutter and I just copied this from a Previous Projekt so I don't know what that does anymore. The function is in the Class Articel, and this is the Widget I call the Function from:

class _androidThomsLineLoadingScreenState extends State<androidThomsLineLoadingScreen> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    Artikel().fetchArticelList(100).then((value) => Navigator.pushReplacementNamed(context, '/artikelListView', arguments: {'artikelList': value}));
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.transparent,
      body: Center(
        child: SpinKitWave(
          color: Color(0xffa51a3e),
        ),
      ),
    );
  }
}

Heres the .jsonFunction:

factory Artikel.fromJson(Map<String, dynamic> json) {
    if (json == null) {
      print("got Empty JSON");
      return null;
    } else {
      print("Erstelle Artikel");
    }
    try {
      //Initialising one line Parameters
      final String renderedTitle =
          new HtmlUnescape().convert(json['title']['rendered']);
      String date = DateFormat.yMd().format(DateTime.parse(json['date']));
      String imageUrl = json['_embedded']['wp:featuredmedia'][0]
          ['media_details']['sizes']['medium']['source_url'];
      String url = json['guid']['rendered'];
      String excerpt = parse(json['excerpt']['rendered'].toString())
          .documentElement
          .text
          .replaceAll(r'
', r'');
      bool thumbnailProvided = false;

      //Get Author(s)
      List<String> authorsNameList = [];
      String authorString = '';
      List<int> authorIdList = [];
      if (json['_embedded']['author'] != null) {
        for (int i = 0; i < json['_embedded']['author'].length; i++) {
          //Generating authorString
          if (i > 0) authorString = authorString + ', ';
          authorString = authorString + json['_embedded']['author'][i]['name'];

          //Generating authorsNameList
          authorsNameList.add(json['_embedded']['author'][i]['name']);

          //Generating authorIdList
          authorIdList.add(json['_embedded']['author'][i]['id']);
        }
      }

      //Generate HTML for Content
      // String content = parse(json['content']['rendered'].replaceAll(r'
', r'').replaceAll(r'"', r'"').toString()).documentElement.text; //Just Text, no formating
      String content = '<h1>$renderedTitle</h1><h4>$date $authorString</h4>' +
          json['content'][
              'rendered']; //HTML Text from API without Pictures                                                                              //HTML Text from APi
      return Artikel(
        title: renderedTitle,
        date: date,
        url: url,
        imageUrl: imageUrl,
        content: content,
        excerpt: excerpt, //Rmeoving HTML from Text
        authorString: authorString,
        authorIdList: authorIdList,
        authorsNameList: authorsNameList,
        thumbnailProvided: thumbnailProvided,
      );
    } catch (e) {
      throw Exception(e.toString());
    }
  }

I hope you can help me, it's probably a realy supid Error, but I'm trying to figure it out for about a day now.

Edit: As requested: heres the request.body. As you see, its a JSON list, the length is nromaly determend by the parameter "artikel", but I put just one here (I alsp replaced the Wordpress URL): https://pastebin.com/5NrB6GkD

question from:https://stackoverflow.com/questions/65846792/error-while-parsing-data-from-http-get-request-in-dart

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As I thought, It was a really Stupid Error. The Error was, that there is a String that is sometimes null, but I over saw that.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...