Flutter Networking: REST APIs u0026 JSON Handling Quiz Quiz

Challenge your understanding of Flutter networking by answering questions focused on REST API integration, asynchronous requests, JSON parsing, and practical coding scenarios. This quiz covers key techniques, error handling, and best practices for efficient data management in Flutter applications.

  1. HTTP Methods in REST APIs

    Which HTTP method should you use to update an existing resource on a REST API in a Flutter app?

    1. PUT
    2. POST
    3. DELETE
    4. GET

    Explanation: PUT is used for updating an existing resource on a REST API. GET retrieves data, POST creates new resources, and DELETE removes resources. Using PUT ensures your update request is idempotent, while the other methods have different purposes or side effects in RESTful design.

  2. Asynchronous HTTP Requests

    How do you ensure that your Flutter app does not freeze when performing HTTP requests to a REST API?

    1. By running the request on the main thread synchronously
    2. By calling the HTTP request in the build method
    3. By using 'print' statements
    4. By using async-await with Future

    Explanation: Using async-await with Future ensures that HTTP requests are performed asynchronously, preventing the app's UI from freezing. Placing requests in the build method can cause repeated fetching and performance issues. 'Print' statements are only for debugging, and running synchronously on the main thread will block the UI.

  3. Decoding JSON Data

    What is the correct way to convert a JSON string response from an API into a Dart Map object?

    1. By using toJson()
    2. By using encodeJson()
    3. By using jsonDecode()
    4. By using parseJson()

    Explanation: The jsonDecode() function takes a JSON string and converts it into a Dart object such as a Map or List. encodeJson() and parseJson() are not valid functions, while toJson() is typically used for converting a Dart object to a JSON string, not the other way around.

  4. Handling HTTP Status Codes

    When receiving an HTTP 404 status code while fetching data in Flutter, what does it indicate?

    1. The requested resource was not found
    2. The request was successful
    3. The server is down
    4. The request was unauthorized

    Explanation: A 404 status code means the requested resource does not exist on the server. A 200 code shows success, a 401 means unauthorized access, and the server being down might produce a 500 or connectivity error rather than a 404.

  5. Serializing Dart Objects

    Which approach is commonly used to convert a Dart object into a JSON map for sending data to a REST API?

    1. Using print() on the object
    2. Implementing a toJson() method in the Dart class
    3. Calling a fromJson() constructor
    4. Declaring variables as static

    Explanation: Defining a toJson() method allows a Dart object to be converted to a Map suitable for JSON encoding. fromJson() is used for deserialization, not serialization. print() outputs text only, and static variables are unrelated to JSON mapping.

  6. Error Handling in HTTP Requests

    What is the recommended way in Flutter to handle exceptions that may occur during an HTTP request to a RESTful API?

    1. Wrapping the request in a try-catch block
    2. Running the request in an infinite loop
    3. Ignoring the exception
    4. Writing errors to a file directly

    Explanation: Using try-catch ensures that exceptions like network errors are caught and handled gracefully. Ignoring exceptions can crash the app, writing errors to a file directly is not standard error handling for HTTP requests, and running an infinite loop can freeze the app.

  7. Making POST Requests

    When making a POST request to a REST API in Flutter, where should you typically place the data payload?

    1. In the request body
    2. In the request header
    3. As a function argument but not sent
    4. In the URL path

    Explanation: Data payloads for POST requests are placed in the request body. Putting data in the header or URL path is incorrect for sending structured data, and not sending the payload at all means nothing is transmitted to the server.

  8. Mapping JSON Arrays

    If a REST API returns a JSON array of objects, such as a list of users, what is the standard Dart type for the decoded JSON?

    1. Listu003CMapu003CString, dynamicu003Eu003E
    2. Listu003CStringu003E
    3. Setu003CStringu003E
    4. Mapu003CString, Objectu003E

    Explanation: Decoding a JSON array of objects gives a List of Map objects where each map holds string keys and dynamic values. A Mapu003CString, Objectu003E represents a single map, Listu003CStringu003E and Setu003CStringu003E only hold strings, which do not match object structure.

  9. Setting HTTP Headers

    To ensure the server knows you are sending JSON data in a Flutter HTTP request, which header should you set?

    1. User-Agent: FlutterApp
    2. Content-Type: application/json
    3. Accept-Language: en-US
    4. Cache-Control: no-cache

    Explanation: Content-Type: application/json explicitly tells the server that the request body contains JSON data. Accept-Language manages language preferences, Cache-Control deals with caching, and User-Agent identifies the client but does not specify content format.

  10. Using Query Parameters

    How can you include query parameters (like search terms or filters) in a Flutter GET request URL?

    1. By appending them in the URL after a question mark
    2. By declaring them as global variables
    3. By placing them in request headers
    4. By setting them in the HTTP body

    Explanation: Query parameters are appended to the URL after a question mark for GET requests. Placing them in the body or headers is improper for GET, and global variables do not influence the actual HTTP request.

  11. Avoiding Redundant API Calls

    What pattern can you use in Flutter to prevent making the same REST API call every time a widget rebuilds?

    1. Make repeated fetches inside setState
    2. Initialize data in the class constructor
    3. Fetch the API data in initState and store in state
    4. Call the API directly inside the build() method

    Explanation: Fetching data in initState and storing it avoids repeated network calls on widget rebuilds. Calling in the build method or setState may trigger multiple requests, while constructors are not ideal for asynchronous logic.

  12. Parsing Nested JSON Structures

    When decoding a JSON response with nested objects in Flutter, what is the recommended strategy to map the data to Dart objects?

    1. Only parse the top-level keys
    2. Create separate Dart classes for nested objects and use fromJson for each
    3. Use only primitive data types
    4. Flatten the JSON into a single map

    Explanation: Using separate Dart classes for nested structures and their own fromJson methods keeps code organized and manageable. Flattening loses structure, top-level parsing ignores inner data, and primitive types do not model complex objects.

  13. Refreshing Data from REST APIs

    Which Flutter widget is commonly used to implement pull-to-refresh functionality for updating data fetched from REST APIs?

    1. AppBar
    2. Drawer
    3. ListView.builder
    4. RefreshIndicator

    Explanation: RefreshIndicator provides a pull-to-refresh UI and triggers a callback to re-fetch data. ListView.builder displays lists, Drawer is for navigation, and AppBar shows app titles and actions, not refresh functionality.

  14. Handling Large JSON Responses

    If your Flutter app receives a very large JSON response, what can you do to avoid performance issues during decoding?

    1. Parse the JSON in a background isolate
    2. Encode the response twice
    3. Increase the UI refresh rate
    4. Use stateless widgets only

    Explanation: Decoding large JSON data off the main thread using an isolate prevents the UI from stalling. Increasing UI refresh rate or using only stateless widgets doesn't address main thread blocking, while encoding twice is unnecessary and wasteful.

  15. Managing API Authentication Tokens

    What is a common way to include authentication tokens when making secure API calls from a Flutter app?

    1. Store the token in plain text in the widget
    2. Add the token to the 'Authorization' header
    3. Send the token in the URL query only
    4. Omit the token for security

    Explanation: The Authorization header is the standard location for API tokens. Placing tokens in URLs can expose them in logs, storing tokens in widgets is insecure, and omitting tokens prevents authentication.

  16. Detecting Network Errors

    If a Flutter app displays a timeout error when connecting to an API, what is a possible cause?

    1. Duplicate header fields
    2. Null values in widgets
    3. Slow or unresponsive server
    4. Incorrect JSON format

    Explanation: A timeout usually indicates that the server is slow or unresponsive. Incorrect JSON format can cause parsing errors, duplicate headers might result in malformed requests, and null values in widgets trigger Flutter errors, not network timeouts.