0

Hi I have a json corresponding to that I need to fetch data but no data is being shown on the screen don't know why most probably Implementation is wrong

class TestScreen extends StatefulWidget {
  const TestScreen({Key? key}) : super(key: key);

  @override
  State<TestScreen> createState() => _TestScreenState();
}

class _TestScreenState extends State<TestScreen> {
  List<AppDetails> details = [];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        backgroundColor: kBackgroundColor,
        title: Text(
          'Home',
          style: Theme.of(context).textTheme.headline2,
        ),
      ),
      body: Expanded(
        child: ListView.builder(
            itemCount: details.length,
            itemBuilder: (context, index) {
              final detail = details[index];
              return buildProduct(detail);
            }),
      ),
    );
  }
}

Widget buildProduct(AppDetails detail) => Column(
      children: [Center(child: Text('${detail.benefits}'))],
    );

Above is My Implementation

{
    "name": "TestingApp",
    "category": "Production",
    "subcategory": "Productivity",
    "imageUrl": "Testing-Banner.jpg",
    "logo": "PI.png",
    "description": "Testing is an application for easy & effective Inspection",
    "appDetails": [{
        "systemOverview": "https:url.com",
        "multiDeviceSupport": [{
                "label": "Multi-Device"
            },
            {
                "label": "Multi-Lingual"
            },
            {
                "label": "Multi-Database"
            }
        ],
        "mainFeatures": [{
                "label": "Testing"
            },
            {
                "label": "Ease"
            },
            {
                "label": "Select failure "
            },
            {
                "label": "Add comments & take evidence Pictures"
            },
            {
                "label": "Send  results to central system"
            },
            {
                "label": "Search/view "
            }
        ],
        "benefits": [{
                "label": "Easy & quick solution "
            },
            {
                "label": "Go paperless "
            },
            {
                "label": "Lower costs"
            },
            {
                "label": "Improve quality/safety"
            },
            {
                "label": "Configurable on hand-held devices and tablets"
            },
            {
                "label": "Electronic notifications to corresponding personnel’s"
            }

        ]
    }]
}

Following is a json sample

I need to show all the benefits similarly all the multidevice support Or can say all the app details but in different kind of a container. any help would be great.

4
  • Where did you assign the data to details Commented Dec 7, 2022 at 5:31
  • javiercbk.github.io/json_to_dart Using this created a model class Commented Dec 7, 2022 at 5:35
  • could you add the part you fetch the data from api? @talalhabib Commented Dec 7, 2022 at 7:05
  • class ItemsApi { static Future<List<ProductModel>> getProducts() async { final response = await http.get(Uri.parse(mainUrl)); final body = json.decode(response.body); return body.map<ProductModel>(ProductModel.fromJson).toList(); } } Commented Dec 7, 2022 at 9:15

1 Answer 1

1

is this what you want?

enter image description here

try this code or try on dartpad

import 'package:flutter/material.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(const MaterialApp(home: TestScreen()));
}

class TestScreen extends StatefulWidget {
  const TestScreen({Key? key}) : super(key: key);

  @override
  State<TestScreen> createState() => _TestScreenState();
}

class _TestScreenState extends State<TestScreen> {
  List<AppDetails>? details = [];
  final Map<String, dynamic> json = {
    "name": "TestingApp",
    "category": "Production",
    "subcategory": "Productivity",
    "imageUrl": "Testing-Banner.jpg",
    "logo": "PI.png",
    "description": "Testing is an application for easy & effective Inspection",
    "appDetails": [
      {
        "systemOverview": "https:url.com",
        "multiDeviceSupport": [
          {"label": "Multi-Device"},
          {"label": "Multi-Lingual"},
          {"label": "Multi-Database"}
        ],
        "mainFeatures": [
          {"label": "Testing"},
          {"label": "Ease"},
          {"label": "Select failure "},
          {"label": "Add comments & take evidence Pictures"},
          {"label": "Send  results to central system"},
          {"label": "Search/view "}
        ],
        "benefits": [
          {"label": "Easy & quick solution "},
          {"label": "Go paperless "},
          {"label": "Lower costs"},
          {"label": "Improve quality/safety"},
          {"label": "Configurable on hand-held devices and tablets"},
          {"label": "Electronic notifications to corresponding personnel’s"}
        ]
      }
    ]
  };

