我已成功尝试从我的 URL 检索数据。我正在尝试分离数据,以便我可以使用我不熟悉的 JSON 单独处理它......
当我更改代码时,我收到错误 400。我确信 URL 没有问题,因为它以前工作过
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')),
]),
],
),
],
),
),
);
}
}
输出:返回特定公交车站所有公交车服务的预计到达时间。绝对时间和相对时间,即26分钟和38分钟到达
[
{
"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 }
]
}
]
我正在尝试使用json库来分别显示公交车服务号、时间和相对时间
当您获得 JSON 输出时,您的请求没有任何问题。如果它返回错误代码 400,这意味着问题出在您的服务器上,您必须检查是否手动返回了该状态。