Build an Image Gallery in Flutter with Headless Oracle Content Management

Introduction

Flutter is an open source framework by Google for building beautiful, natively compiled, multi-platform applications from a single codebase. Flutter code compiles to ARM or Intel machine code as well as JavaScript, for fast performance on any device. Flutter can be a powerful tool for building applications that consume content from Oracle Content Management. Armed with the right content model, you can quickly build Flutter UI that make up a typical gallery.

In this tutorial, we’ll build a simple gallery in Flutter by leveraging Oracle Content Management as a headless CMS. This Flutter sample is available on GitHub.

The tutorial consists of three steps:

  1. Prepare Oracle Content Management
  2. Build the Image Gallery in Flutter
  3. Prepare your application for deployment

Prerequisites

Before proceeding with this tutorial, we recommend that you read the following information first:

To follow this tutorial, you’ll need:

What We’re Building

Our image gallery will consist of several screens of images of food and drinks available at a coffee shop.

This image shows an image gallery with different kinds of bagels, some with cream or toppings, or both.

Categories are child nodes of a taxonomy and can be organized into hierarchies. For our image gallery, we want to show all available categories regardless of the organization. To accomplish this, we first need to find the available taxonomies, which we do using the REST API resource GET /published/api/v1.1/taxonomies.

Next, we need to get the set of categories for each of the taxonomies. This is done using the REST API GET /published/api/v1.1/taxonomies/{id}/categories.

To build the preview of a category, such as Bagels, we need to get a count of the number of images and the URLs of the first four images.

This image shows images in the Breakfast category.

Our request to find the published assets in the category specifies the category criteria through a query string, as follows:

"(taxonomies.categories.nodes.id eq 892CD6BC4F654249A00CB7942EE8C773)"

Note: In addition to publishing the digital assets that we want to view, you also need to publish the taxonomies to the channel.

To proceed, you’ll need to have an active subscription to Oracle Content Management and be logged in with the Content Administrator role.

Task 1: Prepare Oracle Content Management

This tutorial is based on the assumption that you’ve created your asset repository and currently have an empty content model (that is, no content types created).

If you don’t already have an Oracle Content Management instance, see the Quick Start to learn how to register for Oracle Cloud, provision an Oracle Content Management instance, and configure Oracle Content Management as a headless CMS.

For this tutorial, you’ll need to create a content model in either of two ways. There’s a downloadable asset pack available that will fill your empty repository with content types and associated content, or you can create your own content model and content.

To prepare Oracle Content Management:

  1. Create a channel and asset repository.
  2. Import the Oracle Content Management Samples Asset Pack
  3. Upload Your Own Image Assets
  4. Create Taxonomies and Link Them to Image Assets

Create a Channel and Asset Repository

You first need to create a channel and an asset repository in Oracle Content Management so you can publish content.

To create a channel and an asset repository in Oracle Content Management:

  1. Log in to the Oracle Content Management web interface as an administrator.

  2. Choose Content in the left navigation menu and then choose Publishing Channels from the selection list in the page header.

    This image shows the Publishing Channels option selected in the dropdown menu in the Content page header.

  3. In the upper right corner, click Create to create a new channel. Name the channel ‘OCEImageGalleryChannel’ for the purpose of this tutorial, and keep the access public. Click Save to create the channel.

    This image shows the publishing channel definition panel, with ‘OCEImageGalleryChannel’ in the channel name field.

  4. Choose Content in the left navigation menu and then choose Repositories from the selection list in the page header.

    This image shows the Repositories option selected in the dropdown menu in the Content page header.

  5. In the upper right corner, click Create to create a new asset repository. Name the asset repository ‘OCEImageGalleryRepository’ for the purpose of this tutorial.

    This image shows the repository definition panel, with ’ OCEImageGalleryRepository ’ in the repository name field.

  6. In the Publishing Channels field, select OCEImageGalleryChannel to indicate to Oracle Content Management that content in the OCEImageGalleryRepository repository can be published to the OCEImageGalleryChannel channel. Click Save when you’re done.

    This image shows the repository definition panel, with ‘OCEImageGalleryChannel’ in the Publishing Channels field.

Import the Oracle Content Management Samples Asset Pack

