首页 文章

Flutter - 如何将JSON加载到futurebuilder中

提问于
浏览
0

我正在尝试创建一个非常简单的颤动应用程序,它将从带有参数的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"
}]

1 回答

  • 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);
    }
    

相关问题