如何将地图列表中的项目显示到列表视图中

Posted

技术标签:

【中文标题】如何将地图列表中的项目显示到列表视图中【英文标题】:How to display items from a list of maps into a listview 【发布时间】:2020-06-26 13:35:22 【问题描述】:

我不知道如何从系统主题或视频请求中显示主题 ID 的值。

我从一个 http 请求获取源到这个 url:https://public.free.beeceptor.com/api

以下是回复。


    "body": 
        "System Topics": [
            
                "Topic ID": "2",
                "Title": "Tres",
                "Description": "Dos"
            ,
            
                "Topic ID": "3",
                "Title": "Pls Work",
                "Description": "nfewtrwe"
            ,
            
                "Topic ID": "4",
                "Title": "Juice",
                "Description": "Bar"
            
        ],
        "Video Requests": [
            
                "Topic ID": "1",
                "From Name": "New User",
                "From Email": "dawdw@gmail.com",
                "Title": "What's you first christmas like?",
                "Description": "Please tell me about your Christmas?"
            ,
            
                "Topic ID": "4",
                "From Name": "New User",
                "From Email": "dawdw@gmail.com",
                "Title": "What is your name?",
                "Description": ""
            ,
            
                "Topic ID": "5",
                "From Name": "New User",
                "From Email": "dawdw@gmail.com",
                "Title": "What is your name?",
                "Description": ""
            ,
            
                "Topic ID": "6",
                "From Name": "New User",
                "From Email": "dawdw@gmail.com",
                "Title": "What is your name?",
                "Description": ""
            ,
            
                "Topic ID": "7",
                "From Name": "New User",
                "From Email": "dawdw@gmail.com",
                "Title": "What is your name?",
                "Description": ""
            ,
            
                "Topic ID": "8",
                "From Name": "New User",
                "From Email": "dawdw@gmail.com",
                "Title": "What is your name?",
                "Description": ""
            ,
            
                "Topic ID": "9",
                "From Name": "New User",
                "From Email": "dawdw@gmail.com",
                "Title": "What is your name?",
                "Description": "From james"
            ,
            
                "Topic ID": "10",
                "From Name": "New User",
                "From Email": "dawdw@gmail.com",
                "Title": "What is your name?",
                "Description": "From james"
            
        ]
    

我想像这样将值显示到列表视图中,但直接来自 https 流。


Container(
                width: 338,
                height: 500.0,
                child: ListView.builder(
                  itemCount: data == null ? 0 : data.length,
                  itemBuilder: (context, i) 
                    return Container(
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(20.0),
                      ),
                      height: 74.0,
                      margin: const EdgeInsets.only(bottom: 10.0),
                      width: MediaQuery.of(context).size.width,
                      child: Row(
                        children: <Widget>[
                          Container(
                            child: Text(data[i]["System Topics"]["Topic ID"]),
                            height: 74.0,
                            width: 73.0,
                            decoration: BoxDecoration(
                              color: Colors.orange,
                              borderRadius: BorderRadius.only(
                                  topLeft: const Radius.circular(20.0),
                                  bottomLeft: const Radius.circular(20.0)),
                            ),
                          ),
                          Container(
                            height: 74.0,
                            decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.only(
                                  topRight: const Radius.circular(20.0),
                                  bottomRight: const Radius.circular(20.0)),
                            ),
                            width: 265.0,
                            child: Center(
                                child: Text(
                              data[i],
                              style:
                                  TextStyle(fontSize: 24.0, color: maincolor),
                            )),
                          )
                        ],
                      ),
                    );
                  ,
                ),
              ),

我已经解析了 JSON,但是当我尝试将它用作这样的对象时:

文本(问题[i].body.systemTopics.topicid)

它不让我。但是,如果我这样做: questions[i].body.systemTopics 那么它不会抛出错误

【问题讨论】:

你是如何解析 json 的?我认为你需要解析到类。 如果您可以在 dartpad 中设置最小可重现代码,我们可以帮助您修复它。 【参考方案1】:

编辑:更新了答案以利用提供的序列化程序 OP 并利用有状态小部件。

请注意,以下代码中的数据是不变的,但您已经对其进行了调整以处理异步 http 请求,因为我想在 dartpad here 中显示答案。

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

final Color darkBlue = Color.fromARGB(255, 18, 32, 47);

void main() 
  runApp(MainWidget());


class MainWidget extends StatelessWidget 
  @override
  Widget build(context) 
    return MaterialApp(home: Scaffold(body: Questions()));
  


