如何在flutter中将参数传递到get请求中

tjvv9vkg  于 2023-06-24  发布在  Flutter
关注(0)|答案(2)|浏览(138)

我试图通过参数到一个获取请求,我有问题。我试着像代码中看到的那样手动执行,但它返回错误。请帮帮忙。
这是我的服役档案

import 'dart:convert';

import 'package:http/http.dart';

import '../models/journal_response_model.dart';

class GetJournalService {
  String endpoint =
      'https://friendnpalapp-production-fbcc.up.railway.app/api/journal';

  Future<List<JournalResponseModel>> getArticles(String username) async {
    Response response =
        await get(Uri.parse('${endpoint}' '?username=$username'));

    if (response.statusCode == 200) {
      final List result = [jsonDecode(response.body)];
      print(response.body);
      return result.map(((e) => JournalResponseModel.fromJson(e))).toList();
    } else {
      print('error');
      throw Exception(response.reasonPhrase);
    }
  }
}

这是我未来的建筑师

FutureBuilder<List<JournalResponseModel>>(
                      future: GetJournalService().getArticles('jack'),
                      builder: (context, snapshot) {
                        if (snapshot.hasData) {
                          return ListView.builder(
                            shrinkWrap: true,
                            itemCount: snapshot.data!.length,
                            itemBuilder: (context, index) {
                              print(snapshot.data!);
                              final journal = snapshot.data![index];
                              return EntryWidget(
                                backgroundColor: AppColors.blue,
                                icon: Icons.remove,
                                mood: journal.mood!,
                                date: journal.createdAt!,
                              );
                            },
                          );
                        } else if (snapshot.hasError) {
                          return Text('${snapshot.error}');
                        }
                        return CircularProgressIndicator();
                      })
93ze6v8z

93ze6v8z1#

这里有一个来自DartPad的稍微修改过的官方示例

import 'package:http/http.dart' as http;

void main(List<String> arguments) async {
  final url = Uri.https(
    'www.googleapis.com'
    '/books/v1/volumes',
    {'q': 'http'},
  );

  final response = await http.get(url);
  print(response.request.toString());
}

此代码打印出GET https://www.googleapis.com/books/v1/volumes?q=http
在你的例子中,url应该是这样的(用用户名替换Test):

final url = Uri.https(
  'friendnpalapp-production-fbcc.up.railway.app',
  '/api/journal',
  {'username': 'Test'},
);
guykilcj

guykilcj2#

这个问题已经解决了。原因是API错误。
(返回404错误-这表示API有错误。)

相关问题