  @override
  void initState() {
    super.initState();
    final data = AppDetailModel.fromJson(json);
    details = data.appDetails;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        backgroundColor: Colors.blue,
        title: const Text('Home'),
      ),
      body: SizedBox(
        child: ListView.builder(
          itemCount: details?.length,
          itemBuilder: (context, index) {
            final detail = details?[index];
            return buildProduct(detail);
          },
        ),
      ),
    );
  }
}

Widget buildProduct(AppDetails? detail) => Padding(
      padding: const EdgeInsets.all(8.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: (detail?.benefits ?? []).map((e) {
          final index = (detail?.benefits ?? []).indexOf(e);
          return Row(
            children: [
              SizedBox(width: 20, child: Text('${index + 1}.')),
              Text('${e.label}'),
            ],
          );
        }).toList(),
      ),
    );

class AppDetailModel {
  String? name;
  String? category;
  String? subcategory;
  String? imageUrl;
  String? logo;
  String? description;
  List<AppDetails>? appDetails;

  AppDetailModel(
      {this.name,
      this.category,
      this.subcategory,
      this.imageUrl,
      this.logo,
      this.description,
      this.appDetails});

  AppDetailModel.fromJson(Map<String, dynamic> json) {
    name = json['name'];
    category = json['category'];
    subcategory = json['subcategory'];
    imageUrl = json['imageUrl'];
    logo = json['logo'];
    description = json['description'];
    if (json['appDetails'] != null) {
      appDetails = <AppDetails>[];
      json['appDetails'].forEach((v) {
        appDetails!.add(AppDetails.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['name'] = name;
    data['category'] = category;
    data['subcategory'] = subcategory;
    data['imageUrl'] = imageUrl;
    data['logo'] = logo;
    data['description'] = description;
    if (appDetails != null) {
      data['appDetails'] = appDetails!.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class AppDetails {
  String? systemOverview;
  List<Label>? multiDeviceSupport;
  List<Label>? mainFeatures;
  List<Label>? benefits;

  AppDetails(
      {this.systemOverview,
      this.multiDeviceSupport,
      this.mainFeatures,
      this.benefits});

  AppDetails.fromJson(Map<String, dynamic> json) {
    systemOverview = json['systemOverview'];
    if (json['multiDeviceSupport'] != null) {
      multiDeviceSupport = <Label>[];
      json['multiDeviceSupport'].forEach((v) {
        multiDeviceSupport!.add(Label.fromJson(v));
      });
    }
    if (json['mainFeatures'] != null) {
      mainFeatures = <Label>[];
      json['mainFeatures'].forEach((v) {
        mainFeatures!.add(Label.fromJson(v));
      });
    }
    if (json['benefits'] != null) {
      benefits = <Label>[];
      json['benefits'].forEach((v) {
        benefits!.add(Label.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['systemOverview'] = systemOverview;
    if (multiDeviceSupport != null) {
      data['multiDeviceSupport'] =
          multiDeviceSupport!.map((v) => v.toJson()).toList();
    }
    if (mainFeatures != null) {
      data['mainFeatures'] = mainFeatures!.map((v) => v.toJson()).toList();
    }
    if (benefits != null) {
      data['benefits'] = benefits!.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class Label {
  String? label;

  Label({this.label});

  Label.fromJson(Map<String, dynamic> json) {
    label = json['label'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['label'] = label;
    return data;
  }
}

Sign up to request clarification or add additional context in comments.

6 Comments

Yes this is exactly I wanted can you please modify it a little bit as I am getting following data from internet so don't think final Map<String, dynamic> json = {} will be used here
secondly will you explain a bit that is it possible to use a single list to get all the other elements including App details or have to create a list other than this
you can generate the model using this url javiercbk.github.io/json_to_dart and replace my code. if this answer help to solve your problem, please upvote and make it as acceptance answer.
thirdly I have to create a new widget to access multi device support ?
Following is something I was trying to do first class ItemsApi { static Future<List<ProductModel>> getProducts() async { final response = await http.get(Uri.parse(mainUrl)); final body = json.decode(response.body); return body.map<ProductModel>(ProductModel.fromJson).toList(); } }
|

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.