从JSON数组中获取名称并在Listview中显示第一个字符

问题描述 投票:0回答:3

我有一个项目的列表视图,他们都有成员分配给他们,我想在Futurebuilder中使用Listview.builder显示这些成员,我想返回一个CircleAvatar,其名字的第一个字母如下:'H' - ' S'......

我试过这样做但是我在所有细胞中都得到了字母“H”。我希望它像:'H'和'S' - 对于hugo和studentone!

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

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": "109 days ago",
    "overview_requests": [
        {
            "id": 28,
            "user": {
                "username": "hugo",
                "fullname": "Hugo Johnsson"
            },
            "group": 81
        }
    ]
},
{
    "id": 83,
    "users": [
        {
            "username": "hugo",
            "fullname": "Hugo Johnsson"
        }
    ],
    "title": "A ducking project",
    "description": "Hej nu har du din ändrade beskrivning!",
    "subject": "No subject",
    "deadline": "2019-01-09",
    "days_left": "106 days ago",
    "overview_requests": []
},
{
    "id": 86,
    "users": [
        {
            "username": "hugo",
            "fullname": "Hugo Johnsson"
        }
    ],
    "title": "tettestdsfsdf",
    "description": "sdfsadfasdfasdfsadf",
    "subject": "No subject",
    "deadline": "2019-01-09",
    "days_left": "106 days ago",
    "overview_requests": []
}
]

Here is a picture of the APP

Here is a screenshot of how It looks now! with the row implemented!

这是卡/ UI

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
        future: _getProjects(),
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.data == null) {
             return Container(
              child: Center(
                child: CircularProgressIndicator(),
            ),
        );
      } else
        return ListView.builder(
            scrollDirection: Axis.horizontal,
            itemCount: snapshot.data.length,
            itemBuilder: (BuildContext context, int index) {
              return GestureDetector(
                onTap: () {
                  Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => EveryProjectPage(
                                snapshot.data[index],
                                snapshot.data[index].id,
                              )));
                },
                child: Card(
                  margin: EdgeInsets.only(right: 20),
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(18)),
                  child: Container(
                    width: 270,
                    child: Column(
                      children: <Widget>[
                        //TOP PART
                        Container(
                          margin: EdgeInsets.only(top: 10, left: 10),
                          child: Row(
                            children: <Widget>[
                              Container(
                                child: Icon(
                                  Icons.account_circle,
                                  color: Colors.cyan,
                                ),
                                margin: EdgeInsets.only(right: 10),
                              ),
                              Container(
                                child: Icon(
                                  Icons.more_vert,
                                  color: Colors.black54,
                                ),
                                margin: EdgeInsets.only(right: 5),
                              ),
                              DisplayPercentageLinearly(
                                  snapshot.data[index].id)
                            ],
                          ),
                        ),

                        //CIRCLE AVATARS
                        Container(
                            alignment: Alignment.centerLeft,
                            margin: EdgeInsets.only(
                                top: 15, left: 12, right: 8),
                            height: 40,
                            child: FutureBuilder<List<Project>>(
                                future: _getProjects(),
                                builder: (context, snapshot) {
                                  if (!snapshot.hasData)
                                    return Container(
                                        width: 20,
                                        height: 20,
                                        alignment: Alignment.centerLeft,
                                        child: CircularProgressIndicator());
                                  return ListView.builder(
                                    scrollDirection: Axis.horizontal,
                                    itemCount:
                                        snapshot.data[index].users.length,
                                    itemBuilder: (context, index) {
                                      var users =
                                          snapshot.data[index].users;

                                      if (users == null) {
                                        return makeAvatar('?');
                                      }

                                      return Row(
                                        children: users
                                            .map<CircleAvatar>((e) =>
                                                makeAvatar(e['username']))
                                            .toList(),
                                      );
                                    },
                                  );
                                })),

                        Container(
                          margin: EdgeInsets.only(top: 75, left: 20),
                          alignment: Alignment.centerLeft,
                          child: Text(
                              "You have ${snapshot.data[index].days_left} days left"),
                        ),

                        //TEXT PART
                        Container(
                          alignment: Alignment.centerLeft,
                          margin:
                              EdgeInsets.only(left: 20, right: 15, top: 6),
                          child: Text(
                            "${snapshot.data[index].title[0].toString().toUpperCase()}"
                                "${snapshot.data[index].title.toString().substring(1)}",
                            style: TextStyle(
                                color: Colors.black87,
                                fontWeight: FontWeight.w500,
                                fontSize: 18),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              );
            });
    });
  }
} 

class DisplayPercentageLinearly extends StatefulWidget {
  final int id;

  DisplayPercentageLinearly(this.id);

  @override
  _DisplayPercentageLinearlyState createState() =>
  _DisplayPercentageLinearlyState(this.id);
}

   class _DisplayPercentageLinearlyState extends       State<DisplayPercentageLinearly> {
  //ID
  final int id;

   _DisplayPercentageLinearlyState(this.id);

    @override
   Widget build(BuildContext context) {
 return LinearPercentIndicator(
  width: 175,
  lineHeight: 13,
  percent: 0.2,
  backgroundColor: Colors.black12,
  progressColor: Colors.amber,
  center: Text(
    "",
    style: TextStyle(color: Colors.white),
    ),
   );
    }
}
json api listview indexing flutter
3个回答
0
投票

我误解了你的问题,我重新拟定了我的答案,实际上回答了你的问题。

New answer:

如果你想迭代var users,你可以使用map()函数,如果var users是一个列表。

You can use this:

itemBuilder: (context, index) {
  var users = snapshot.data[index].users;
  return Column( // It doesn't need to be Column, it can be any widget with a children attribute.
    children: users.map((var user) {
      return CircleAvatar(
        foregroundColor: Colors.white,
        backgroundColor: Colors.blue,
        child: Text(user['username'].substring(0,1).toUpperCase()),
      );
    }).toList(),
  );
},

Explanation

让我解释一下代码:我们需要返回一个带有children属性的小部件,因为作为子级,我们为每个用户返回一个带有List小部件的CircularAvatar()。在这种情况下,我们使用Column()小部件。

在children属性中,我们调用users.map(),这将遍历用户内的每个用户。 map()采用回调函数,回调函数将为用户List中的每个项执行。并且该回调函数接受一个参数,该参数是List的项目。

在回调函数中,我们现在可以返回一个CircularAvatar(),作为孩子,我们返回一个Text()小部件。作为参数,我们调用user['username']来获取迭代时当前用户的用户名。然后我们调用substring(0,1)来获取用户名的第一个字母。最后我们打电话给toUpperCase()以确保这封信是大写的。

Full code:

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;
              return Column(
                children: users.map((var user) {
                  return CircleAvatar(
                    foregroundColor: Colors.white,
                    backgroundColor: Colors.blue,
                    child: Text(user['username'].substring(0,1).toUpperCase()),
                  );
                }).toList(),
              );
            },
          );
        },
      ),
    );
  }
}

Hope I understood right now and that this is helpful for you.


-1
投票

var users = snapshot.data [index] .users;给你用户列表,你应该迭代获得那些用于构建列表的那些,你只是得到列表的第一项。

String username = ... users[0]['username'] ...
© www.soinside.com 2019 - 2024. All rights reserved.