Flutter:在Futurebuilder中显示包含Listview的JSON字符串数组

时间:2019-04-18 10:47:24

标签: arrays json list listview flutter

我有一个JSON,仅显示字符串没有问题,但是我的问题是字符串数组。我有一个Future函数,该函数从JSON中获取数据,然后将其显示在futurebuilder中。

为了清楚起见,我希望用户名“ hugo”和“ studentone”显示在listview.builder中!

如果有人可以说出如何完成有助于加载的未来功能!

JSON:

    {
    "id": 81,
    "users": [
        {
            "username": "hugo",
            "fullname": "Hugo Johnsson"
        },
        {
            "username": "studentone",
            "fullname": "Student One"
        }
    ],
    "title": "test med teacher chat",
    "description": "This project does not have a description.",
    "subject": "No subject",
    "deadline": "2019-01-06",
    "days_left": "91 days ago",
    "overview_requests": [
        {
            "id": 28,
            "user": {
                "username": "hugo",
                "fullname": "Hugo Johnsson"
            },
            "group": 81
        }
    ]
},

未来功能:        未来> _getUSERS()异步{

var data = await http.get("IP");
var jsonData = json.decode(data.body); 

List<USER> users;

for (var JData in jsonData) {

  var jsonUsers = JData["users"];

  for(int i = 0; i<users.length ; i++) {
    var user = jsonUsers[i];
    users.add(USER(user["username"], user["fullname"]));
  }
}

用户界面:

child: FutureBuilder(
      future: _getUSERS(),
      builder: (BuildContext context, AsyncSnapshot snapshot ) {
        if (snapshot.data == null){
          return Container(
            child: Center(
              child: CircularProgressIndicator(),
            ),
          );
        }
        else return ListView.builder(
          itemCount: snapshot.data.length,
          itemBuilder: (BuildContext context, int index) {
            return ListTile(
              title: Text(snapshot.data[index].username),
            );
          }
        );
      }
    ),

2 个答案:

答案 0 :(得分:0)

将来的函数中有一些错误会获取json数据。

我已更正,这里是:

Future<List<USER>> _getUSERS() async {

var data = await http.get("IP");
var jsonData = json.decode(data.body); 

List<USER> users;

for (var JData in jsonData) {

  var jsonUsers = JData["users"];

  for(int i = 0; i<jsonUsers.length ; i++) {
    var user = jsonUsers[i];
    users.add(USER(user["username"], user["fullname"]));
  }
}
return users;

修复:

  1. for(int i = 0; i << strong> jsonUsers .length; i ++)
  2. 回访用户;

答案 1 :(得分:0)

这是我所做的。您可以从此

获取参考
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_list_http/MyApp1.dart';
import 'package:flutter_list_http/XYZ.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:fluttertoast/fluttertoast.dart';

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

XYZ parsePosts(String responseBody) {

  var myClass = XYZ.fromJson(jsonDecode(responseBody));
  for (var result in myClass.data.toList()) {
    print('result');
    print(result?.id);
  }
  return myClass;
}

Future<XYZ> fetchPosts(http.Client client) async {
  final response = await client.get(
      'url',
      headers: {
        "Authorization":
           "headers if any"
      });
  print(response.body);
  // compute function to run parsePosts in a separate isolate
  return compute(parsePosts, response.body);
}

class HomePage extends StatelessWidget {
  final String title;

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

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

          return snapshot.hasData
              ? ListViewPosts(posts: snapshot.data)
              : Center(child: CircularProgressIndicator());
        },
      ),
    );
  }
}

class ListViewPosts extends StatelessWidget {
  final XYZ posts;

  ListViewPosts({Key key, this.posts}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: ListView.builder(
          itemCount: posts.data.length,
          padding: const EdgeInsets.all(15.0),
          itemBuilder: (context, position) {
            return Column(
              children: <Widget>[
                Divider(height: 5.0),
                ListTile(
                  title: Text(
                    '${posts.data[position].name}',
                    style: TextStyle(
                      fontSize: 22.0,
                      color: Colors.deepOrangeAccent,
                    ),
                  ),
                  onTap: () => _onTapItem(context, posts, position),
                ),
              ],
            );
          }),
    );
  }

  void _onTapItem(BuildContext context, XYZ posts, int position) {

    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => MyApp1()),
    );
  }
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final appTitle = 'JavaSampleApproach HTTP-JSON';

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

希望有帮助。