You can download a preconfigured Oracle Content Management sample assets pack that contains all required content types and assets for this tutorial.

You can upload a copy of the content we’re using in this tutorial from the Oracle Content Management Samples Asset Pack. This will let you experiment with the content types and modify the content. You can download the asset pack archive, OCESamplesAssetPack.zip, and extract it to a directory of your choice:

  1. Download the Oracle Content Management Samples Asset Pack (OCESamplesAssetPack.zip) from the Oracle Content Management downloads page. Extract the downloaded zip file to a location on your computer. After extraction, this location will include a file called OCEImageGallery_data.zip.

  2. Log in to the Oracle Content Management web interface as an administrator.

  3. Choose Content in the left navigation menu and then choose Repositories from the selection list in the page header. Now select OCEImageGalleryRepository and click the Import Content button in the top action bar.

    This image shows the Repositories page, with the OCEImageGalleryRepository item selected.

  4. Upload OCEImageGallery_data.zip from your local computer to the Documents folder.

    This image shows the upload confirmation screen for the OCEImageGallery_data.zip file.

  5. Once it’s uploaded, select OCEImageGallery_data.zip and click OK to import the contents into your asset repository.

    This image shows the selected OCEImageGallery_data.zip file with the OK button enabled.

  6. After the content has been imported successfully, navigate to the Assets page and open the OCEImageGalleryRepository repository. You’ll see that all the related images and content items have now been added to the asset repository.

    This image shows the OCEGettingStartedRepository repository, with all assets that were just imported.

  7. Click Select All on the top left and then Publish to add all the imported assets to the publishing channel that you created earlier, OCEImageGalleryChannel.

    This image shows the OCEImageGalleryRepository repository, with all assets selected and the Publish option in the action bar visible.

  8. Before publishing, you need to validate all the assets. First add OCEImageGalleryChannel as a selected channel, and then click the Validate button.

    This image shows the Validation Results page, with the OCEImageGalleryChannel channel added in the Channels field, all assets to be validated, and the Validate button enabled.

  9. After the assets have been validated, you can publish all the assets to the selected channel by clicking the Publish button in the top right corner.

    This image shows the Validation Results page, with the OCEImageGalleryChannel channel added in the Channels field, all assets validated, and the Publish button enabled.

Once that’s done, you can see on the Assets page that all assets have been published. (You can tell by the icon above the asset name.)

This image shows the Assets page, with all assets pubished.

After importing the Oracle Content Management Samples Asset Pack, you can start building the image gallery in Flutter.

Upload Your Own Image Assets

For this tutorial, we’re using an asset repository called ‘OCEImageGalleryRepository’ to build the home page for our gallery site. This home page consists of the title ‘Image Gallery’ as well as image collection albums that have image assets inside.

This image shows the home page for the image gallery, with images of various image categories: sandwiches, drinks, dessert, breakfast, and food.

To add image assets to the gallery asset repository:

  1. Log in to the Oracle Content Management web interface.

  2. Click Assets in the left navigation menu.

  3. Open the OCEImageGalleryRepository repository.

  4. Click Add in the upper right corner of the page to add image assets to the gallery asset repository.

    This image shows the Assets page with content and the Add dropdown menu opened, showing two options: Add from Documents and Add from this computer.

  5. Upload your own new assets from your local computer or choose existing assets already in Oracle Content Management.

You need to create a taxonomy in Oracle Content Management and then assign categories to the assets in your repository.

To create a taxonomy in Oracle Content Management:

  1. Log in to the Oracle Content Management web interface as an administrator.

  2. Choose Content in the left navigation menu and then choose Taxonomies from the selection list in the page header.

    This image shows the Taxonomies option selected in the dropdown menu in the Content page header.

  3. In the upper right corner, click Create to create a new taxonomy. Name the channel ‘OCEImageGalleryTaxonomy’ for the purpose of this tutorial.

    This image shows the taxonomy definition panel, with ‘OCEImageGalleryTaxonomy’ in the taxonomy name field.

  4. Click Create.

  5. Now build your taxonomy by adding categories. Click Add a category.

    This image shows the Add Category page for the ‘OCEImageGalleryTaxonomy’ taxonomy.

  6. Name the parent category item ‘Food’, and add the following child categories:

    • Breakfast
    • Dessert
    • Drinks
    • Sandwiches

    Click Done at the top right of the screen.

    This image shows the category definition page, with ‘Food’ as the parent category and these child categories: Breakfast, Dessert, Drinks, and Sandwiches.

  7. On the Taxonomies page, select the OCEImageGalleryTaxonomy taxonomy and click Promote in the actions bar to make it available for use in your asset repositories.

    This image shows the OCEImageGalleryTaxonomy taxonomy selected in the list, with the Promote option in the action bar visible.