class Questions extends StatefulWidget 
  @override
  _QuestionsPageState createState() => _QuestionsPageState();


class _QuestionsPageState extends State<Questions> 
  QuestionModel data;
  var users;

  String url =
      'https://90d53c1e-1ca3-4d5e-982e-0ff81a3ba7f5.mock.pstmn.io/profile/questions';

  requestQuestionsAPI() 
//   final response = await http.get(Uri.encodeFull(url), headers: "Accept": "application/json");

    setState(() 
      //data = json.decode(response.body);

      // Isntead of http fecth a constant data
      data = questionModelFromJson('''
  "body": 
    "System Topics": [
      "Topic ID": "2", "Title": "Tres", "Description": "Dos",
      "Topic ID": "3", "Title": "Pls Work", "Description": "nfewtrwe",
      "Topic ID": "4", "Title": "Juice", "Description": "Bar"
    ],
    "Video Requests": [
      
        "Topic ID": "1",
        "From Name": "New User",
        "From Email": "dawdw@gmail.com",
        "Title": "What's you first christmas like?",
        "Description": "Please tell me about your Christmas?"
      ,
      
        "Topic ID": "4",
        "From Name": "New User",
        "From Email": "dawdw@gmail.com",
        "Title": "What is your name?",
        "Description": ""
      ,
      
        "Topic ID": "5",
        "From Name": "New User",
        "From Email": "dawdw@gmail.com",
        "Title": "What is your name?",
        "Description": ""
      ,
      
        "Topic ID": "6",
        "From Name": "New User",
        "From Email": "dawdw@gmail.com",
        "Title": "What is your name?",
        "Description": ""
      ,
      
        "Topic ID": "7",
        "From Name": "New User",
        "From Email": "dawdw@gmail.com",
        "Title": "What is your name?",
        "Description": ""
      ,
      
        "Topic ID": "8",
        "From Name": "New User",
        "From Email": "dawdw@gmail.com",
        "Title": "What is your name?",
        "Description": ""
      ,
      
        "Topic ID": "9",
        "From Name": "New User",
        "From Email": "dawdw@gmail.com",
        "Title": "What is your name?",
        "Description": "From james"
      ,
      
        "Topic ID": "10",
        "From Name": "New User",
        "From Email": "dawdw@gmail.com",
        "Title": "What is your name?",
        "Description": "From james"
      
    ]
  
''');
    );
  

  _questions() 
    requestQuestionsAPI();
  

  void initState() 
    super.initState();
    _questions();
  

  dispose() 
    super.dispose();
  

  @override
  Widget build(BuildContext context) 
    return MyNewWidget(questionModel: data);
  


class MyNewWidget extends StatefulWidget 
  final QuestionModel questionModel;
  MyNewWidget(this.questionModel);
  @override
  _MyNewWidgetState createState() => _MyNewWidgetState();


class _MyNewWidgetState extends State<MyNewWidget> 
  @override
  Widget build(BuildContext context) 
    print(widget.questionModel);
    return MyList(
      bodyElement: widget.questionModel.body,
    );
  


class MyList extends StatelessWidget 
  final Body bodyElement;
  MyList(this.bodyElement);
  @override
  Widget build(BuildContext context) 
    return Column(children: [
      Text(
        'Sytem Topics',
        style: TextStyle(
            fontWeight: FontWeight.bold,
            fontSize: 25,
            fontStyle: FontStyle.italic),
      ),
      Divider(),
      Expanded(
        child: ListView.builder(
            shrinkWrap: true,
            itemCount: bodyElement.systemTopics.length,
            itemBuilder: (context, index) 
              return MyListElement(
                id: bodyElement.systemTopics[index].topicId,
                description: bodyElement.systemTopics[index].description,
              );
            ),
      ),
      Text(
        'Video Requests',
        style: TextStyle(
            fontWeight: FontWeight.bold,
            fontSize: 25,
            fontStyle: FontStyle.italic),
      ),
      Divider(),
      Expanded(
        child: ListView.builder(
            shrinkWrap: true,
            itemCount: bodyElement.videoRequests.length,
            itemBuilder: (context, index) 
              return MyListElement(
                id: bodyElement.videoRequests[index].topicId,
                description: bodyElement.videoRequests[index].description,
              );
            ),
      )
    ]);
  


