Bird
Raised Fist0
Fluttermobile~20 mins

GET and POST requests in Flutter - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
HTTP Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ ui_behavior
intermediate
2:00remaining
What happens when this Flutter code runs?
This Flutter widget fetches data from a URL using a GET request and displays the result. What will the UI show after the data is successfully fetched?
Flutter
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class DataFetcher extends StatefulWidget {
  @override
  State<DataFetcher> createState() => _DataFetcherState();
}

class _DataFetcherState extends State<DataFetcher> {
  String data = 'Loading...';

  @override
  void initState() {
    super.initState();
    fetchData();
  }

  Future<void> fetchData() async {
    final response = await http.get(Uri.parse('https://example.com/data'));
    if (response.statusCode == 200) {
      setState(() {
        data = response.body;
      });
    } else {
      setState(() {
        data = 'Error fetching data';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(child: Text(data)),
    );
  }
}
AThe screen shows the text content fetched from https://example.com/data.
BThe screen shows the text 'Loading...' indefinitely.
CThe screen shows a blank white screen with no text.
DThe app crashes with a runtime error due to missing internet permission.
Attempts:
2 left
💡 Hint
Think about what happens after the HTTP GET request completes successfully.
📝 Syntax
intermediate
2:00remaining
Which option correctly sends a POST request with JSON body in Flutter?
You want to send a POST request with JSON data {'name': 'Alice'} to https://example.com/api. Which code snippet is correct?
Aawait http.post(Uri.parse('https://example.com/api'), body: jsonEncode({'name': 'Alice'}), headers: {'Content-Type': 'text/plain'});
Bawait http.post(Uri.parse('https://example.com/api'), body: {'name': 'Alice'});
Cawait http.post('https://example.com/api', body: jsonEncode({'name': 'Alice'}));
Dawait http.post(Uri.parse('https://example.com/api'), headers: {'Content-Type': 'application/json'}, body: jsonEncode({'name': 'Alice'}));
Attempts:
2 left
💡 Hint
Remember to set the content type header to 'application/json' and encode the body as JSON string.
❓ lifecycle
advanced
2:00remaining
What is the problem with this Flutter GET request code inside build()?
Consider this Flutter widget code snippet that fetches data inside the build method. What issue will it cause?
Flutter
import 'package:http/http.dart' as http;

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    http.get(Uri.parse('https://example.com/data')).then((response) {
      print(response.body);
    });
    return Text('Fetching data...');
  }
}
AThe GET request runs only once and works fine.
BThe GET request runs repeatedly causing performance issues and multiple prints.
CThe code causes a compile-time error because http.get is not allowed in build.
DThe app crashes because build method cannot have async calls.
Attempts:
2 left
💡 Hint
Think about how often build() runs in Flutter widgets.
🔧 Debug
advanced
2:00remaining
Why does this POST request fail with a 415 Unsupported Media Type error?
This Flutter code sends a POST request but the server responds with 415 error. What is the cause?
Flutter
final response = await http.post(
  Uri.parse('https://example.com/api'),
  body: jsonEncode({'key': 'value'}),
);
AThe Content-Type header is missing or incorrect.
BThe URL is invalid and causes server error.
CThe body is not encoded as JSON string.
DThe http.post method requires a GET request instead.
Attempts:
2 left
💡 Hint
Check what header tells the server the data format.
🧠 Conceptual
expert
2:00remaining
What is the best way to handle errors in Flutter async HTTP requests?
You want to fetch data with GET and handle possible errors like network failure or bad response. Which approach is best?
AUse only .then() without error handling callbacks.
BIgnore errors and assume the request always succeeds.
CUse try-catch around await http.get and check response status code inside try block.
DCall http.get without await and do not check response.
Attempts:
2 left
💡 Hint
Think about catching exceptions and validating responses.

Practice

(1/5)
1. What is the main purpose of a GET request in Flutter when using the http package?
easy
A. To send data to a server to create or update something
B. To delete data from a server
C. To fetch data from a server without changing it
D. To authenticate a user

Solution

  1. Step 1: Understand GET request purpose

    GET requests are used to retrieve or fetch data from a server without modifying it.
  2. Step 2: Compare with other request types

    POST requests send data to create or update, DELETE removes data, and authentication is separate.
  3. Final Answer:

    To fetch data from a server without changing it -> Option C
  4. Quick Check:

    GET = fetch data [OK]
