|
| 1 | +# Flutter Networking: Answers |
| 2 | + |
| 3 | +1. **What is the http package used for in Flutter?** |
| 4 | + The `http` package is used to make HTTP requests to APIs, allowing Flutter apps to communicate with web services. |
| 5 | + |
| 6 | +2. **How do you make a GET request using the http package?** |
| 7 | + You can make a GET request using the following code: |
| 8 | + |
| 9 | + ```dart |
| 10 | + import 'package:http/http.dart' as http; |
| 11 | +
|
| 12 | + Future<void> fetchData() async { |
| 13 | + final response = await http.get(Uri.parse('https://api.example.com/data')); |
| 14 | + if (response.statusCode == 200) { |
| 15 | + // Process the response |
| 16 | + } else { |
| 17 | + throw Exception('Failed to load data'); |
| 18 | + } |
| 19 | + } |
| 20 | + ``` |
| 21 | + |
| 22 | +3. **How do you handle errors when making API calls?** |
| 23 | + Use a try-catch block to handle errors and check the response status code. For example: |
| 24 | + |
| 25 | + ```dart |
| 26 | + try { |
| 27 | + final response = await http.get(Uri.parse('https://api.example.com/data')); |
| 28 | + if (response.statusCode != 200) { |
| 29 | + throw Exception('Failed to load data'); |
| 30 | + } |
| 31 | + } catch (error) { |
| 32 | + // Handle error |
| 33 | + } |
| 34 | + ``` |
| 35 | + |
| 36 | +4. **What is the difference between GET and POST requests?** |
| 37 | + GET requests retrieve data from the server, while POST requests send data to the server. GET requests include parameters in the URL, whereas POST requests include data in the body. |
| 38 | + |
| 39 | +5. **How can you send JSON data in a POST request?** |
| 40 | + You can send JSON data by encoding the data and specifying the content type: |
| 41 | + |
| 42 | + ```dart |
| 43 | + import 'dart:convert'; |
| 44 | +
|
| 45 | + Future<void> postData() async { |
| 46 | + final response = await http.post( |
| 47 | + Uri.parse('https://api.example.com/data'), |
| 48 | + headers: {'Content-Type': 'application/json'}, |
| 49 | + body: json.encode({'key': 'value'}), |
| 50 | + ); |
| 51 | + } |
| 52 | + ``` |
| 53 | + |
| 54 | +6. **What are headers, and how do you use them in requests?** |
| 55 | + Headers are key-value pairs sent with HTTP requests to provide additional information. You can specify headers in a request like this: |
| 56 | + |
| 57 | + ```dart |
| 58 | + final response = await http.get( |
| 59 | + Uri.parse('https://api.example.com/data'), |
| 60 | + headers: {'Authorization': 'Bearer token'}, |
| 61 | + ); |
| 62 | + ``` |
| 63 | + |
| 64 | +7. **How do you handle response data from an API call?** |
| 65 | + You can handle response data by decoding it and converting it into a model: |
| 66 | + |
| 67 | + ```dart |
| 68 | + if (response.statusCode == 200) { |
| 69 | + final data = json.decode(response.body); |
| 70 | + // Convert data to model |
| 71 | + } |
| 72 | + ``` |
| 73 | + |
| 74 | +8. **What is the purpose of the Dio package?** |
| 75 | + Dio is a powerful HTTP client for Dart that provides advanced features like interceptors, request cancellation, file downloading, and more. |
| 76 | + |
| 77 | +9. **How do you implement request timeouts using Dio?** |
| 78 | + You can set a timeout when creating the Dio instance: |
| 79 | + |
| 80 | + ```dart |
| 81 | + Dio dio = Dio(BaseOptions( |
| 82 | + connectTimeout: 5000, // 5 seconds |
| 83 | + receiveTimeout: 3000, // 3 seconds |
| 84 | + )); |
| 85 | + ``` |
| 86 | + |
| 87 | +10. **How can you handle pagination in API responses?** |
| 88 | + You can handle pagination by sending parameters for the page and limit in your API requests: |
| 89 | + |
| 90 | + ```dart |
| 91 | + final response = await http.get( |
| 92 | + Uri.parse('https://api.example.com/data?page=1&limit=10'), |
| 93 | + ); |
| 94 | + ``` |
| 95 | +
|
| 96 | +11. **What is the role of the connectivity package?** |
| 97 | + The `connectivity` package is used to check the network connectivity status of the device, allowing you to determine if the app can access the internet. |
| 98 | +
|
| 99 | +12. **How do you perform a PUT request using the http package?** |
| 100 | + You can perform a PUT request like this: |
| 101 | +
|
| 102 | + ```dart |
| 103 | + final response = await http.put( |
| 104 | + Uri.parse('https://api.example.com/data/1'), |
| 105 | + headers: {'Content-Type': 'application/json'}, |
| 106 | + body: json.encode({'key': 'new value'}), |
| 107 | + ); |
| 108 | + ``` |
| 109 | +
|
| 110 | +13. **What are interceptors in Dio, and how are they used?** |
| 111 | + Interceptors in Dio allow you to intercept requests and responses before they are processed, useful for logging, modifying requests, or handling errors. |
| 112 | +
|
| 113 | +14. **How do you download files using Dio?** |
| 114 | + You can download files using Dio’s `download` method: |
| 115 | +
|
| 116 | + ```dart |
| 117 | + await dio.download('https://example.com/file.pdf', 'local/path/file.pdf'); |
| 118 | + ``` |
| 119 | +
|
| 120 | +15. **How do you upload files using http?** |
| 121 | + You can upload files using the `http.MultipartRequest` class: |
| 122 | +
|
| 123 | + ```dart |
| 124 | + var request = http.MultipartRequest('POST', Uri.parse('https://api.example.com/upload')); |
| 125 | + request.files.add(await http.MultipartFile.fromPath('file', 'path/to/file')); |
| 126 | + final response = await request.send(); |
| 127 | + ``` |
| 128 | +
|
| 129 | +16. **What is the purpose of the flutter_secure_storage package in networking?** |
| 130 | + The `flutter_secure_storage` package is used to securely store sensitive data, such as API tokens, ensuring they are not exposed. |
| 131 | +
|
| 132 | +17. **How do you cancel a network request in Dio?** |
| 133 | + You can cancel requests by using a `CancelToken`: |
| 134 | +
|
| 135 | + ```dart |
| 136 | + CancelToken cancelToken = CancelToken(); |
| 137 | + dio.get('https://api.example.com/data', cancelToken: cancelToken); |
| 138 | + cancelToken.cancel('Request canceled'); |
| 139 | + ``` |
| 140 | +
|
| 141 | +18. **What is the difference between synchronous and asynchronous HTTP requests?** |
| 142 | + Synchronous requests block the execution until a response is received, while asynchronous requests allow the program to continue running while waiting for the response. |
| 143 | +
|
| 144 | +19. **How do you create a custom HTTP client with Dio?** |
| 145 | + You can create a custom HTTP client by extending the Dio class and adding custom functionality as needed. |
| 146 | +
|
| 147 | +20. **How do you test network calls in Flutter?** |
| 148 | + You can test network calls by using mock HTTP responses with packages like `http_mock_adapter` or `mockito`. |
| 149 | +
|
| 150 | +21. **What is the significance of status codes in HTTP?** |
| 151 | + Status codes indicate the result of an HTTP request, helping you understand if the request was successful or if there was an error (e.g., 200 for success, 404 for not found). |
| 152 | +
|
| 153 | +22. **How do you handle SSL pinning in Flutter?** |
| 154 | + SSL pinning can be implemented using the `flutter_ssl_pinning` package to validate the server's SSL certificate. |
| 155 | +
|
| 156 | +23. **What are WebSockets, and how can they be used in Flutter?** |
| 157 | + WebSockets provide a full-duplex communication channel over a single TCP connection, allowing real-time data transfer in Flutter apps. |
| 158 | +
|
| 159 | +24. **How do you use GraphQL in Flutter?** |
| 160 | + You can use the `graphql_flutter` package to interact with GraphQL APIs, enabling queries and mutations. |
| 161 | +
|
| 162 | +25. **What is the purpose of using the http package’s Request class?** |
| 163 | + The `Request` class allows you to create more complex HTTP requests, providing more control over the request configuration. |
| 164 | +
|
| 165 | +26. **How do you implement caching for API responses?** |
| 166 | + You can implement caching by storing responses in local storage and checking for cached data before making a new request. |
| 167 | +
|
| 168 | +27. **What is the json_serializable package, and how is it used?** |
| 169 | + The `json_serializable` package automates JSON serialization and deserialization, simplifying the conversion of model classes. |
| 170 | +
|
| 171 | +28. **How can you monitor network activity in Flutter?** |
| 172 | + You can monitor network activity by using logging interceptors in Dio or by integrating tools like Flipper. |
| 173 | +
|
| 174 | +29. **What are some best practices for making network requests in Flutter?** |
| 175 | + - Use asynchronous programming. |
| 176 | + - Handle errors gracefully. |
| 177 | + - Implement caching where appropriate. |
| 178 | + - Secure sensitive data. |
| 179 | +
|
| 180 | +30. **How do you parse XML data from an API in Flutter?** |
| 181 | + You can use the `xml` package to parse XML data into a manageable format: |
| 182 | +
|
| 183 | + ```dart |
| 184 | + import 'package:xml/xml.dart'; |
| 185 | +
|
| 186 | + var document = XmlDocument.parse(response.body); |
| 187 | + ``` |
| 188 | +
|
| 189 | +31. **How do you authenticate API requests using tokens?** |
| 190 | + You can include tokens in the headers of your requests: |
| 191 | +
|
| 192 | + ```dart |
| 193 | + headers: {'Authorization': 'Bearer your_token'}, |
| 194 | + ``` |
| 195 | +
|
| 196 | +32. **What is the difference between http.get() and http.read()?** |
| 197 | + `http.get()` retrieves the full response including headers, while `http.read()` retrieves only the response body. |
| 198 | +
|
| 199 | +33. **How do you refresh tokens in a Flutter app?** |
| 200 | + You can refresh tokens by making a request to a refresh endpoint using the existing refresh token. |
| 201 | +
|
| 202 | +34. **How do you implement retry logic for network requests?** |
| 203 | + You can implement retry logic using a loop with a delay or using Dio's retry interceptor. |
| 204 | +
|
| 205 | +35. **How can you use async and await for networking calls?** |
| 206 | + Use the `async` keyword in your function signature and the `await` keyword before the network call: |
| 207 | +
|
| 208 | + ```dart |
| 209 | + Future<void> fetchData() async { |
| 210 | + final response = await http.get(Uri.parse('https://api.example.com/data')); |
| 211 | + } |
| 212 | + ``` |
| 213 | +
|
| 214 | +36. **What is the purpose of the http.Response class?** |
| 215 | + The `http.Response` class represents the response from an HTTP request, including the status code, headers, and body. |
| 216 | +
|
| 217 | +37. **How do you use query parameters in a GET request?** |
| 218 | + You can add query parameters using the `Uri` constructor: |
| 219 | +
|
| 220 | + ```dart |
| 221 | + final response = await http.get(Uri.parse('https://api.example.com/data?param=value')); |
| 222 | + ``` |
| 223 | +
|
| 224 | +38. **How can you handle multipart requests in Flutter?** |
| 225 | + You can handle multipart requests using the `http.MultipartRequest` class, which allows you to send files along with other data. |
| 226 | +
|
| 227 | +39. **What is the role of the http.MultipartFile class?** |
| 228 | + The `http.Multipart |
| 229 | +
|
| 230 | +File` class is used to represent files in multipart requests, allowing you to upload files to a server. |
| 231 | +
|
| 232 | +40. **How do you set default headers for all requests in Dio?** |
| 233 | + You can set default headers in the Dio instance like this: |
| 234 | +
|
| 235 | + ```dart |
| 236 | + Dio dio = Dio(BaseOptions(headers: {'Authorization': 'Bearer token'})); |
| 237 | + ``` |
| 238 | +
|
| 239 | +41. **How can you convert a response body to a model object?** |
| 240 | + You can decode the JSON response and use a factory constructor to create a model object: |
| 241 | +
|
| 242 | + ```dart |
| 243 | + final data = json.decode(response.body); |
| 244 | + MyModel myModel = MyModel.fromJson(data); |
| 245 | + ``` |
| 246 | +
|
| 247 | +42. **What are some common security measures when making network requests?** |
| 248 | + - Use HTTPS to encrypt data. |
| 249 | + - Validate SSL certificates. |
| 250 | + - Store sensitive data securely. |
| 251 | +
|
| 252 | +43. **How do you handle network connectivity issues in your app?** |
| 253 | + You can use the connectivity package to check for network status and display messages to the user. |
| 254 | +
|
| 255 | +44. **What is the role of the http.Client class?** |
| 256 | + The `http.Client` class provides a way to make HTTP requests and manage connections, allowing you to implement custom behavior. |
| 257 | +
|
| 258 | +45. **How can you create a REST API client in Flutter?** |
| 259 | + You can create a REST API client by wrapping HTTP calls in a class and providing methods for each endpoint. |
| 260 | +
|
| 261 | +46. **What are the limitations of using the http package?** |
| 262 | + The `http` package lacks advanced features like interceptors, cancellation, and custom response handling compared to packages like Dio. |
| 263 | +
|
| 264 | +47. **How do you implement OAuth 2.0 in a Flutter app?** |
| 265 | + You can implement OAuth 2.0 by using the authorization code flow, redirecting users to the login page, and exchanging the code for tokens. |
| 266 | +
|
| 267 | +48. **What is the retrofit package, and how does it help with networking?** |
| 268 | + Retrofit is a type-safe HTTP client that simplifies API requests by defining methods for API endpoints using annotations. |
| 269 | +
|
| 270 | +49. **How can you log HTTP requests and responses for debugging?** |
| 271 | + You can log requests and responses using Dio interceptors or by implementing logging in your API client. |
| 272 | +
|
| 273 | +50. **How do you use flutter_bloc with networking for state management?** |
| 274 | + You can use `flutter_bloc` to manage the state of your network requests, handling loading, success, and error states in a structured manner. |
0 commit comments