Flutter GetX - Fetching Data From OpenSea API

Pieces 🌟 - Feb 8 '23 - - Dev Community

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 and getx package in pubspec.yaml.
  2. Create a model based on your data.
  3. Create a GetX controller and make a network request using the http package.
  4. Display the data in an appropriate format.

First, let's start by adding the packages:

Code snippet with Flutter.

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

flutter pub get

Save to Pieces

Create a Model Based on Your Data:

You can use this website to create a DART model 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;
  }
}
Enter fullscreen mode Exit fullscreen mode

Save to Pieces

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.
  2. If the server returns a status code of 200, use the fromJSON() factory method to convert JSON Map into OpenSea model.
  3. 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);
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Save to Pieces

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';
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Save to Pieces

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

Output:

A screenshot of OpenSea API data returned in the browser.

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:

Full Source Code:

https://bit.ly/3NkrvkZ

Bonus Tip!

If you want to be more productive and grab the codes easily from any website, try Pieces. 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.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .