简体   繁体   中英

How to display the JSON data fetched from API in flutter?

I want to fetch the data from API and display it in flutter app. I've been able to fetch the data and display it using ListView builder. But, the problem now I'm facing is that the scroll is not working properly in this case and I don't want to display the data in the form of Lists.

So, is there any other way where we can fetch the data and show it in the app. This is how the UI is going to look.

在此处输入图片说明

I'm unable to accomplish this using ListView builder or any other way as I'm very new to flutter.

This is my code which I used in another widget where I was facing the scrolling issue, to create the ListView:

  @override
  _AllEventsState createState() => _AllEventsState();
}

class _AllEventsState extends State<AllEvents> {
  final String url =
      "api-url";
  List data;

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

  createRoute(id) {
    print('args $id');
    Navigator.pushNamed(context, '/eventdetail', arguments: id);
  }

  Future<String> getAllEvents() async {
    var response = await http.get(
      Uri.encodeFull(url),
      headers: {"Accept": "application/json"},
    );
    setState(() {
      var convertDataToJson = jsonDecode(response.body);
      data = convertDataToJson["events"];
    });
    return "Success";
  }

  @override
  Widget build(BuildContext context) {
  ScrollController _controller = new ScrollController();
    return Container(
      child: ListView.builder(
        physics: const AlwaysScrollableScrollPhysics(),
        controller: _controller,
        shrinkWrap: true,
        itemCount: data == null ? 0 : data.length,
        itemBuilder: (BuildContext cont, int index) {
          // format date
          var dateString = data[index]["eventDate"];
          var eventDate = Jiffy(dateString).MMMEd;
          return Container(
            padding: const EdgeInsets.fromLTRB(30, 7, 30, 7),
            child: Center(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: <Widget>[
                  new InkWell(
                    onTap: () {
                      print('card tapped');
                      createRoute(data[index]['_id']);
                    },
                    child: Card(
                      child: Container(
                        decoration: BoxDecoration(
                          border: Border.all(
                            width: 3,
                            color: hexToColor("#EBEBEB"),
                          ),
                          borderRadius: BorderRadius.circular(8.0),
                        ),
                        padding: const EdgeInsets.fromLTRB(20, 20, 20, 20),
                        child: Column(
                          children: <Widget>[
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: <Widget>[
                                customText(
                                  eventDate.toString(),
                                  "#000000",
                                  "20.0",
                                  TextAlign.left,
                                  "Roboto Black",
                                  FontWeight.w900,
                                ),
                                customText(
                                  "10, 9",
                                  "#000000",
                                  "20.0",
                                  TextAlign.right,
                                  "Roboto Black",
                                  FontWeight.w900,
                                ),
                              ],
                            ),
                            SizedBox(height: 20),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: <Widget>[
                                Expanded(
                                  child: customText(
                                    "${data[index]['city']} | ${data[index]['arenaName']} | ${data[index]['categories'][0]['title']}",
                                    "#000000",
                                    "18.0",
                                    TextAlign.left,
                                    "Roboto Black",
                                    FontWeight.w900,
                                  ),
                                ),
                              ],
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          );
        },
      ),
    );
  }
}

This is how I'm fetching the data from the API in another widget:

    print("$url${widget.eventId}");
    var response = await http.get(
      Uri.encodeFull("$url${widget.eventId}"),
      // headers: {"Accept": "application/json"},
    );

    print('events response ${response.body}');
    setState(() {
      var convertDataToJson = jsonDecode(response.body);
      data = convertDataToJson["event"];
      print(data);
    });
    return "Success";
  }```

Can you please suggest a way as to how I can display the data properly in flutter?

Use FutureBuilder to get data from api like this :-

FutureBuilder(
      future: yourMethodName(),
      builder: (context, AsyncSnapshot<NameOfModelClass> snapshot) {
        if (snapshot.data == null) {
          return Center(child: CircularProgressIndicator());
        }
        // after getting data from api
      },
    );

Your method can be like this :

Future<NameOfModelClass> YourMethodName() async {
  final response = await http.get('Your url here');
  return NameOfModelClass.fromJson(json.decode(response.body.toString()));
}

The model class can be generate by using jsonToDart

I hope this help :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM