【问题标题】:Flutter ListTile title name from json来自 json 的 Flutter ListTile 标题名称
【发布时间】:2021-05-13 20:41:10
【问题描述】:

我正在尝试将一个人的两个名字都显示为 listtile flutter 中的标题。这是示例 json 文件

var users = const [
    {
       "first_name": "melissa",
       "last_name": "fleming",
       "phone_number": "0740-304-475"
    },
    {
      "first_name": "christoffer",
      "last_name": "christiansen",
      "phone_number": "05761325"
    },
    {
      "first_name": "valtteri",
      "last_name": "pulkkinen",
      "phone_number": "041-829-79-61"
    }
]

这是颤振代码

 @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text(
          "List of Customers",
      ),
      
      body: ListView.separated(
        itemCount: users.length,
        separatorBuilder: (context, index) => Divider(),
        itemBuilder: (BuildContext context, int index) {
          var user = users[index];
          return ListTile(
            title: Text(user['first_name']),
            isThreeLine: true,
          );
        },
      ),
    );
  }

如何将这两个名称都传递给这部分

title: Text(user['first_name']),

【问题讨论】:

  • user['first_name'] 得到什么?

标签: android json flutter


【解决方案1】:

您可以在循环中使用 for 并将值存储在字符串中

for(var i in users){
String name = i['first_name'] + " "+ i['last_name'];
print(name);}



ListView.separated(
    itemCount: users.length,
    separatorBuilder: (context, index) => Divider(),
    itemBuilder: (BuildContext context, int index) {
      var user = users[index];
      return ListTile(
        title: Text(name),
        isThreeLine: true,
      );
    },
  ),

【讨论】:

    【解决方案2】:

    有两种方法可以做到。

    第一种方法:如果你想显示全名作为标题:

    title : Text("$users[0]['first_name'] $users[0]['last_name']")
    

    第二种方法:如果您想分别显示名字和姓氏,请使用副标题:

    ListTile(
      leading: const Icon(Icons.flight_land),
      title: const Text($users[0]['first_name']),
      subtitle: Text($users[0]['last_name']),
      onTap: () { /* react to the tile being tapped */ }
    )
    

    【讨论】:

    • 第一种方法打印整个json文件
    • 如果您只想按索引获取特定数据,则需要使用索引。我已经编辑了我的答案,
    猜你喜欢
    • 1970-01-01
    • 2018-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-25
    • 2018-10-05
    • 2017-11-17
    相关资源
    最近更新 更多