Home > Net >  Parsing Json data in flutter
Parsing Json data in flutter

Time:12-07

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.

CodePudding user response:

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;
  }
}

CodePudding user response:

Try this In Listview.buider use Different Listview.builder for benefits,main features and multiDeviceSupport. Give them NeverScrollablePhysics and shrink wrap true.

  • Related