Mikel Tawfik
Mikel Tawfik

Reputation: 746

can't fetch data api url json flutter

i try to fetch api json id , username , photo ..etc... and when use jsonplaceholder it's working fine and when use mine don't get any data

flutter code

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

class ListViewJsonapi extends StatefulWidget {
  _ListViewJsonapiState createState() => _ListViewJsonapiState();
}

class _ListViewJsonapiState extends State<ListViewJsonapi> {
  final String uri = 'https://www.christian-dogma.com/android-index.php';

  Future<List<Users>> _fetchUsers() async {
    var response = await http.get(uri);
    if (response.statusCode == 200) {
      final items = json
          .decode(utf8.decode(response.bodyBytes))
          .cast<Map<String, dynamic>>();
      List<Users> listOfUsers = items.map<Users>((json) {
        return Users.fromJson(json);
      }).toList();

      return listOfUsers;
    } else {
      throw Exception('Failed to load internet');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder<List<Users>>(
        future: _fetchUsers(),
        builder: (context, snapshot) {
          if (!snapshot.hasData)
            return Center(child: CircularProgressIndicator());

          return ListView(
            children: snapshot.data
                .map((user) => ListTile(
                      title: Text(user.name),
                      subtitle: Text(user.email),
                      leading: CircleAvatar(
                        backgroundColor: Colors.red,
                        child: Text(user.name[0],
                            style: TextStyle(
                              fontSize: 18.0,
                              color: Colors.white,
                            )),
                      ),
                    ))
                .toList(),
          );
        },
      ),
    );
  }
}

class Users {
  int id;
  String name;
  String username;
  String email;

  Users({
    this.id,
    this.name,
    this.username,
    this.email,
  });

  factory Users.fromJson(Map<String, dynamic> json) {
    return Users(
      id: json['id'],
      name: json['name'],
      email: json['email'],
      username: json['username'],
    );
  }
}

when use https://jsonplaceholder.typicode.com/users it's working fine and when use mine https://www.christian-dogma.com/android-index.php i don't get any data

Upvotes: 0

Views: 1041

Answers (2)

DomingoMG
DomingoMG

Reputation: 1857

He managed to make it work, one of the problems he has is that the id asks me to be a String since you had it as an integer, I hope it worked for you.

import 'dart:convert';

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

class JsonApiPhp extends StatefulWidget {
  @override
  _JsonApiPhpState createState() => _JsonApiPhpState();
}

class _JsonApiPhpState extends State<JsonApiPhp> {

  bool loading = true;
  final String url = 'https://www.christian-dogma.com/android-index.php';
  var client = http.Client();
  List<User> users = List<User>();


  @override
  void initState(){
    fetchData();
    super.initState();
  }


  Future<void> fetchData() async {
    http.Response response = await client.get(url);
    if(response.statusCode == 200){ // Connection Ok
      List responseJson = json.decode(response.body);
      responseJson.map((m) => users.add(new User.fromJson(m))).toList();
      setState(() {
        loading = false;
      });
    } else {
      throw('error');
    }
  }



  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Container(
        child: loading ?
        Container(
          child: Center(
            child: CircularProgressIndicator(),
          ),
        ) :
        ListView.builder(
          itemCount: users.length,
          itemBuilder: (BuildContext context, int index){
            return Card(
              child: ListTile(
                title: Text(users[index].username),
              ),
            );
          },
        )
      ),
    );
  }
}

class User {
  final String id;
  final String name;
  final String username;
  final String email;

  User({
    this.id,
    this.name,
    this.username,
    this.email,
  });

  factory User.fromJson(Map<String, dynamic> json) {
    return User(
      id: json['id'],
      name: json['name'],
      email: json['email'],
      username: json['username'],
    );
  }
}

Upvotes: 1

baradwaj
baradwaj

Reputation: 266

I kind of banged my head around and finally found out that your JSON response is returning the id as a string and not as an integer.

Change the factory to following code.

factory Users.fromJson(Map<String, dynamic> json) {

    return Users(
      id: int.parse(json['id']),
      name: json['name'],
      email: json['email'],
      username: json['username'],
    );

Cheers!

Upvotes: 0

Related Questions