Next, edit the OCEImageGalleryRepository repository to enable the OCEImageGalleryTaxonomy taxonomy for that repository:

  1. Log in to the Oracle Content Management web interface as an administrator.

  2. Choose Content in the left navigation menu and then choose Repositories from the selection list in the page header.

  3. Select and edit the OCEImageGalleryRepository repository.

  4. In the Taxonomies field, select OCEImageGalleryTaxonomy, so you can assign categories from that taxonomy to the assets in the OCEImageGalleryRepository repository.

    This image shows the repository definition panel, with ‘OCEImageGalleryTaxonomy’ in the Taxonomies field.

  5. Click Save.

Then, assign taxonomy categories to each of the image assets in the OCEImageGalleryRepository repository:

  1. Log in to the Oracle Content Management web interface.

  2. Click Assets in the left navigation menu.

  3. Open the OCEImageGalleryRepository repository.

  4. Select one or more image assets, click More in the actions bar, and then choose Categories from the menu.

    This image shows a selected asset in the the OCEImageGalleryRepository repository, with the More selection menu displayed (including the Categories option).

  5. In the Categories panel, click Add Category. Search for the category name in the search bar or select a category from the taxonomy hierarchical structure, and click Add to assign the selected category. You can assign multiple categories to an asset.

    This image shows the Categories panel for an assets, with categories search bar and ‘Food’ taxonomy hierarchical structure.

  6. After you’re done assigning taxonomies to all the image assets, select all assets in your repository and publish them to the OCEImageGalleryChannel channel.

To consume our Oracle Content Management content in a Flutter application, we can use the Flutter gallery sample, which is available as an open-source repository on GitHub.

Note: Remember that using the Flutter sample is optional, and we use it in this tutorial to get you started quickly. You can also build your own Flutter application.

Building the image gallery in Flutter consists of these steps:

  1. Install Flutter
  2. Clone the sample repository and install dependencies
  3. Configure the Flutter application
  4. Use the Oracle Content Management REST API to fetch content

Install Flutter

The first thing you need to do to get started with Flutter is to set up your environment. You can find the instructions for setting it up on the Flutter website. Use the option corresponding to your operating system. Here’s a summary of the installation steps:

  1. Get the Flutter SDK.
  2. Update your path environment variable.
  3. Run flutter doctor.
  4. Follow the steps outlined on the Flutter website to install an editor of your choice.
  5. Add an editor plugin for Android Studio, IntelliJ, VS Code, or Emacs. The instructions specify how to install the Flutter and Dart plugins in your editor.
  6. Modify the values in the android.properties file to refer to the appropriate locations, sdk and kotlin versions. You may also need to modify values in the android.gradle file for the appropriate versions.

Clone the Sample Repository and Install Dependencies

The Flutter gallery sample is available as an open-source repository on GitHub.

You’ll first need to clone the sample from GitHub to your local computer and change your directory into the repository root:

git clone https://github.com/oracle-samples/oce-flutter-gallery-sample.git
cd oce-flutter-gallery-sample

Open the project from Android Studio or any other editor of your choice. To get all the packages that are being used in the project, click the Get packages button.

Configure the Flutter Application

In this Flutter gallery sample, you need to configure a few pieces of information so that your REST API requests can target the correct instance URL and API version with the correct channel token. These values defined in lib/config/oce.dart are used by the functions defined in lib/networking/content.dart to establish the endpoint for the REST API.

You’ll see the following information in lib/config/oce.dart:

const Map<String, String> config = <String, String>{
  'serverUrl': 'https://samples.mycontentdemo.com',
  'apiVersion': 'v1.1',
  'channelToken': 'e0b6421e73454818948de7b1eaddb091'
};

