Error 400 while I'm using json library to handle returned value http.response

40 views Asked by At

I've succeeded in trying to retrieve the data from my URL. I'm trying to separate the data so that I can deal with it individually using JSON which I not familiar with...

As I'm changing the code I got error 400. I'm sure there's no problem with the URL as it worked before

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

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: busNearby(),
    );
  }
}

class busNearby extends StatefulWidget {
  const busNearby({super.key});

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

class busNearbyState extends State<busNearby> {
  final TextEditingController queryController = TextEditingController();
  List<Map<String, dynamic>> dataList = [];
  String busCode = '';
  late BuildContext scaffoldContext;

   String? busServiceNo;
   String? actualTime;
   String? relativeTime;


  Future<void> fetchData(String userInput) async{
    try{
      var response = await http.post(
        Uri.parse('https://laravelsyd-fypfinalver.herokuapp.com/getBusService'),

        headers: <String, String>{
          'Content-Type': 'application/json; charset=UTF-8',
        },
        body:
        json.encode({'bus_stop_id': busCode}),
      );
      hndleResponse(response);

    }catch (e){
      print("Error : $e");
    }
    print(busCode);
  }

  void hndleResponse(http.Response a) {
    if (a.statusCode >= 200 && a.statusCode < 300){
      List<dynamic> returnedData = json.decode(a.body);

      if(returnedData.isNotEmpty){
        busServiceNo = returnedData[0]['bus_service_no'];
        actualTime = returnedData[0]['eta']['time'][0];
        relativeTime = returnedData[0]['eta'][0]['relative_time'];
      }

      setState(() {});
    }else {
      print("Error:  ${a.statusCode}");
    }
    print(a.statusCode);
    print(busServiceNo);
    print(actualTime );
    print(relativeTime );

  }



  // Function to show fetched data or an error message in a bottom sheet
 void showFetchedData() {
    showModalBottomSheet(
      context: scaffoldContext,
      builder: (BuildContext context) {
        if (dataList.isEmpty) {
          return Container(
            padding: const EdgeInsets.all(16.0),
            child: const Text('No data available.'),
          );
        } else {
          return ListView.builder(
            itemCount: dataList.length,
            itemBuilder: (context, index) {
              final item = dataList[index];
              return SizedBox(
                height: 100,
                child: Card(
                  color: Colors.lightBlue[100],
                  child: Padding(
                    padding: const EdgeInsets.all(12.0),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text('Bus Code: ${item['bus_service_no']}'),
                        Text('Arrival Time: ${item['eta'].toString()}'),

                      ],
                    ),
                  ),
                ),
              );
            },
          );
        }
      },
    );
  }




  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Data Retrieval Example'),
      ),
      body: Center(
        child: Column(
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: TextField(
                onChanged: (value){
                  setState(() {
                    busCode = value;
                  });
                },
                controller: queryController,
                decoration: const InputDecoration(
                  labelText: 'Enter Bus Service Code',

                ),
              ),
            ),
            Builder(
              builder: (context) {
                scaffoldContext = context;
                return ElevatedButton(
                  onPressed: () async {
                    await fetchData(queryController.text);
                    showFetchedData(); // Call this method after data is fetched
                  },
                  child: const Text('Fetch Data'),
                );
                
              },
            ),
            if (dataList.isNotEmpty) // Show fetched data if available
              Expanded(
                child: ListView.builder(
                  itemCount: dataList.length,
                  itemBuilder: (context, index) {
                    final item = dataList[index];
                    return SizedBox(
                      height: 10,
                      child: Card(
                        child: Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text('Bus Code: ${item['bus_service_no']}'),
                              Text('ETA (minutes): ${item['relative_time']}'),
                            ],
                          ),
                        ),
                      ),
                    );


                  },
                ),
              ),
            DataTable(
              columns: const <DataColumn>[
                DataColumn(label: Text('Service Code')),
                DataColumn(label: Text('Location')),
              ],
              rows: const <DataRow>[
                DataRow(cells: <DataCell>[
                  DataCell(Text('1076')),
                  DataCell(Text('Larkin Terminal')),
                ]),
                DataRow(cells: <DataCell>[
                  DataCell(Text('1084')),
                  DataCell(Text('Taman Universiti')),
                ]),
                DataRow(cells: <DataCell>[
                  DataCell(Text('1019')),
                  DataCell(Text('Skudai Prade')),
                ]),
                DataRow(cells: <DataCell>[
                  DataCell(Text('1052')),
                  DataCell(Text('Opposite Skudai Prade')),
                ]),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

Output: return the estimated arrival time of all bus services at a particular bus stop. Absolute time, and relative time, i.e., arriving in 26 min, and 38 mins

[
    { 
        "route_id": 1,
        "bus_service_no": "7",
        "eta": [
                   { "time": "2020-07-10 15:17:07",
                     "relative_time": 26 },
                   { "time":"2020-07-10 15:29:21",
                     "relative_time":38 }
               ]
     }
]

I'm trying to use json library to separately display the bus service no, time and relative time

1

There are 1 answers

0
Loïc Yabili On

As you're getting the JSON output, there is nothing wrong in your request. if it returns error code 400 that means the problem is on your server you have to check if you manually returned that status.