flutter 将数据发送到Internet并显示返回值

hfsqlsce  于 2023-11-21  发布在  Flutter
关注(0)|答案(1)|浏览(141)

我目前正在学习如何发送数据到互联网即时通讯使用heroku服务器持有的数据
现在,我设法清除了http post请求中的一些错误。问题是我无法在应用程序中将返回值显示为字符串。
我总是以No data available结束。
x1c 0d1x的数据
有人能帮忙吗?我不知道是不是网址或请求本身有问题。

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;

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

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

  
  String showFetchedData() {
    if (dataList.isEmpty) {
      return 'No data available.';
    } else {
      // You can format the data as a string here if needed
      String result = '';
      for (var item in dataList) {
        result += 'Service: ${item['service']}, Next Bus: ${item['next bus']}\n';
      }
      return result;
    }
  }

  @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);
                      String message = showFetchedData();
                      if (message.isNotEmpty) {
                        // Show the message using a dialog or other UI element
                        showDialog(
                          context: context,
                          builder: (context) => AlertDialog(
                            title: const Text('Data Retrieval Result'),
                            content: Text(message),
                            actions: [
                              TextButton(
                                onPressed: () {
                                  Navigator.pop(context);
                                  },
                                child: const Text('OK'),
                              ),
                            ],
                          ),
                        );
                      }
                      }, 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 ListTile(
                      title: Text('Service: ${item['service']}'),
                      subtitle: Text('Next Bus: ${item['next bus']}'),
                    );
                  },
                ),
              ),
            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}]}

ckx4rj1h

ckx4rj1h1#

您的fetchData(String c)方法不完整。您发送了HTTP请求,但未对响应执行任何操作。
它应该看起来像这样

Future<http.Response> fetchData(String c) async {
    final response = await http.post(
        Uri.parse('https://laravelsyd-fypfinalver.herokuapp.com/getBusService'),
        headers: <String, String>{
          'Content-Type': 'application/json; charset=UTF-8',
        },
        body: jsonEncode({'bus_stop_id': busCode}),);

     if (response.statusCode == 200) {
         var returnedData = jsonDecode(response.Body) as Map<string,dynamic>;
         // If desired, perform some data validation
         // ...
         dataList = returnedData
     } else {
         // Display error message
         throw Exception('Failed to load data');
     }
    return response;
}

字符串
这只是一个基本的实现,你可能需要花些时间来考虑数据验证、错误处理、日志记录等。
但重要的部分是dataList = returnedData。你需要将加载的数据分配给你的状态属性。否则应用程序现在不会有任何新数据

相关问题