Dheepak S
Dheepak S

Reputation: 217

How to add list view builder inside another list view builder?

This is my list view widget. There are two list view builders, one inside another. I added shrinkWrap property and physics property. Nothing is rendered.I have another doubt when to use list view, single child scroll view and custom scroll view.


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

            return Container(
              child: ListView.builder(
                shrinkWrap: true,
                itemCount: innerData == null ? 0 : innerData.length,
                itemBuilder: (BuildContext context, int index) {
                  String title = innerData[index]["title"];

                  return Text("$title");
                },
              ),
            );
          }
        },
      ),
    );
  }

This is the output screen

This is my json response:

[
    {
        "type": "single",
        "data": [
            {
                "title": "Fresh Vegetables"
            },
            {
                "title": "Fresh Fruits"
            },
            {
                "title": "Cuts and Sprouts"
            },
            {
                "title": "Exotic Center"
            }
        ]
    }
]

I want to do like the flipkart home page. I want to build widgets based on the response. What is the widgets should I use?

Upvotes: 0

Views: 2130

Answers (2)

Sagar Acharya
Sagar Acharya

Reputation: 3767

I some how copy pasted your code and made some modifications and it worked for me just check the code i have modified :

I have loaded your json locally mentioned below:

[
    {
        "type": "single",
        "data": [
            {
                "title": "Fresh Vegetables"
            },
            {
                "title": "Fresh Fruits"
            },
            {
                "title": "Cuts and Sprouts"
            },
            {
                "title": "Exotic Center"
            }
        ]
    }
]

According to you json class i have created a model class where you can access the specific object from the listview using this model class :

// To parse this JSON data, do
//
//     final data = dataFromJson(jsonString);

import 'dart:convert';

List<Data> dataFromJson(String str) => List<Data>.from(json.decode(str).map((x) => Data.fromJson(x)));

String dataToJson(List<Data> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Data {
    String type;
    List<Datum> data;

    Data({
        this.type,
        this.data,
    });

    factory Data.fromJson(Map<String, dynamic> json) => Data(
        type: json["type"],
        data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
    );

    Map<String, dynamic> toJson() => {
        "type": type,
        "data": List<dynamic>.from(data.map((x) => x.toJson())),
    };
}

class Datum {
    String title;

    Datum({
        this.title,
    });

    factory Datum.fromJson(Map<String, dynamic> json) => Datum(
        title: json["title"],
    );

    Map<String, dynamic> toJson() => {
        "title": title,
    };
}


And just check the main file where i have made the changes :

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:sample_testing_project/models.dart';

main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  List<Data> data = List();
  bool _isLoading = false;


  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    loadYourData();
  }

  Future<String> loadFromAssets() async {
    return await rootBundle.loadString('json/parse.json');
  }

  loadYourData() async {
    setState(() {
      _isLoading = true;
    });
    // Loading your json locally you can make an api call, when you get the response just pass it to the productListFromJson method
    String jsonString = await loadFromAssets();
    final datamodel = dataFromJson(jsonString);
    data = datamodel;

    setState(() {
      _isLoading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: new Scaffold(
        appBar: AppBar(
          title: Text("Listviews"),
          backgroundColor: Colors.blue,
        ),
        body: ListView.builder(
          shrinkWrap: true,
          itemCount: data == null ? 0 : data.length,
          itemBuilder: (BuildContext context, int index) {
            if (data[index].type == "single") {
              var innerData = data[index].data;

              return Container(
                child: ListView.builder(
                  shrinkWrap: true,
                  itemCount: innerData == null ? 0 : innerData.length,
                  itemBuilder: (BuildContext context, int index) {
                    String title = innerData[index].title;

                    return Container(
                      width: MediaQuery.of(context).size.width,
                      child: Card(
                        child: Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: Text("$title"),
                        ),
                      ),
                    );
                  },
                ),
              );
            }
          },
        ),
      ),
    );
  }
}

Upvotes: 0

Navin Kumar
Navin Kumar

Reputation: 4027

Use physics property inside listViewBuilder

    shrinkWrap: true,
    physics: ClampingScrollPhysics(), /// listView scrolls

Upvotes: 1

Related Questions