Jorden
Jorden

Reputation: 768

How Can I access JSON Object using flutter?

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?

Upvotes: 4

Views: 11041

Answers (3)

Crazy Lazy Cat
Crazy Lazy Cat

Reputation: 15063

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

Upvotes: 7

flutter
flutter

Reputation: 6776

I'd have 2 model classes:

class EmployeeList {
  final List<Employee> employees;

  EmplyeeList({
    this.employees,
});

  factory EmployeeList.fromJson(List<dynamic> parsedJson) {

    List<Employee> employees = new List<Employee>();
    employees = parsedJson.map((i)=>Employee.fromJson(i)).toList();

    return new EmployeeList(
      employees: employees
    );
  }
}

class Employee{
  final String id;
  final String title;
  final String body;
  final String userId;


  Employee({
  String userId;
  String id;
  String title;
  String body;

}) ;

  factory Employee.fromJson(Map<String, dynamic> json){
    return new Employee(
      id: json['id'],
      userId:[userId]
      title: json['title'],
      body: json['body'],
    );
  }

}

maybe think about using a FutureBuilder as well...from the flutter docs: FutureBuilder

Upvotes: 0

Manish
Manish

Reputation: 5213

You never initialized the model from json so all of the properties of model are null. Try something like this:

    if (response.statusCode == 200) {
      final employees = json.decode(response.body);
      list = (employees as List)
          .map((data) => new EmployeeModel.fromJson(data))
          .toList();
      setState(() {
        model = new EmployeeModel.fromJson(employees[0]);
        isLoading = false;
      });
    }

Upvotes: 1

Related Questions