Bird
Raised Fist0
Fluttermobile~20 mins

http package in Flutter - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
HTTP Package Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ ui_behavior
intermediate
2:00remaining
What is the output of this Flutter code using http package?
Consider this Flutter code snippet that fetches data from a URL and displays the response body in a Text widget. What will the UI show after a successful fetch?
Flutter
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class MyWidget extends StatefulWidget {
  @override
  State<MyWidget> createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  String data = 'Loading...';

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

  Future<void> fetchData() async {
    final response = await http.get(Uri.parse('https://example.com'));
    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 UI shows the full HTML content of https://example.com as text.
BThe UI shows the text 'Loading...' forever because fetchData is never called.
CThe UI shows 'Error fetching data' because the URL is invalid.
DThe UI shows a blank screen because setState is not called.
Attempts:
2 left
💡 Hint
Look at when fetchData is called and what happens on a successful response.
📝 Syntax
intermediate
2:00remaining
Which option correctly creates a POST request with JSON body using http package?
You want to send a POST request with JSON data {'name': 'Alice'} to 'https://api.example.com/user'. Which code snippet is correct?
Aawait http.post(Uri.parse('https://api.example.com/user'), body: {'name': 'Alice'});
B;))}'ecilA' :'eman'{(edocnEnosj :ydob ,)'resu/moc.elpmaxe.ipa//:sptth'(esrap.irU(tsop.ptth tiawa
Cawait http.post(Uri.parse('https://api.example.com/user'), body: jsonEncode({'name': 'Alice'}));
Dawait http.post(Uri.parse('https://api.example.com/user'), headers: {'Content-Type': 'application/json'}, body: '{"name":"Alice"}');
Attempts:
2 left
💡 Hint
Remember to set the content type header when sending JSON data.
❓ lifecycle
advanced
2:00remaining
What happens if you call http.get inside build() method directly?
In a Flutter widget, what is the effect of calling http.get inside the build() method without caching or state management?
AThe HTTP request runs repeatedly causing performance issues and possible infinite loops.
BThe HTTP request runs once and the UI updates correctly.
CThe HTTP request is ignored by Flutter and does not run.
DThe app crashes with a runtime error.
Attempts:
2 left
💡 Hint
Think about how often build() runs and what happens if you do async calls there.
🔧 Debug
advanced
2:00remaining
Why does this http.get code throw a FormatException?
This code throws a FormatException: Invalid argument(s): Invalid URL. What is the cause?
Flutter
final response = await http.get(Uri.parse('htp://invalid-url'));
AUri.parse cannot parse URLs with 'http' scheme.
BThe URL scheme 'htp' is invalid; it should be 'http' or 'https'.
Chttp.get requires a String, not a Uri object.
DThe URL is missing a trailing slash.
Attempts:
2 left
💡 Hint
Check the URL scheme spelling carefully.
🧠 Conceptual
expert
2:00remaining
Which option best describes how to handle HTTP errors gracefully in Flutter using http package?
You want your app to show a friendly message if the HTTP request fails due to network issues or server errors. Which approach is best?
AUse http.get without await to avoid exceptions.
BIgnore errors; Flutter will automatically retry failed HTTP requests.
CWrap the http call in try-catch, check response status, and update UI accordingly.
DOnly check response status code; no need for try-catch.
Attempts:
2 left
💡 Hint
Think about network failures and how exceptions are handled in Dart async code.

Practice

(1/5)
1.

What does the http.get() function do in Flutter's http package?

easy
A. It deletes data from a server.
B. It sends data to a server.
C. It fetches data from a given URL.
D. It updates data on a server.

Solution

  1. Step 1: Understand the purpose of http.get()

    The http.get() method is used to request data from a specified URL.
  2. Step 2: Differentiate from other HTTP methods

    Sending data uses http.post(), deleting uses http.delete(), and updating uses http.put() or http.patch().
  3. Final Answer:

    It fetches data from a given URL. -> Option C
  4. Quick Check:

    http.get() = fetch data [OK]
Hint: Remember: get = fetch, post = send [OK]
Common Mistakes:
  • Confusing get() with post()
  • Thinking get() sends data
  • Mixing HTTP methods
2.

Which of the following is the correct way to create a URI for http.get() in Flutter?

http.get(???);
easy
A. http.get(Uri.parse('https://example.com'))
B. http.get(Uri.https('example.com'))
C. http.get(Uri('https://example.com'))
D. http.get('https://example.com')

Solution

  1. Step 1: Check the required argument type for http.get()

    The http.get() method requires a Uri object, not a plain string.
  2. Step 2: Use Uri.parse() to convert string to Uri

    The correct way is to wrap the URL string with Uri.parse() to create a Uri object.
  3. Final Answer:

    http.get(Uri.parse('https://example.com')) -> Option A
  4. Quick Check:

    Use Uri.parse() for URLs in http.get() [OK]
Hint: Always wrap URL string with Uri.parse() [OK]
Common Mistakes:
  • Passing URL as plain string
  • Using Uri() constructor incorrectly
  • Trying Uri.https() without parameters
3.

What will be printed by this Flutter code snippet?

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

void fetchData() async {
  final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts/1'));
  if (response.statusCode == 200) {
    print('Success');
  } else {
    print('Failed');
  }
}

fetchData();
medium
A. SyntaxError
B. Success
C. Failed
D. No output

Solution

  1. Step 1: Analyze the HTTP GET request

    The code requests a valid URL that returns a post with status code 200 on success.
  2. Step 2: Check the status code condition

    If the status code is 200, it prints 'Success'; otherwise, 'Failed'. The URL is valid and should return 200.
  3. Final Answer:

    Success -> Option B
  4. Quick Check:

    Status code 200 means Success [OK]
Hint: Status code 200 means success [OK]
Common Mistakes:
  • Assuming any response prints 'Failed'
  • Ignoring async/await usage
  • Not checking statusCode properly
4.

Identify the error in this Flutter code using the http package:

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

void sendData() async {
  final response = await http.post('https://example.com/api/data');
  if (response.statusCode == 201) {
    print('Created');
  }
}
medium
A. No error; code is correct.
B. Incorrect status code check; should be 200.
C. http.post() cannot be awaited.
D. Missing Uri.parse() around the URL string.

Solution

  1. Step 1: Check the argument type for http.post()

    The http.post() method requires a Uri object, not a plain string.
  2. Step 2: Identify missing Uri.parse()

    The URL string should be wrapped with Uri.parse() to convert it to a Uri object.
  3. Final Answer:

    Missing Uri.parse() around the URL string. -> Option D
  4. Quick Check:

    http.post() needs Uri.parse() for URL [OK]
Hint: Always use Uri.parse() for URLs in http methods [OK]
Common Mistakes:
  • Passing URL as string directly
  • Confusing status codes 200 and 201
  • Forgetting async/await with http calls
5.

You want to send JSON data using http.post() in Flutter. Which code snippet correctly sends a JSON body and sets the content type header?

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

void sendJson() async {
  final url = Uri.parse('https://example.com/api');
  final response = await http.post(
    url,
    headers: ???,
    body: ???,
  );
}
hard
A. {'Content-Type': 'application/json'}, jsonEncode({'key': 'value'})
B. {'content-type': 'text/plain'}, jsonEncode({'key': 'value'})
C. {'Content-Type': 'application/json'}, {'key': 'value'}
D. {'Content-Type': 'application/json'}, json.decode({'key': 'value'})

Solution

  1. Step 1: Set the correct header for JSON

    The header must be {'Content-Type': 'application/json'} to tell the server the body is JSON.
  2. Step 2: Encode the body as JSON string

    The body must be a string, so use jsonEncode() to convert the map to a JSON string.
  3. Final Answer:

    {'Content-Type': 'application/json'}, jsonEncode({'key': 'value'}) -> Option A
  4. Quick Check:

    Headers + jsonEncode() = correct JSON POST [OK]
Hint: Use jsonEncode() and set Content-Type header [OK]
Common Mistakes:
  • Passing map directly as body
  • Wrong content-type header
  • Using json.decode() instead of jsonEncode()
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