Hint: GET fetches data, POST sends data [OK]
Common Mistakes:
  • Confusing GET with POST requests
  • Thinking GET modifies server data
  • Mixing GET with DELETE or authentication
2. Which of the following is the correct syntax to make a POST request using the http package in Flutter?
easy
A. http.post(Uri.parse(url), body: {"key": "value"});
B. http.get(Uri.parse(url), body: {"key": "value"});
C. http.post(url, {"key": "value"});
D. http.sendPost(Uri.parse(url), body: {"key": "value"});

Solution

  1. Step 1: Identify correct method and parameters

    The http.post method requires a Uri object and an optional body map for data.
  2. Step 2: Check syntax correctness

    http.post(Uri.parse(url), body: {"key": "value"}); uses Uri.parse(url) and passes body correctly. Others use wrong methods or parameters.
  3. Final Answer:

    http.post(Uri.parse(url), body: {"key": "value"}); -> Option A
  4. Quick Check:

    POST syntax = http.post(Uri.parse(url), body) [OK]
Hint: Use Uri.parse() and http.post() with body map [OK]
Common Mistakes:
  • Passing URL as string instead of Uri
  • Using http.get instead of http.post for POST
  • Wrong method name like sendPost
3. What will be the output of this Flutter code snippet using the http package?
var response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts/1'));
print(response.statusCode);
print(response.body.contains('userId'));
medium
A. 200 and false
B. 404 and false
C. 500 and false
D. 200 and true

Solution

  1. Step 1: Understand the GET request URL

    The URL points to a valid post resource, so the server should respond with status 200 (OK).
  2. Step 2: Check response body content

    The JSON response includes a 'userId' field, so response.body.contains('userId') returns true.
  3. Final Answer:

    200 and true -> Option D
  4. Quick Check:

    Status 200 and body contains 'userId' = true [OK]
Hint: Valid URL returns 200 and expected JSON content [OK]
Common Mistakes:
  • Assuming 404 for valid URL
  • Not checking response body content
  • Confusing status codes
4. Identify the error in this Flutter code that tries to send a POST request:
var response = await http.post('https://example.com/api', body: {"name": "John"});
print(response.statusCode);
medium
A. Body should be a JSON string, not a map
B. URL should be wrapped with Uri.parse()
C. http.post cannot be awaited
D. Missing headers for content type

Solution

  1. Step 1: Check URL parameter type

    The http.post method requires the URL as a Uri object, not a plain string.
  2. Step 2: Confirm correct usage

    Wrapping the URL string with Uri.parse() fixes the error. Other options are not mandatory errors here.
  3. Final Answer:

    URL should be wrapped with Uri.parse() -> Option B
  4. Quick Check:

    URL must be Uri.parse(string) [OK]
Hint: Always wrap URL string with Uri.parse() [OK]
Common Mistakes:
  • Passing URL as plain string
  • Assuming body must be JSON string always
  • Forgetting to await async calls
5. You want to send a POST request with JSON data and receive a JSON response in Flutter. Which code snippet correctly handles this scenario using the http package?
hard
A. var response = await http.post(Uri.parse(url), headers: {"Content-Type": "application/json"}, body: jsonEncode({"name": "Alice"})); var data = jsonDecode(response.body);
B. var response = await http.post(Uri.parse(url), body: {"name": "Alice"}); var data = response.body;
C. var response = await http.get(Uri.parse(url), headers: {"Content-Type": "application/json"}); var data = jsonDecode(response.body);
D. var response = await http.post(url, body: jsonEncode({"name": "Alice"})); var data = jsonDecode(response.body);

Solution

  1. Step 1: Set headers and encode body correctly

    To send JSON data, set header "Content-Type" to "application/json" and encode body with jsonEncode.
  2. Step 2: Parse JSON response properly

    Use jsonDecode on response.body to convert JSON string to Dart object.
  3. Step 3: Check URL parameter type

    URL must be wrapped with Uri.parse() for correct request.
  4. Final Answer:

    Use http.post with Uri.parse, headers, jsonEncode body, and jsonDecode response -> Option A
  5. Quick Check:

    POST JSON = headers + jsonEncode + jsonDecode [OK]
Hint: Use headers and jsonEncode for POST JSON, decode response [OK]
Common Mistakes:
  • Not setting Content-Type header
  • Passing body as map without encoding
  • Using http.get instead of post for sending data
  • Passing URL as string without Uri.parse
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard