![]() |
VOOZH | about |
In today's world, most applications heavily rely on fetching and updating information from the servers through the internet. In Flutter, such services are provided by the http package. In this article, we will explore the same. Let's see a sample video of what we are going to develop.
Sample Video:
Create a new Flutter application using the command Prompt. To create a new app, write the following command and run it.
flutter create app_nameTo know more about it refer this article: Creating a Simple Application in Flutter
To add the dependency to the pubspec.yaml file, add http as a dependency in the dependencies part of the pubspec.yaml file, as shown below:
Now, run the command below in the terminal.
flutter pub getOr
Run the command below in the terminal.
flutter pub add httpTo use libraries, import all of them in the respective .dart file.
import 'package:http/http.dart' as http;-
Use the http.put() method to update the title of the Album in JSONPlaceholder as shown below:
-
Though making a network request is no big deal, working with the raw response data can be inconvenient. To make your life easier, convert the raw data (ie, http.response) into a Dart object. Here we will create an Album class that contains the JSON data as shown below:
Now, follow the steps below to update the fetchAlbum() function to return a Future<Album>:
-
Now use the fetch() method to fetch the data as shown below:
-
Now create a TextField for the user to enter a title and a RaisedButton to send data to the server. Also, define a TextEditingController to read the user input from a TextField as shown below:
-
Use the FlutterBuilder widget to display the data on the screen as shown below:
Output: