如何在画布上渲染JSON数据?

时间:2019-05-31 13:40:20

标签: json http flutter

我在这里找到了一个关于如何在flutter中解析json数据的解决方案,并且一切正常。现在如何在手机屏幕上渲染它们?

我试图在return语句后制作方法,然后调用list.builder初始化它,但我做不到。

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

void main() => runApp(PostHome());


class PostHome extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text("My Test"),),
      body: PostScreen(),

      ),
    );
  }
}

class PostScreen extends StatefulWidget {
  @override
  _PostScreenState createState() => _PostScreenState();
}

class _PostScreenState extends State<PostScreen> {

  List<Post> _postList =new List<Post>();

  Future<List<Post> > fetchPost() async {
    final response =
    await http.get('http://alkadhum-col.edu.iq/wp-json/wp/v2/posts/');

    if (response.statusCode == 200) {
      // If the call to the server was successful, parse the JSON
      List<dynamic> values=new List<dynamic>();
      values = json.decode(response.body);
      if(values.length>0){
        for(int i=0;i<values.length;i++){
          if(values[i]!=null){
            Map<String,dynamic> map=values[i];
            _postList.add(Post.fromJson(map));
            print('${map['link']}');
          }
        }
      }
      return _postList;

    } else {
      // If that call was not successful, throw an error.
      throw Exception('Failed to load post');
    }
  }
  @override
  Widget build(BuildContext context) {
    return Container(

    );
  }

      @override
      void initState() {
        fetchPost();
      }


}

class Post {

  final int id;
  String title;
  String link;
  String sourceurl;


  Post({this.id, this.title, this.link, this.sourceurl});

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

问题是我不知道自己需要在列表中打电话什么。

任何帮助将不胜感激。
预先感谢。

1 个答案:

答案 0 :(得分:0)

您应该看看如何使用FutureBuilder小部件。

interface{}