How Can I access JSON Object using flutter?

Jorden

How Can I access my JSON Objects?

Getting Employee Title = null How can I directly use the object?

Like this Getting proper output Text('Employee Title = ${list[0].title}') or any other way directly using model object ?

What is the correct way?

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:flutter/cupertino.dart';


class EmployeeModel {
  int userId;
  int id;
  String title;
  String body;

  EmployeeModel({this.userId, this.id, this.title, this.body});

  EmployeeModel.fromJson(Map<String, dynamic> json) {
    userId = json['userId'];
    id = json['id'];
    title = json['title'];
    body = json['body'];
  }
}
class EmployeePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return EmployeePageState();
  }
}

class EmployeePageState extends State<EmployeePage> {
  EmployeeModel model = EmployeeModel();
  List<EmployeeModel> list = List();
  var isLoading = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Employee Title = ${model.title}'),
        ),
        body: isLoading
            ? Center(
          child: CircularProgressIndicator(),
        ):Center(
            child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[

                ])));
  }


  @override
  void initState() {
    super.initState();
    getEmployee(2);
  }

  getEmployee(int id) async {
    setState(() {
      isLoading = true;
    });
    final response =
        await http.get("https://jsonplaceholder.typicode.com/posts?userId=$id");
    if (response.statusCode == 200) {
      list = (json.decode(response.body) as List)
          .map((data) => new EmployeeModel.fromJson(data))
          .toList();
      setState(() {
        isLoading = false;
      });
    }
  }
}

My Code is working fine but I want to know is this right way? This way
Text('Employee Title = ${list[0].title}') or if I want to directly use object what is the way?

My Code is working fine but I want to know is this right way? This way
Text('Employee Title = ${list[0].title}') or if I want to directly use object what is the way?

Crazy Lazy Cat

Try this,

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: EmployeePage(),
    );
  }
}

class EmployeePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => EmployeePageState();
}

class EmployeePageState extends State<EmployeePage> {
  Future<List<EmployeeModel>> _employeeList;

  @override
  void initState() {
    _employeeList = _getEmployee(2);
    super.initState();
  }

  Future<List<EmployeeModel>> _getEmployee(int id) async {
    final response = await http.get(
      "https://jsonplaceholder.typicode.com/posts?userId=$id",
    );
    if (response.statusCode == 200) {
      final jsonBody = json.decode(response.body) as List;
      return jsonBody.map((data) => new EmployeeModel.fromJson(data)).toList();
    } else
      throw Exception("Unable to get Employee list");
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<List<EmployeeModel>>(
      future: _employeeList,
      builder: (context, snapshot) {
        print(snapshot);
        if (snapshot.hasData)
          return _buildBody(snapshot.data);
        else if (snapshot.hasError)
          return _buildErrorPage(snapshot.error);
        else
          return _buildLoadingPage();
      },
    );
  }

  Widget _buildBody(List<EmployeeModel> employeeList) => Scaffold(
        appBar: AppBar(
          title: Text('Employee Title = ${employeeList[0].title}'),
        ),
        body: ListView.builder(
          itemCount: employeeList.length,
          itemBuilder: (context, index) {
            return ListTile(
              title: Text(employeeList[index].title),
            );
          },
        ),
      );

  Widget _buildErrorPage(error) => Material(
        child: Center(
          child: Text("ERROR: $error"),
        ),
      );

  Widget _buildLoadingPage() => Material(
        child: Center(
          child: CircularProgressIndicator(),
        ),
      );
}

class EmployeeModel {
  int userId;
  int id;
  String title;
  String body;

  EmployeeModel({this.userId, this.id, this.title, this.body});

  EmployeeModel.fromJson(Map<String, dynamic> json) {
    userId = json['userId'];
    id = json['id'];
    title = json['title'];
    body = json['body'];
  }
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How can I build this JSON object in Flutter?

How can I access my JSON object?

How can I access this json response object?

How can I access these json object in python

How can I access an object in a complex JSON file as follows?

How can i query the access object from JSON in CouchDB

How can I access JSON elements in PHP like array object?

How can I get access to multiple values of nested JSON object?

How can I access to each field of a json object?

how can I have access to property class in the Json object?

How can I legally access object with wrong alignment using pointer?

how to access properties of json object flutter

how can i access json data using for loop in vue js

using Javascript how can I access elements form a json array?

How can I access Json information in php using array indexing

How can I access multipage API with Flutter?

How can I access this JSON response that I am getting from an HTTP POST request in Flutter?

How can I print out multiple object in JSON using python?

How can I pull the object from the json using a key?

How can I include raw JSON in an object using Jackson?

How can I pass through a JSON object using an intermediate API?

How I can persist a json object using hibernate?

How can I cast JSON to a complex object using Typescript and Angular

How can I update a MongoDB collection using a JS/JSON object?

How can I get a JSON file into an object and display it using AngularJS?

How can I export a JSON object to Excel using Nextjs/React?

how can i display object data in flutter?

How can I access JSON property of nested object inside object array

How can I access an object of type A that's within an object of type B using pipes and mapping?

TOP Ranking

HotTag

Archive