Change each key-value pair to reflect your instance URL, the API version you want to target, and the channel token associated with your publishing channel. The channel for this tutorial is OCEImageGalleryChannel.

Use the Oracle Content Management REST API to Fetch Content

The REST API for Content Delivery provides access to published assets in Oracle Content Management. Published assets include content items and digital assets, as well as their renditions. We can now leverage the Oracle Content Management REST API to fetch content so that we can render it in our image gallery Flutter application.

The lib/networking/content.dart file has methods for connecting to the server specified in the oce.dart file using the REST API and returning the response from it.

  //Utility method to build up the URL for published content.
  String _getPublishedContentServerURL() {
    final String? serverUrl = data['serverUrl'] as String?;
    final String? apiVersion = data['apiVersion'] as String?;
    return '$serverUrl/content/published/api/$apiVersion/';
  }

  // Adds the channel token to the URL
  String _addChannelToURL(String currUrl) {
    final String? channelToken = data['channelToken'] as String?;
    return '$currUrl?channelToken=$channelToken';
  }

  //Make an http get call and return the response if successful
  Future<dynamic> _get(String url) async {
    dynamic responseJson;
    try {
      final Response response = await get(Uri.parse(url));
      responseJson = _returnResponse(response);
    } on SocketException {
      throw FetchDataException(kConnectionError);
    }
    return responseJson;
  }

  //Return the json decoded response body if response status is successful
  dynamic _returnResponse(Response response) {
    switch (response.statusCode) {
      case 200:
        final Map<String, dynamic>? responseJson =
            json.decode(response.body.toString()) as Map<String, dynamic>?;
        return responseJson;
      case 400:
        throw BadRequestException(response.body.toString());
      case 401:
      case 403:
        throw UnauthorizedException(response.body.toString());
      case 500:
      default:
        throw FetchDataException('StatusCode : ${response.statusCode}');
    }
  }

For rendering the images, the content.dart also provides helper methods to retrieve the various renditions for an asset.

  String getMediumRenditionUrl(Map<String, String> args) {
    final String itemId = args['id'];
    if (itemId == null) return null;
    String url = _getPublishedContentServerURL();
    url = '${url}assets/$itemId/Medium';
    // add the channel token to the URL
    url = _addChannelToURL(url);
    url = '$url&format=jpg&&type=responsiveimage';
    return url;
  }

  String getRenditionURL(Map<String, String> args) {
    final String itemId = args['id'];
    if (itemId == null) return null;
    String url = _getPublishedContentServerURL();
    url = '${url}assets/$itemId/native';
    // add the channel token to the URL
    url = _addChannelToURL(url);
    return url;
  }

The lib/networking/services.dart file contains all the code to get data for the application.

Home Page Data

The home page requires several data calls to get all of its data:

  1. First we load the taxonomies for the channel specified in oce.dart.
  2. For each of the taxonomies, we get all the categories in that taxonomy.
  3. For each category, we get four content items in that category.
  4. For each of those items, we extract its rendition URLs.

Open lib/networking/services.dart and find the functions below, which helps to get all of the data for the home page.

The fetchTaxonomies() in conjunction with fetchCategories() function gets all the categories in all of the taxonomies. The fetchItemsForCategory function is then called to add the four category items to each category. Finally, retrieveThumbnailURL is called to get the thumbnail URLs.

  // Fetch the taxonomies for the channel
  Future<List<String>> fetchTaxonomies() async {
    final Content content = Content();
    try {
      dynamic data = await content.getTaxonomies();
      dynamic taxonomies = data['items'];
      List<String> idArray = [];
      for (var taxonomy in taxonomies) {
        idArray.add(taxonomy['id']);
      }
      return idArray;
    } catch (exception) {
      rethrow;
    }
  }

  // Fetch the categories for the specified taxonomyId.
  Future<List<dynamic>> fetchCategories(taxonomyId) async {
    final Content content = Content();
    dynamic data = await content.queryTaxonomyCategories({
      'id': '$taxonomyId',
    });
    return data['items'];
  }

  // Fetch the items that belong to the specified category
  Future<dynamic> fetchItemsForCategory(String categoryId, bool limit) async {
    final Content content = Content();
    dynamic data = await content.queryItems({
      'q': '(taxonomies.categories.nodes.id eq "$categoryId")',
      'fields': 'all',
      'expand': 'all',
      'limit': limit ? '4' : '100',
      'totalResults': 'true',
    });
    return data;
  }

  // Retrieve the thumbnail URL for the item specified.
  Future<String> retrieveThumbnailURL(identifier) async {
    final Content content = Content();
    dynamic data = await content.getItem({
      'id': identifier,
      'fields': 'all',
      'expand': 'all',
    });
    String url = data['fields']['renditions'][1]['formats'][0]['links'][0]['href'];
    return url;
  }