class MyListElement extends StatelessWidget 
  final String id;
  final String description;

  MyListElement(this.id, this.description);

  @override
  Widget build(BuildContext context) 
    print('id is $id');
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(20.0),
      ),
      height: 74.0,
      margin: const EdgeInsets.only(bottom: 10.0),
      child: Row(
        children: <Widget>[
          Container(
            alignment: Alignment.center,
            child: Text(id),
            height: 74.0,
            width: 73.0,
            decoration: BoxDecoration(
              color: Colors.orange,
              borderRadius: BorderRadius.only(
                  topLeft: const Radius.circular(20.0),
                  bottomLeft: const Radius.circular(20.0)),
            ),
          ),
          Container(
            height: 74.0,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.only(
                  topRight: const Radius.circular(20.0),
                  bottomRight: const Radius.circular(20.0)),
            ),
            width: 265.0,
            child: Center(
                child: Text(
              description,
              style: TextStyle(fontSize: 24.0, color: Colors.red),
            )),
          )
        ],
      ),
    );
  


/// Serializers

QuestionModel questionModelFromJson(String str) =>
    QuestionModel.fromJson(json.decode(str));

String questionModelToJson(QuestionModel data) => json.encode(data.toJson());

class QuestionModel 
  Body body;

  QuestionModel(
    this.body,
  );

  factory QuestionModel.fromJson(Map<String, dynamic> json) => QuestionModel(
        body: Body.fromJson(json["body"]),
      );

  Map<String, dynamic> toJson() => 
        "body": body.toJson(),
      ;


class Body 
  List<SystemTopic> systemTopics;
  List<VideoRequest> videoRequests;

  Body(
    this.systemTopics,
    this.videoRequests,
  );

  factory Body.fromJson(Map<String, dynamic> json) => Body(
        systemTopics: List<SystemTopic>.from(
            json["System Topics"].map((x) => SystemTopic.fromJson(x))),
        videoRequests: List<VideoRequest>.from(
            json["Video Requests"].map((x) => VideoRequest.fromJson(x))),
      );

  Map<String, dynamic> toJson() => 
        "System Topics":
            List<dynamic>.from(systemTopics.map((x) => x.toJson())),
        "Video Requests":
            List<dynamic>.from(videoRequests.map((x) => x.toJson())),
      ;


class SystemTopic 
  String topicId;
  String title;
  String description;

  SystemTopic(
    this.topicId,
    this.title,
    this.description,
  );

  factory SystemTopic.fromJson(Map<String, dynamic> json) => SystemTopic(
        topicId: json["Topic ID"],
        title: json["Title"],
        description: json["Description"],
      );

  Map<String, dynamic> toJson() => 
        "Topic ID": topicId,
        "Title": title,
        "Description": description,
      ;


class VideoRequest 
  String topicId;
  String fromName;
  String fromEmail;
  String title;
  String description;

  VideoRequest(
    this.topicId,
    this.fromName,
    this.fromEmail,
    this.title,
    this.description,
  );

  factory VideoRequest.fromJson(Map<String, dynamic> json) => VideoRequest(
        topicId: json["Topic ID"],
        fromName: json["From Name"],
        fromEmail: json["From Email"],
        title: json["Title"],
        description: json["Description"],
      );

  Map<String, dynamic> toJson() => 
        "Topic ID": topicId,
        "From Name": fromName,
        "From Email": fromEmail,
        "Title": title,
        "Description": description,
      ;


对应的输出如下图。

【讨论】:

感谢您的回答,但这对 StatefulWidgets 有何作用?我需要它们,因为 json 数据是从 api 检索的 如果您需要,您必须为传入的 json 编写一个 json 序列化程序。如果您的 api 具有更复杂的结构以及像 this 这样的代码生成器,有很多关于如何进行简单 json 序列化的很好的资源。当前的方法将适用于 StatefulWidget。 所以你已经写好了序列化器。您本可以早点发布它会有所帮助。 :) 无论如何,为了访问有状态小部件的实例变量,您需要像 widget.datawidget.myvariable 等那样使用它。我会看看是否可以为有状态小部件提供相同的解决方案,但这次使用您的序列化程序. 上面显示的 ui 结果是你所期望的还是别的什么? 我希望这会有所帮助。如果这不能解决您的问题,那么我建议您编辑问题以关注您真正需要的内容。

以上是关于如何将地图列表中的项目显示到列表视图中的主要内容,如果未能解决你的问题,请参考以下文章

Android Studio:如何将列表视图中的项目添加到列表视图 onClick

如何在保留 onClickListener 的同时将菜单按钮添加到列表视图?

如何选择/突出显示列表视图中的项目而不触摸它?

在列表视图中滚动地图时如何避免滚动列表视图

如何将列表视图中的数据从一个片段发送到另一个片段

如何使列表视图中的项目可点击?