Tuesday, June 18, 2024
Google search engine
HomeDevelopersRetrofit Implementation In Flutter

Retrofit Implementation In Flutter

Hello Everyone..!!!! Today we are learning about Retrofit In Flutter. In any mobile application, communication with the server to fetch the data or send the data to the server via API is a basic need in Retrofit.dart is a type conversion dio client generator using source_gen and inspired by Chopper and Retrofit.

If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.


Table Of Contents:

Introduction

Add Dependency

Implementation

Conclusion

GitHub Link



Introduction:-

Retrofit is a Dio client that makes consuming Rest APIs easier for us. Build runner is used for code generation in Dart, apart from the pub. JSON Serialization creates a model class from JSON data.

Almost in every Android and IOS, we have to use Rest API and Retrofit is best to arrange the API properly. For fetching the API we can also use many libraries but Retrofit is easy to use and has clean code.


Add Dependency:-

To add the dependency first you have open pubspec.ymal file and then add some dependencies,

cupertino_icons: ^1.0.2
retrofit: ^3.3.1
json_annotation: ^4.7.0

dev_dependencies:
flutter_test:
sdk: flutter
: ^2.3.2
retrofit_generator: ^4.2.0

we add retrofit, json_annotation, build_runner, and retrofit_generator. Retrofit is a dio client generator using source_gen, inspired by Chopper and Retrofit. JSON annotation is used to create code for JSON serialization and deserialization. Build Runner is the build system for Dart code generation and modular compilation. Retrofit Generator is a dio client generator using source_gen, inspired by Chopper and Retrofit.


Implementation:-

Welcome to my blog… Now we start the application, by creating a new flutter application. First, we have to create an abstract API request class.

@RestApi(baseUrl: "http://www.json-generator.com/api/json/get/")
abstract class RestClient {
factory RestClient(Dio dio) = _RestClient;
@GET("/ceLGCumWjS?indent=2")
Future<List<Post>> getTasks();
}

In this, we define baseUrl and then create a Rest-client abstract class in which we create _restclient which is dio type, and then use get because we use get API and call the list of API. RestClient class is responsible for handling all the network call methods. In the above code, it will show an error on the _RestClient variable, which will be resolved with steps we see later on in this post.


@JsonSerializable()
class Post{
int index;
String name;
String picture;
String gender;
int age;
String email;
String phone;
String company;

Post({
this.index,
this.name,
this.picture,
this.gender,
this.age,
this.email,
this.phone,
this.company});

factory Post.fromJson(Map<String, dynamic> json) => _$PostFromJson(json);
Map<String, dynamic> toJson() => _$PostToJson(this);
}

After that, we create our model class in which we pass all the data we want to fetch from the server(API).

After that, we have to run two commands by which we can create the g.dart class:

# dart
dart pub run build_runner build

# flutter
flutter pub run build_runner build

In the home. dart class, we create UI and call the API. In this, we create AppBar, passing the title and title’s style.

AppBar(
backgroundColor: Colors.blue[300],
centerTitle: true,
title: Text(
'Flutter Retrofit',
style: TextStyle(
fontSize: 25, color: Colors.white, fontWeight: FontWeight.bold),
),
),

After that, we create a FutureBuilder type method with the name _buildBody and pass BuildContext in this method. And pass the Post list in the FutureBuilder method. We call the RestClient by creating a client. And return the FutureBuilder.

FutureBuilder<List<Post>> _buildBody(BuildContext context) {
final client = RestClient(Dio(BaseOptions(contentType: "application/json")));
return FutureBuilder<List<Post>>(

future: client.getTasks(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
final List<Post> posts = snapshot.data!;
return _buildPosts(context, posts);
} else {
return Center(
child: CircularProgressIndicator(),
);
}
},
);
}

In this, we also call the _buildPosts method which is List-view. and return the ListView.Builder. In itemCount, we pass the length posts list. And in item builder, we return the Card and fetch the data from API.

ListView _buildPosts(BuildContext context, List<Post> posts) {
return ListView.builder(
itemCount: posts.length,
padding: EdgeInsets.all(8),
itemBuilder: (context, index) {
return Card(
elevation: 4,
child: ListTile(
title: Text(
posts[index].name,
style: TextStyle(fontWeight: FontWeight.bold),
),
subtitle: Text(posts[index].email),
leading: Column(
children: <Widget>[
Image.network(posts[index].picture,width: 50,height: 50,
),
],

),
),
);
},
);
}

Conclusion:

In this article, we learn how to implement Retrofit in Flutter Application. In this, we learn many things like how to create the model and how to generate g.dart file

❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


GitHub Link:

Find the source code of the RetroFit Application :

GitHub – flutter-devs/retrofit_demo
A new Flutter project. This project is a starting point for a Flutter application. A few resources to get you started…github.com


Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! For any flutter-related queries, you can connect with us on Facebook, GitHub, Twitter, and LinkedIn.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments