【问题标题】:How to read a list from json object in flutter?如何在颤动中从 json 对象中读取列表?
【发布时间】:2020-10-11 23:53:09
【问题描述】:

我有 json 格式的数据,其中一个字段 subtitle 再次具有数据列表。如何遍历已经在列表中的列表。这是代码。

#Data.json

[
    {
        "id":0,
        "title":"Heading",
        "subtitle":[
            "sub1",
            "sub2",
            "sub3"
        ]
    },
    {
        "id":1,
        "title":"Heading1",
        "subtitle":[
            "sub4",
            "sub5",
            "sub6"
        ]
    },
    {
        "id":2,
        "title":"Heading2",
        "subtitle":[
            "sub7",
            "sub8",
            "sub9"
        ]
    }
]

#list.dart

import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:flutter/services.dart' show rootBundle;

void main() {
  runApp(new MaterialApp(
    home: new HomePage()
  ));
}

class HomePage extends StatefulWidget {
  @override
  HomePageState createState() => new HomePageState();
}

class Location {
  final String id;
  final double lat;
  final double long;

  Location({this.id, this.lat, this.long});
}

class HomePageState extends State<HomePage> {

  List data;
  Future _future;
  List<Location> locations;

  Future<String> getData() async {
    var response = await rootBundle.loadString('asset/sample.json');
  
    this.setState(() {
      data = jsonDecode(response);
    });
    
    for(var i=0; i< data.length; i++){
      print( data[i]["subtitle"]);
    }
    
    
    return "Success!";
  }

  @override
  void initState(){
    this.getData();
  }

  @override
  Widget build(BuildContext context){
    return new Scaffold(
      appBar: new AppBar(title: new Text("Listviews"), backgroundColor: Colors.blue),
      body: new ListView.builder(
        itemCount: data == null ? 0 : data.length,
        itemBuilder: (BuildContext context, int index){
          return new Card(
            child: new Text(data[index]["title"]),
          );
        },
      ),
    );
  }
}

我想列出subtitle 中的项目。我该怎么做?

【问题讨论】:

  • 试试这个:data[index]["subtitle"][subtitleIndex] subtitleIndex 在你的情况下是一个从 0 到 3 的整数。
  • 我试过这个。问题是如何将字幕索引放入循环中。我应该使用嵌套循环吗?
  • 是的,您可以为此使用嵌套循环

标签: json flutter flutter-layout


【解决方案1】:

例如,您可以对列执行类似操作:

Column(children: [
    for ( var subtitle in data[index]['subtitle'] ) Text(subtitle)
  ],
),

【讨论】:

    猜你喜欢
    • 2020-09-26
    • 2020-11-26
    • 2021-09-24
    • 1970-01-01
    • 2020-02-29
    • 1970-01-01
    • 2018-12-05
    • 2020-11-28
    • 1970-01-01
    相关资源
    最近更新 更多