从另一个字符串的JSON数组中获取的另一个FutureBuilder中的Flutter FutureBuilder

时间:2019-04-23 18:22:06

标签: json api listview flutter future

我要在另一个Futurebuilder中放入一个Futurebuilder。我有一个JSON,我想在CircleAvatars内部显示用户名,并且只显示第一个字母!

我已经尝试了很多改变类及其组成的方法,试图使其正常工作,但是我似乎永远都做不到!

我得到这些错误:

  

flutter:引发了另一个异常:NoSuchMethodError:吸气剂   'length'被调用为null。

     

flutter:引发了另一个异常:NoSuchMethodError:该方法   在空值上调用了[[]]。

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": "107 days ago",
"overview_requests": [
    {
        "id": 28,
        "user": {
            "username": "hugo",
            "fullname": "Hugo Johnsson"
        },
        "group": 81
    }
]

}

Flutter内部的类:

class Project {
  final int id;
  final String title;
  final String description;
  final String deadline;
  final String subject;
  final String days_left;
  final List<USER> users;

  Project(
      this.id,
      this.title,
      this.description,
      this.deadline,
      this.subject,
      this.days_left,
      this.users
  );
}

class USER {
  final String username;
  final String fullname;

USER(
  this.username,
  this.fullname
  );
}

未来:

  Future<List<Project>> _getProjects() async {
var data = await http.get(
    "http://studieplaneraren.pythonanywhere.com/api/projects/${UserLog().Username}/?format=json");
var jsonData = json.decode(data.body); //an array of json objects

List<Project> allProjects = [];

for (var JData in jsonData) {
  Project project = Project(
      JData["id"],
      JData["title"],
      JData["description"],
      JData["deadline"],
      JData["subject"],
      JData["days_left"],
      JData[USER("username", "fullname")]
  );

  allProjects.add(project);
}

return allProjects;
}

CircleAvatars:

                      //CIRCLE AVATARS
                  Container(
                    margin: EdgeInsets.only(top: 10, left: 8, right: 8),
                    height: 40,
                    child: FutureBuilder(
                      future: _getProjects(),
                      builder: (context, snapshot) => ListView.builder(
                        itemCount: snapshot.data.length,
                        itemBuilder: (context, userIndex) =>
                            CircleAvatar(
                              foregroundColor: Colors.white,
                              backgroundColor: UserLog().Color,
                              child: Text(snapshot.data[index].users[userIndex].username[0]),
                            )
                      )
                    )
                    ),

2 个答案:

答案 0 :(得分:0)

尝试一下

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

class FutureBuilderJSON extends StatefulWidget {
  FutureBuilderJSON({Key key}) : super(key: key);

  _FutureBuilderJSONState createState() => _FutureBuilderJSONState();
}

class _FutureBuilderJSONState extends State<FutureBuilderJSON> {
  Future<List<Project>> _getProjects() async {
    var data = await http.get(
        "http://studieplaneraren.pythonanywhere.com/api/projects/hugo/?format=json");
    var jsonData = json.decode(data.body); //an array of json objects
    List<Project> allProjects = [];
    for (var JData in jsonData) {
      Project project = Project(
        JData["id"],
        JData["title"],
        JData["description"],
        JData["deadline"],
        JData["subject"],
        JData["days_left"],
        JData["users"],
      );
      allProjects.add(project);
    }

    return allProjects;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(top: 10, left: 8, right: 8),
      child: FutureBuilder<List<Project>>(
        future: _getProjects(),
        builder: (context, snapshot) {
          if (!snapshot.hasData)
            return Center(child: CircularProgressIndicator());
          return ListView.builder(
            itemCount: snapshot.data.length,
            itemBuilder: (context, index) {
              var users = snapshot.data[index].users;
              String username =
                  users != null ? users[0]['username'] : 'Default';
              var oneChar = username.substring(0, 1).toUpperCase();
              return CircleAvatar(
                foregroundColor: Colors.white,
                backgroundColor: Colors.blue,
                child: Text(oneChar),
              );
            },
          );
        },
      ),
    );
  }
}

class Project {
  final int id;
  final String title;
  final String description;
  final String deadline;
  final String subject;
  final String days_left;
  final List<dynamic> users;

  Project(
    this.id,
    this.title,
    this.description,
    this.deadline,
    this.subject,
    this.days_left,
    this.users,
  );
}

class User {
  final String username;
  final String fullname;
  User(this.username, this.fullname);
}

答案 1 :(得分:0)

您可以尝试使用以下代码。

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

class FutureBuilderJSON extends StatefulWidget {
  FutureBuilderJSON({Key key}) : super(key: key);

  _FutureBuilderJSONState createState() => _FutureBuilderJSONState();
}

class _FutureBuilderJSONState extends State<FutureBuilderJSON> {
  Future<List<Project>> _getProjects() async {
    var data = await http.get(
        "http://studieplaneraren.pythonanywhere.com/api/projects/hugo/?format=json");
    var jsonData = json.decode(data.body); //an array of json objects
    List<Project> allProjects = [];
    for (var JData in jsonData) {
      Project project = Project(
        JData["id"],
        JData["title"],
        JData["description"],
        JData["deadline"],
        JData["subject"],
        JData["days_left"],
        JData["users"],
      );
      allProjects.add(project);
    }

    return allProjects;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(top: 10, left: 8, right: 8),
      child: FutureBuilder<List<Project>>(
        future: _getProjects(),
        builder: (context, snapshot) {
          if (!snapshot.hasData)
            return Center(child: CircularProgressIndicator());
          return ListView.builder(
            itemCount: snapshot.data.length,
            itemBuilder: (context, index) {
              List<dynamic> users = snapshot.data[index].users;
              List<Widget> ws = List<Widget>();
              users.forEach((u) {
                var oneChar = u['username'].substring(0, 1).toUpperCase();
                var w = CircleAvatar(
                  foregroundColor: Colors.white,
                  backgroundColor: Colors.blue,
                  child: Text(oneChar),
                );
                ws.add(w);
              });
              // String username =
              //     users != null ? users[0]['username'] : 'Default';
              // var oneChar = username.substring(0, 1).toUpperCase();

              // return CircleAvatar(
              //   foregroundColor: Colors.white,
              //   backgroundColor: Colors.blue,
              //   child: Text(oneChar),
              // );
              return Column(
                children: ws,
              );
            },
          );
        },
      ),
    );
  }
}

class Project {
  final int id;
  final String title;
  final String description;
  final String deadline;
  final String subject;
  final String days_left;
  final List<dynamic> users;

  Project(
    this.id,
    this.title,
    this.description,
    this.deadline,
    this.subject,
    this.days_left,
    this.users,
  );
}

class User {
  final String username;
  final String fullname;
  User(this.username, this.fullname);
}