Flutter show loading when call api

Sure! Here’s an example of how you can display a loading indicator in Flutter while making an API call.

“`html

“`

Explanation:

1. We have a container `div` to hold our loading indicator, result section, and a button for triggering the API call.
2. Inside the container `div`, we have two child `div` elements: `loading` and `result`. The `loading` div initially set to `display: none`, and we show it when the API call starts. The `result` div also initially set to `display: none`, and we show it when the API call is successfully completed.
3. Inside the `loading` div, we have a `span` element with the text “Loading…”. You can style this div to match your desired loading indicator UI.
4. Inside the `result` div, we have another `span` element with the id `data`. This is where we will display the result of the API call.
5. We also have a button with an `onclick` event listener that triggers the `callApi` JavaScript function.
6. In the `callApi` function, we first get references to the loading and result elements using `getElementById`.
7. We display the loading indicator by setting the `display` property of the loading div to “block”.
8. We make the API call using the `fetch` function. You should replace `”https://your-api-endpoint”` with the actual URL of your API.
9. Once the API call is successful, we hide the loading indicator and display the result section by setting their `display` properties accordingly. We also update the `innerText` property of the `dataSpan` with the received data.
10. Finally, we handle any error that may occur during the API call by catching and logging them to the console.

You can further customize the loading indicator and the result section according to your UI requirements.

Leave a comment