-1

In Flutter, I want to pass a parameter ('1') and fetch the album title where the id = 1; the API is written in Java Springboot and the backend is MS SQL Database. Please help me to learn how to pass the parameter in my query in http.get or post method.

Currently I get an Exception error and the http response code is 400 or 405

Here's my code

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();
            },
          ),
        ),
      ),
    );
  }
}
MAS
  • 1

2 Answers2

0

You should use the URL to set parameters :

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');
  }
}

So you can pass the id to the method that will call your API.

You can search for stuff like REST API and GET parameters : REST API Best practices: Where to put parameters?

BabC
  • 715
  • 1
  • 13
0

If you want to send it in post format, you can send it like this

When body is form data :

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');
  }
}

When body is 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');
  }
}

Since the http/http.dart package has been added to your code, I recommend reading the following documentation.

https://pub.dev/packages/http

And the http error codes 400 and 405 are

400: Bad Request

405: Method Not Allowed

battlecook
  • 142
  • 1
  • 10