GetX Api Call | Flutter make network call using GetX

 

GetX Api Call :

GetX Api Call makes it much easier to fetch data in your flutter app, this tutorial will guide you through the basics of GetX Api call implementation.

Api calls are much needed in every app so as to provide much more services and make use of CRUD operations in database.

We will be fetch data from Getx Api Call like name, picture, email … and populate them onto the screen by making use of providers, controllers, data binding concepts.

If you are the beginner i suggest you to go through our video tutorials on youtube channel to get much more information in detail on GetX Api Call.

 

GetX Api Call Video Tutorial :

Go through the below tutorial for more interesting updates.

 

pubspec.yaml :

Add get library to your pubspec file so as to make use of the GetX library in flutter app.

dependencies:
  flutter:
    sdk: flutter
  get: ^4.3.4

 

main.dart:

We are initializing the GetX library here with GetMaterialApp so that we can make use GetX Api Call implementaion and more features in our app. Also we have specified initial route and pages so as to navigate to them as app loads.

 

import 'package:flutter/material.dart';
import 'package:flutter_fetch_data_getx/routes/route.dart';
import 'package:get/get.dart';

void main(){
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      initialRoute: '/data',
      getPages: Routes.routes
    );
  }
}

controller.dart:

With the help of a GetX Controller we are placing all our business logic in these classes, all the variables and methods are placed here and populated in view from here.

These class provide high performance by avoiding memory consumption issues without any extra effort by disposing them this will be done automatically without any manual effort.

Controller has onInit() and onClose() methods which can avoid StatefulWidget implementation and make us code much easier.

 

import 'package:flutter_fetch_data_getx/provider/provider.dart';
import 'package:get/get.dart';

class DataController extends GetxController with StateMixin<dynamic>{

  @override
  void onInit() {
    super.onInit();
    Provider().getUser().then((value) {
      change(value, status: RxStatus.success());
    },onError: (error){
      change(null,status: RxStatus.error(error.toString()));
    });
  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
  }
}

provider.dart :

With the help of provider we are making a GetX Api Call and fetch the data from the api specified.Once the data is fetched we can know the status of the response.

And according to the response we can move ahead with code implementations as stated below.

 

import 'package:get/get.dart';

class Provider extends GetConnect{

  Future<dynamic> getUser() async{
    final response = await get('http://www.json-generator.com/api/json/get/cfrJFXLTAO?indent=2');
    if(response.status.hasError){
      return Future.error(response.statusText!);
    } else {
      return response.body;
    }
  }

}

databinding.dart :

We are binding our dependency’s here like data controller so that we can use them to populate data onto screen, we are making use of Get.lazy put to avoid multiple creations of instances.

Once the route is re-created we will not re create dependency rather than use the same available data.

When you have multiple screens and their controller’s can specify them here.

 

import 'package:flutter_fetch_data_getx/controller/datacontroller.dart';
import 'package:get/get.dart';

class DataBinding extends Bindings{
  @override
  void dependencies() {
    Get.lazyPut(() => DataController());
  }

}

route.dart :

This screen helps us to navigate from one screen to another currently we have only one screen so specified the same with it’s bindings too.

 

import 'package:flutter_fetch_data_getx/bindings/databinding.dart';
import 'package:flutter_fetch_data_getx/data.dart';
import 'package:get/get.dart';

class Routes{

  static final routes = [

    GetPage(
      name: '/data',
      page: () => Data(),
      binding: DataBinding(),
    ),


  ];
}

data.dart :

And finally we are making use of the above data which we fetched from GetX api call and we are populating it to the screen as below.

 

import 'package:flutter/material.dart';
import 'package:flutter_fetch_data_getx/controller/datacontroller.dart';
import 'package:get/get.dart';

class Data extends GetView<DataController> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('GetX Network Call'),
      ),
      body: controller.obx(
          (data) => Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                CircleAvatar(
                  radius: 80,
                  backgroundImage: NetworkImage(data['picture']),
                ),
                SizedBox(height: 20.0,),
                Text(data['name']),
                SizedBox(height: 10.0,),
                Text(data['email']),
                SizedBox(height: 10.0,),
                Text(data['company']),

              ],
            ),
          )
      ),
    );
  }
}

Getx Api Call Output :

The screen below depicts the usage of Api Call implementation.

getx api call

If you have any query’s in this tutorial on GetX Api Call implementation do let us know in the comment section below.If you like this tutorial do like and share us for more interesting updates.

 

Show Buttons
Hide Buttons