如何在类之间将数组的可变结果引发抖动

时间:2019-05-26 22:55:10

标签: flutter dart

我正在尝试将json流程的功能结果从一个类传输到另一个类。 这是我渲染的json:

[
  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat",
    "body": "quia et suscipit\nsuscipit"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "qui est esse",
    "body": "est rerum tempore vitae\nsequi"
  }
]

当我尝试在该方法内打印但未在目标类上打印时,显示方法的结果。这是我的代码:

源类:

class DataNews {
  final String id;
  final String title;
  final String body;

  DataNews({this.id, this.title, this.body});

  factory DataNews.fromJson(json) {
    return DataNews(id: json['id'].toString(), title: json['title'], body: json['body']);
  }
}

getData() async {
    final response = await http.get('https://jsonplaceholder.typicode.com/posts');
    List data = json.decode(response.body);
    final items = (data).map((i) => new DataNews.fromJson(i));
    print('Satu');
    print(items.elementAt(1).id);
    print(items.elementAt(1).title);
    print(items.elementAt(1).body);
    print('Dua');
    return items;
}

目标类别:

class News extends StatefulWidget {  
  @override
  _NewsState createState() => _NewsState(post: getData());
}

class _NewsState extends State<News> {
  Iterable<dynamic> post;
  _NewsState({Key key, this.post});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Text(post.elementAt(0).title),
      ),
    );
  }
}

我想在Container上显示结果之一。该怎么做?

1 个答案:

答案 0 :(得分:0)

首先,您的方法getData()不返回Iterable,而是返回Future<Iterable>,但是最好返回Future<List>。请注释您正在使用的类型,它将使您的生活更加轻松。

Future<List<DataNews>> getData() async {
  final response = await http.get('https://jsonplaceholder.typicode.com/posts');
  List data = json.decode(response.body);
  List<DataNews> items = data.map((i) => DataNews.fromJson(i)).toList();
  return items;
}

第二,您不应将任何数据传递到_NewsState。数据要么来自父级Widget并存储在News中,要么在_NewsState本身中获取数据。 FutureBuilder可以帮助您显示来自Future的内容。

class News extends StatefulWidget {
  @override
  _NewsState createState() => _NewsState();
}

class _NewsState extends State<News> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder(
        future: getData(), // Fetch the data
        builder: (_, AsyncSnapshot snapshot) {
          if (snapshot.hasData) {
            // If your List got fetched, them show each DataNews using a ListView
            List<DataNews> newsList = snapshot.data;
            return ListView.builder(
              itemCount: newsList.length,
              itemBuilder: (_, int index) {
                return Container(
                  child: Text(newsList[index].title),
                );
              },
            );
          } else {
            // If you have no data, show a progress indicator
            return Center(
              child: CircularProgressIndicator(),
            );
          }
        },
      ),
    );
  }
}