Flutter GetX - Fetching Data From OpenSea API
Tags: flutter, api
Published: 2023-02-08 16:45:57

This is a step-by-step tutorial that will walk you through the process of retrieving data from an OpenSea API using Flutter and GetX.

## What is Flutter GetX?

Flutter has numerous state management components, including Provider, GetX, Bloc, Riverpod, Mobx, and others. GetX, however, is more than just a state management library; it is also a micro-framework that combines dependency injection and route management. GetX provides a top-notch development experience in a lightweight yet effective Flutter solution.

## To Get Data from an OpenSea API Using GetX, Follow These Steps:

1. Add the [HTTP package](https://pub.dev/packages/http) and [getx package](https://pub.dev/packages/get) in `pubspec.yaml`.
1. Create a model based on your data.
1. Create a GetX controller and make a network request using the http package.
1. Display the data in an appropriate format.


First, let's start by adding the packages:

<figure><img src="https://d37oebn0w9ir6a.cloudfront.net/account_32099/image2_8d7201cf6c9bd88973f42d2a2efc2e21.png" alt="Code snippet with Flutter."/></figure>

Now, use the following Flutter GetX CLI command in your command prompt to install the packages:

`flutter pub get`

[Save to Pieces](https://amanullah.pieces.cloud/?p=8a7e48a554)

### Create a Model Based on Your Data:

You can use this website to [create a DART model](https://jsontodart.com/) from your JSON data.

Next, you’ll be creating an `OpenseaModel` class that contains the JSON data as shown below:

```
class OpenseaModel {
  OpenseaModel({
    required this.assets,
  });

  List<Assets>? assets;

  OpenseaModel.fromJson(Map<String, dynamic> json) {
    assets = List.from(json['assets']).map((e) => Assets.fromJson(e)).toList();
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['assets'] = assets!.map((e) => e.toJson()).toList();
    return _data;
  }
}

class Assets {
  Assets({
    required this.imageUrl,
    required this.name,
    this.description,
    required this.permalink,
  });

  String? imageUrl;
  String? name;
  String? description;
  String? permalink;

  Assets.fromJson(Map<String, dynamic> json) {
    imageUrl = json['image_url'];
    name = json['name'];
    description = null;
    permalink = json['permalink'];
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['image_url'] = imageUrl;
    _data['name'] = name;
    _data['description'] = description;
    _data['permalink'] = permalink;
    return _data;
  }
}
```

[Save to Pieces](https://amanullah.pieces.cloud/?p=b97c4fb8bf)

## Create a Flutter GetX Controller and make a Network Request Using the HTTP Package:

Now, follow the steps below to create a Flutter GetX controller and fetch the data into the OpenSea model:

1. Convert the response body to a JSON Map using the dart: convert package.
1. If the server returns a status code of 200, use the fromJSON() factory method to convert JSON Map into OpenSea model.
1. Throw an exception if the server does not respond with an OK status code of 200.


Here, we called `fetchData()` in the `onInit()` method, which will call the method whenever we create an instance of our controller.

```
import 'dart:convert';

import 'package:get/get.dart';
import 'package:getx_tutorials/models/opensea_model.dart';
import 'package:http/http.dart' as http;

class OpenseaController extends GetxController {
  var isLoading = false.obs;
  OpenseaModel? openseaModel;

  @override
  Future<void> onInit() async {
    super.onInit();
    fetchData();
  }

  fetchData() async {
    try {
      isLoading(true);
      http.Response response = await http.get(Uri.tryParse(
          'https://api.opensea.io/api/v1/assets?collection=cryptopunks')!);
      if (response.statusCode == 200) {
        ///data successfully
        var result = jsonDecode(response.body);

        openseaModel = OpenseaModel.fromJson(result);
      } else {
        print('error fetching data');
      }
    } catch (e) {
      print('Error while getting data is $e');
    } finally {
      isLoading(false);
    }
  }
}
```

[Save to Pieces](https://amanullah.pieces.cloud/?p=3d6846bee6)

### Display the Data in an Appropriate Format:

Now, on our home screen, we create an instance of our controller as well as a list view to display the data we retrieved from the OpenSea API.

```
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_tutorials/controllers/opensea_controller.dart';
import 'package:url_launcher/url_launcher.dart';

main() {
  runApp(GetMaterialApp(home: MyApp()));
}

class MyApp extends StatelessWidget {
  OpenseaController openseaController = Get.put(OpenseaController());
 
 @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('opensea Api')),
        body: Obx(
      () => openseaController.isLoading.value
          ? Center(
              child: CircularProgressIndicator(),
            )
          : ListView.builder(
              itemCount: openseaController.openseaModel?.assets?.length ?? 0,
              itemBuilder: (context, index) {
                return ListTile(
                    title: Text(
                        openseaController.openseaModel?.assets![index].name ??
                            'no name'),
                    subtitle: Text(openseaController
                            .openseaModel?.assets![index].description ??
                        'no description'),
                    leading: openseaController
                                .openseaModel?.assets![index].imageUrl ==
                            null
                        ? Icon(Icons.image)
                        : Image.network(openseaController
                            .openseaModel!.assets![index].imageUrl!),
                    onTap: () {
                      _launchInBrowser(Uri.parse(openseaController
                          .openseaModel!.assets![index].permalink!));
                    });
              }),
    ));
  }

  Future<void> _launchInBrowser(Uri url) async {
    if (!await launchUrl(
      url,
      mode: LaunchMode.externalApplication,
    )) {
      throw 'Could not launch $url';
    }
  }
}
```

[Save to Pieces](https://amanullah.pieces.cloud/?p=4ebd4cbbe4)

Also, there is a `_launchInBrowser()`method that will open your images link in the browser.

**Output:**

<figure><img src="https://d37oebn0w9ir6a.cloudfront.net/account_32099/image_f5d273aa10090f0519efd3ee2f85112c.png" alt="A screenshot of OpenSea API data returned in the browser. "/></figure>

## Conclusion

In this article, you learned how to use Flutter and GetX to Fetch data from an OpenSea API. We began by importing packages, then generated a model for our JSON. After that, we created a controller file to retrieve data from the OpenSea API. Finally, the data was displayed in a list view.

### Follow this Tutorial on YouTube:

{% embed https://www.youtube.com/watch?v=Hjv0n_Qp9lQ&list=PLrTDw7ICfHFkvOFW_AERUTUbpmIPFccjS&index=3 %}

**Full Source Code:**

[https://bit.ly/3NkrvkZ](https://bit.ly/3NkrvkZ)

### Bonus Tip!

If you want to be more productive and grab the codes easily from any website, [try Pieces](https://code.pieces.app/install). It allows you to save snippets in one-click from the web or your editor, and it auto-saves your frequently used code. Pieces also recommends snippets with Framework standards, saves snippets from screenshots, and much more.