0

I have data in json format where one field subtitle has list of data again. How can I iterate through this list which already inside a list. here is the code.

#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"]),
          );
        },
      ),
    );
  }
}

I want to list the items in subtitle. How can I do it?

3
  • 1
    try this: data[index]["subtitle"][subtitleIndex] subtitleIndex is an int from 0 to 3 in your case. Commented Jun 22, 2020 at 7:16
  • I tried this. The problem is how can I put the subtitle index in loop. Shall I use nested loops? Commented Jun 22, 2020 at 7:20
  • 1
    Yes you can use a nested loop for this Commented Jun 22, 2020 at 7:30

1 Answer 1

1

You can do something like this with a column for example:

Column(children: [
    for ( var subtitle in data[index]['subtitle'] ) Text(subtitle)
  ],
),
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.