【问题标题】:How to pass a Parameter JSON while fetching from API in Flutter如何在 Flutter 中从 API 获取时传递参数 JSON
【发布时间】:2021-04-11 08:21:43
【问题描述】:

在 Flutter 中,我想传递一个参数 ('1') 并获取 id = 1 的专辑标题; API 是用 Java Springboot 编写的,后端是 MS SQL 数据库。请帮助我学习如何在 http.get 或 post 方法中的查询中传递参数。

目前我收到一个异常错误,http 响应代码是 400 或 405

这是我的代码

import 'dart:async';
import 'dart:convert';

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

Future<Album> fetchAlbum() async {
  final response =
      await http.get('https://jsonplaceholder.xxx.com/albums/');

  if (response.statusCode == 200) {
    return Album.fromJson(jsonDecode(response.body));
  } else {
    throw Exception('Failed to load album');
  }
}

class Album {
  final int userId;
  final int id;
  final String title;

  Album({this.userId, this.id, this.title});

  factory Album.fromJson(Map<String, dynamic> json) {
    return Album(
      userId: json['userId'],
      id: json['id'],
      title: json['title'],
    );
  }
}

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

class MyApp extends StatefulWidget {
  MyApp({Key key}) : super(key: key);

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

class _MyAppState extends State<MyApp> {
  Future<Album> futureAlbum;

  @override
  void initState() {
    super.initState();
    futureAlbum = fetchAlbum();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Fetch Data Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Fetch Data Example'),
        ),
        body: Center(
          child: FutureBuilder<Album>(
            future: futureAlbum,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return Text(snapshot.data.title);
              } else if (snapshot.hasError) {
                return Text("${snapshot.error}");
              }

              // By default, show a loading spinner.
              return CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}

【问题讨论】:

    标签: json api flutter


    【解决方案1】:

    你应该使用 URL 来设置参数:

    Future<Album> fetchAlbum(number id) async {
      final response =
          await http.get('https://jsonplaceholder.xxx.com/albums/$id');
    
      if (response.statusCode == 200) {
        return Album.fromJson(jsonDecode(response.body));
      } else {
        throw Exception('Failed to load album');
      }
    }
    

    因此您可以将 id 传递给将调用您的 API 的方法。

    您可以搜索 REST API 和 GET 参数等内容:REST API Best practices: Where to put parameters?

    【讨论】:

      【解决方案2】:

      如果你想以post格式发送,你可以这样发送

      当body为表单数据时:

      Future<Album> fetchAlbum() async {
        final response = await http.post('https://jsonplaceholder.xxx.com/albums/',
          body: <String, String> {
            'id': '1',
          },
        );
      
        if (response.statusCode == 200) {
          return Album.fromJson(jsonDecode(response.body));
        } else {
          throw Exception('Failed to load album');
        }
      }
      

      当body为json时:

      Future<Album> fetchAlbum() async {
        final response = await http.post(
          'https://jsonplaceholder.xxx.com/albums/',
          body: jsonEncode(
            {
              'id': '1',
            },
          ),
          headers: {'Content-Type': "application/json"},
        );
      
        if (response.statusCode == 200) {
          return Album.fromJson(jsonDecode(response.body));
        } else {
          throw Exception('Failed to load album');
        }
      }
      

      由于 http/http.dart 包已添加到您的代码中,我建议您阅读以下文档。

      https://pub.dev/packages/http

      而http错误码400和405分别是

      400:错误请求

      405: 方法不允许

      【讨论】:

        猜你喜欢
        • 2019-10-16
        • 2021-06-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-24
        • 1970-01-01
        • 2020-03-29
        相关资源
        最近更新 更多