Introduction
Working with data is a crucial part of development whether it comes from a network or from the app storage.
Different sources of Data are:
-
Local JSON data
- Put the JSON in the assets folder
- Update the pubspec.yaml
- Access the JSON using
rootBundle.loadString('path')
- The data we get will be in string format to convert it into JSON use
json.decode
and to convert the json to string use json.encode
- Once the data is received in JSON format map it into the modal (Class) and use it in the app. (JSON Serialization)
-
Data from API
- Get the url of the API
- Use http package (or any other http client like chopper) to fetch the response from the url and store it in a variable
- Map the data into our modal (Class) and use it in the app (JSON Serialization).
- In addition to creating the service, on Android you need to add the permission to access the internet.
- This is considered a “safe” permission and doesn’t require the user to approve it.
<aside>
💡 When you create your project, Android Studio automatically add the permission to the debug version of the AndroidManifest.xml file. For the release version, you’ll need to add the same permission manually.
</aside>
chopper
is a good package to perform Network requests, http
package is easy to use to handle network calls, but it’s also pretty basic. Chopper does a lot more.
- It generates code to simplify the development of networking code.
- It allows you to organize that code in a modular way, so it’s easier to change and reason about
- Similar libraries in native development are
Retrofit
for Android and AlamoFire
for iOS.
- To log network calls we can use
logging
package.
Interceptors
can intercept both requests and responses and change those values.
Converters
can modify requests and responses.
<aside>
💡 Modals are basically the blueprint of our data. A class which we used to map fetched data on and use in our app.
</aside>
Dealing with Asynchrounous Data
FutureBuilder
is a widget that retrieves information from a Future.
- Whenever we work with asyn function or data that will come in the future using future builder is a good choice for that.
Stream sends data events for a listener to grab.
- With Dart streams, you can send one data event at a time while other parts of your app listen for those events.
- Such events can be collections, maps or any other type of data you’ve created.
- Streams can send errors in addition to data; you can also stop the stream, if you need to.