1

I'm trying to load json data using HTTP Get Request but it doesn't sho any thing and doesn't even display the list. It's the first time I use the API and I'm not really understand how it works, please give me some instructions to understand and work with it. I just follow this tutorial https://www.youtube.com/watch?v=aIJU68Phi1w

MyHomePage.dart

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

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final String url = "http://127.0.0.1:8000/api/membres";
  List data;

  @override
  void initState() {
    super.initState();
    this.getJsonData();
  }

  Future<String> getJsonData() async {
    var response = await http
        .get(Uri.encodeFull(url), headers: {"Accept": "application/json"});
    print(response.body);

    setState(() {
      var convertDataToJson = json.decode(response.body);
      data = convertDataToJson['results'];
    });
    return "Success";
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          title: Text('Membres'),
        ),
        body: new ListView.builder(
            itemCount: data == null ? 0 : data.length,
            padding: const EdgeInsets.all(4.0),
            itemBuilder: (BuildContext context, int index) {
              return new Container(
                child: new Center(
                  child: new Column(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: <Widget>[
                      new Card(
                        child: new Container(
                          child: new Text(data[index]['nom']),
                          padding: const EdgeInsets.all(20.0),
                        ),
                      )
                    ],
                  ),
                ),
              );
            }));
  }
}

enter image description here

This is My JSON enter image description here

Yoss
  • 466
  • 2
  • 4
  • 13

2 Answers2

1

You are sure that the variable data has data? try to print(data). You can use .map() without using ListView.

body: new Container(
  child: new Center(
    child: new Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
        children: data.map((d) => 
          return new Card(
            child: new Container(
              child: new Text(d.nom),
                padding: const EdgeInsets.all(20.0),
              ),
            )
          ).toList();
        ),
      ),
    );
JideGuru
  • 7,102
  • 6
  • 26
  • 48
GirlWhoCode
  • 628
  • 4
  • 12
1

I feel you are making a mistake with the JSON parsing!

in your code you have data = convertDataToJson['results']; but in your JSON, there is no such thing as results.

Use data = convertDataToJson['membre']; instead.

Full code should be

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

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final String url = "http://127.0.0.1:8000/api/membres";
  List data;

  @override
  void initState() {
    super.initState();
    this.getJsonData();
  }

  Future<String> getJsonData() async {
    var response = await http
        .get(Uri.encodeFull(url), headers: {"Accept": "application/json"});
    print(response.body);

    setState(() {
      var convertDataToJson = json.decode(response.body);
      data = convertDataToJson['results'];
    });
    return "Success";
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          title: Text('Membres'),
        ),
        body: new ListView.builder(
            itemCount: data == null ? 0 : data.length,
            padding: const EdgeInsets.all(4.0),
            itemBuilder: (BuildContext context, int index) {
              return new Container(
                child: new Center(
                  child: new Column(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: <Widget>[
                      new Card(
                        child: new Container(
                          child: new Text(data[index]['nom']),
                          padding: const EdgeInsets.all(20.0),
                        ),
                      )
                    ],
                  ),
                ),
              );
            }));
  }
}
JideGuru
  • 7,102
  • 6
  • 26
  • 48
  • Even i used data = convertDataToJson['membre']; it doesn't work – Yoss Apr 22 '19 at 21:48
  • are you sure your request is returning any data? have u tried printing the response.body? – JideGuru Apr 22 '19 at 22:55
  • yes the problem is in http get and it return too many errors like `SocketException: OS Error: Connection refused, errno = 111, address = 127.0.0.1, port = 49021 E/flutter (23212): #0 IOClient.send (package:http/src/io_client.dart:33:23)` and `get (package:http/http.dart:46:5) E/flutter (23212): #6 _MyHomePageState.getJsonData (package:association/MyHomePage.dart:30:26) E/flutter (23212): ` – Yoss Apr 23 '19 at 17:44
  • That's a connection problem. Check your device connection – JideGuru Apr 23 '19 at 17:51
  • The problem is in the connection with localhost but every thing is okey with the device ( my phone) – Yoss Apr 23 '19 at 19:46
  • Ok then. I hope you fix it. Try this [link](https://stackoverflow.com/questions/49855754/unable-to-make-calls-to-localhost-using-flutter-random-port-being-assigned-to-h) – JideGuru Apr 23 '19 at 23:14