Image Grid Page

The image grid page receives a category ID and requires several data calls to get all of its data:

  1. Get all the items for the specified category.
  2. For each item, get its rendition URLs.

Open lib/networking/services.dart and find the function below, which is used by the fetchData function in image_grid.dart.

  Future<dynamic> fetchItemsForCategory(String categoryId, bool limit) async {
    final Content content = Content();
    dynamic data = await content.queryItems({
      'q': '(taxonomies.categories.nodes.id eq "$categoryId")',
      'fields': 'all',
      'expand': 'all',
      'limit': limit ? '4' : '100',
      'totalResults': 'true',
    });
    return data;
  }

It calls fetchItemsForCategory, like the home page, but with no limit, so that all the items are returned, not just four.

Now that we have our data query, we can render the responses in our Flutter components.

Flutter Components

The gallery application breaks down each page into a number of smaller components.

The next few sections provide an overview of how Flutter renders our application in each of our components:

HomePage Component

The home page consists of a list of categories for a taxonomy, with a preview of four items in that category. It is rendered by the HomePage component located at lib/screens/home_page.dart. The component uses the functions defined in services.dart file to get the data.

  Future<void> fetchData() async {
    final Services services = Services();
    try {
      List<String> taxonomyIdArray = await services.fetchTaxonomies();
      // For each taxonomy, fetch the categories and append them to an array
      for (var taxonomyId in taxonomyIdArray) {
        List<dynamic> data = await services.fetchCategories(taxonomyId);
        for (var categoryData in data) {
          categories.add(CategoryListItemModel.fromJson(categoryData));
        }
        setState(() {
          categories = categories;
        });
      }
    } catch (exception) {
      setState(() => this.exception = exception.toString());
      print(exception.toString());
    }
  }

This file also uses a component located at lib/components/card_grid.dart to render the images in a grid.

ImageGrid Component

The ImageGridPage component displays the items in the category. It is rendered by the ImageGrid component, located at lib/screens/image_grid.dart.

The component makes call to get the data from the services.dart file.

  Future<void> fetchData() async {
    final Services services = Services();

    String categoryId = widget.category.id;
    try {
      dynamic categoryItems =
          await services.fetchItemsForCategory(categoryId, false);
      items = categoryItems['items'];
      setState(() {
        dataFetched = true;
      });
    } catch (exception) {
      setState(() {
        this.exception = exception.toString();
      });
      print(exception.toString());
    }
  }

ImagePager Component

The ImagePager component located at lib/screens/image_pager.dart, displays the items in a sliding pager form.

Task 3: Prepare Your Application for Deployment

Now that we’ve built our Flutter image gallery site, we need to deploy it on an emulator or device so we can debug any issues and preview the application before it goes live.

Follow the instructions on the Flutter website for your editor to run the app.

  1. If you are using Android Studio as your editor, locate the main Android Studio toolbar.
  2. In the target selector, select an Android device for running the app. If none are listed as available, select Tools > Android > AVD Manager and create one there. For details, see Managing AVDs.
  3. Click the run icon in the toolbar, or invoke the menu item Run > Run.

Conclusion

In this tutorial, we created a gallery site in Flutter, which can be found on GitHub. This site uses Oracle Content Management as a headless CMS. After setting up and configuring Oracle Content Management with a channel of published content for the gallery site tutorial, we installed and ran the Flutter site to fetch the required content and build the site.

For more information on Flutter, go to the Flutter website.

Learn about important Oracle Content Management concepts in the documentation.

You can find more samples like this on the Oracle Content Management Samples page in the Oracle Help Center.