【问题标题】:How do i render the json data on the canvas?如何在画布上呈现 json 数据?
【发布时间】:2019-05-31 13:40:20
【问题描述】:

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

我尝试在 return 语句之后创建方法,然后调用 list.builder inisde 它,但我做不到。

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(),
    );
  }
}

问题是我不知道我需要在我的列表中调用什么。

任何帮助将不胜感激。
提前致谢。

【问题讨论】:

    标签: json http flutter


    【解决方案1】:

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

    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 FutureBuilder<List<Post>>(
          future: fetchPost(),
          builder: (_, AsyncSnapshot<List<Post>> snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return Center(child: CircularProgressIndicator());
            }
    
            return ListView.builder(
              itemCount: snapshot.data.length,
              itemBuilder: (_, index) {
                final post = snapshot.data[index];
                return ListTile(
                  title: Text(post.title),
                );
              },
            );
          },
        );
      }
    
      @override
      void initState() {
        super.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']['rendered'].toString(),
          link: json['link'].toString(),
        );
      }
    }
    

    【讨论】:

    • 谢谢亲爱的。但是我以这种形式获得了数据 {rendered: .....} 我需要删除已渲染和大括号,或者以其他方式将其转换为没有任何大括号的字符串,只有数据。
    猜你喜欢
    • 1970-01-01
    • 2016-10-26
    • 1970-01-01
    • 1970-01-01
    • 2014-01-29
    • 1970-01-01
    • 2020-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多