0

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

1
  • I will use your PHP link to see what the problem is. Commented Aug 20, 2019 at 12:48

2 Answers 2

1

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'],
    );
  }
}
Sign up to request clarification or add additional context in comments.

6 Comments

thanks , for your help , i will need to show image float rigth , thats possible !!
If you want to add an image on the right side, use the ListTile Trailing to add an image.
If I have helped you, I would appreciate your help as a problem solved, regards.
i marked it as solved , but i wanna to ask , how to make it clickable box with id of news , and how to make image float right , do you have any urls to help !!
Use the InkWell ( child: Card ( child: ListTile (.......) ), onTap () { // Card Item OnTap } );
|
0

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.