skip to Main Content

I am using a api endpoint where I am getting following type of List in:

`[
[

    { "productName": "Chicken Biryani Half" },
    { "productName": " Chicken Momos" }

 ],

 [
    { "productName": "Chicken Biryani Half" },
    { "productName": "Chicken Biryani Half" },
    { "productName": " Chicken Momos" }

 ]]`

How do I implement this with Listview.builder

2

Answers


  1. Try this!

    OUTPUT:

    enter image description here

    CODE:

    class MyListViewBuilder extends StatelessWidget {
      final List<List<Map<String, String>>> data = [
        [
          {"productName": "Chicken Biryani Half"},
          {"productName": "Chicken Momos"}
        ],
        [
          {"productName": "Chicken Biryani Half"},
          {"productName": "Chicken Biryani Half"},
          {"productName": "Chicken Momos"}
        ]
      ];
    
      MyListViewBuilder({super.key});
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
             title: Text("Example"),
          ),
          body: ListView.builder(
            itemCount: data.length,
            itemBuilder: (BuildContext context, int index) {
              return Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(
                    padding:
                        const EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0),
                    child: Text(
                      'Group ${index + 1}',
                      style: const TextStyle(
                          fontSize: 18, fontWeight: FontWeight.bold),
                    ),
                  ),
                  ListView.builder(
                    shrinkWrap: true,
                    physics: const NeverScrollableScrollPhysics(),
                    itemCount: data[index].length,
                    itemBuilder: (BuildContext context, int subIndex) {
                      final product = data[index][subIndex];
                      return ListTile(
                        title: Text(product["productName"]!),
                      );
                    },
                  ),
                ],
              );
            },
          ),
        );
      }
    }
    
    Login or Signup to reply.
  2. In this cause you should make model class for manage our API response data, and you should keep your mind we cannot access dynamic data with listView builder we want use Future builder with random data like API call,

    1.First we should make our model class like bellow,

    class Product {
      final String productName;
    
      Product({required this.productName});
    
      factory Product.fromJson(Map<String, dynamic> json) {
        return Product(
          productName: json['productName'],
        );
      }
    }
    

    2.Look at bellow API data fetch part,

     Future<List<Product>> fetchProducts() async {
        final response = await http.get(Uri.parse('YOUR_API_ENDPOINT'));
    
        if (response.statusCode == 200) {
          // If the server returns a 200 OK response, parse the JSON
          List<dynamic> responseData = json.decode(response.body);
          List<Product> productList = [];
          for (dynamic data in responseData) {
            productList.add(Product.fromJson(data));
          }
          return productList;
        } else {
          // If the server did not return a 200 OK response,
          // throw an exception.
          throw Exception('Failed to load products');
        }
      }
    

    you should learn asynchronous programming know about async and wait keywords, read flutter documentation get more details you can read it using this

    3.Now we can pass our data into list, like bellow.

      @override
      Widget build(BuildContext context) {
        return FutureBuilder<List<Product>>(
          future: fetchProducts(),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return Center(child: CircularProgressIndicator());
            } else if (snapshot.hasError) {
              return Center(child: Text('Error: ${snapshot.error}'));
            } else {
              return ListView.builder(
                itemCount: snapshot.data!.length,
                itemBuilder: (BuildContext context, int index) {
                  return ListTile(
                    title: Text(snapshot.data![index].productName),
                  );
                },
              );
            }
          },
        );
      }
    
    • fetchProducts() makes an HTTP GET request to your API endpoint.
      Replace 'YOUR_API_ENDPOINT' with the actual URL of your API
      endpoint.

    • If the request is successful (status code 200), it parses the JSON
      response and creates a list of Product objects.
      If an error occurs during the request or parsing, it throws an exception which is caught by the FutureBuilder and displayed as an
      error message.

    in this implementation will be help fix your issue, and I attach new link for learn fetch data from internet, use this link for read it.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search