Flutter-如何将JSON加载到futurebuilder中

时间:2018-07-31 01:50:09

标签: flutter

我正在尝试创建一个应该非常简单的flutter应用程序,该应用程序将使用参数从POST加载所有数据,并创建包含详细信息的滚动列表。 目前,我没有任何错误,但是即使JSON成功返回,加载循环也永远旋转,任何帮助或想法都将不胜感激。 这是我到目前为止的内容:

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

Future<List<Post>> fetchPosts(http.Client client) async {
var url = "contacts.json";
var client = new http.Client();
var request = new http.Request('POST', Uri.parse(url));
var body = {'type': 'getContacts'};
request.bodyFields = body;

var data = http.post(url, body: {"type": "getContacts"})
  .then((response) {
    print(response.body);
return compute(parsePosts, response.body);

});


}

// A function that will convert a response body into a List<Photo>
List<Post> parsePosts(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();

return parsed.map<Post>((json) => Post.fromJson(json)).toList();
}

class Post {
final String First;
final String Last;
final String Email;
final String Phone;
final String Photo;
final String Full;

Post({this.Full, this.First, this.Last, this.Photo, this.Email, this.Phone});

factory Post.fromJson(Map<String, dynamic> json) {
return new Post(
  Full: json['Full'] as String,
  First: json['First'] as String,
  Last: json['Last'] as String,
  Photo: json['Photo'] as String,
  Email: json['Email'] as String,
  Phone: json['Phone'] as String,
);
}
}

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

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final appTitle = 'CONTACTS';

return MaterialApp(
  title: appTitle,
  home: MyHomePage(title: appTitle),
);
}
}

class MyHomePage extends StatelessWidget {
final String title;

MyHomePage({Key key, this.title}) : super(key: key);

@override
Widget build(BuildContext context) {
return Scaffold(
  appBar: AppBar(
    title: Text(title),
  ),
  body: FutureBuilder<List<Post>>(
    future: fetchPosts(http.Client()),
    builder: (context, snapshot) {
      if (snapshot.hasError) print(snapshot.error);

      return snapshot.hasData
          ? PhotosList(photos: snapshot.data)
          : Center(child: CircularProgressIndicator());
    },
  ),
  );
}
}

class PhotosList extends StatelessWidget {
final List<Post> photos;

PhotosList({Key key, this.photos}) : super(key: key);

@override
Widget build(BuildContext context) {
return ListView.builder(
    itemCount: photos == null ? 0 : photos.length,
    itemBuilder: (BuildContext context, i) {
      return new ListTile(
          title: new Text(photos[i].Last + " " + photos[i].First),
          subtitle: new Text(photos[i].Phone),
          leading: new CircleAvatar(
            backgroundImage:
            new NetworkImage(photos[i].Photo),
          )
      );
    }
 );
 }
 }

像这样测试JSON数据:

[{
"Full": "Billy Bobbins",
"First": "Billy",
"Last": "Bobbins",
"Photo": "",
"Email": "billyb@here.com",
"Phone": "18885551212"
}, {
"Full": "Darron Dragonborn",
"First": "Darron",
"Last": "Dragonborn",
"Photo": "",
"Email": "dragond@here.com",
"Phone": "18005551111"
}]

2 个答案:

答案 0 :(得分:0)

因为您使用的是Futureasync,所以可以使用await进行异步操作。 所以您的fetchPosts应该像这样

Future<List<Post>> fetchPosts(http.Client client) async {
  var url = "contacts.json";
  var client = new http.Client();
  var request = new http.Request('POST', Uri.parse(url));
  var body = {'type': 'getContacts'};
  request.bodyFields = body;

  var data = await http.post(url, body: {"type": "getContacts"});
  print(data.body);
  return await compute(parsePosts, data.body);
}

答案 1 :(得分:0)

您也可以参考这个。真的很有帮助。

https://flutter.dev/docs/cookbook/networking/background-parsing