Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 516
Jorden Avatar asked Nov 01 '25 03:11

Jorden


1 Answers

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

like image 159
Crazy Lazy Cat Avatar answered Nov 02 '25 17:11

Crazy Lazy Cat