Flutter Integration Guide

Learn how to integrate JustCMS into your Flutter project in just a few simple steps

Installation and Setup

Setting up JustCMS in your Flutter project is a straightforward process that requires just a few simple steps. We'll walk you through adding the necessary files and dependencies to get you started quickly.

Add Service File

Copy just_cms_service.dart to your project's services or lib directory

Update Dependencies

Add the http package to pubspec.yaml

Install Packages

Run flutter pub get to install required dependencies

Let's break down each step in detail to ensure a smooth setup process:

1. Adding the Service File

The first step is to add the JustCMS service file to your project. Simply copy the just_cms_service.dart file into your project's services or lib directory. This file contains all the necessary code to interact with the JustCMS API.

2. Adding Dependencies

Next, you'll need to add the required HTTP package to your project. Open your pubspec.yaml file and add the following dependency:

dependencies:
  http: ^0.13.0

3. Installing Packages

Finally, install the dependencies by running the following command in your terminal:

flutter pub get

That's all you need to do for the installation! With these three simple steps completed, you're ready to start using JustCMS in your Flutter project. The service file is in place, and all required dependencies are installed.

Quick Setup Check

Verify that just_cms_service.dart is in your project

Dependencies Check

Confirm http package is listed in pubspec.yaml

Installation Check

Ensure flutter pub get completed successfully

Basic Configuration of JustCMS Service

Getting started with JustCMS in your Flutter project is straightforward. The main step is configuring the JustCMSService with your credentials. You'll need two key pieces of information:

  • Your JustCMS API token for authentication
  • Your JustCMS project ID
final justCmsService = JustCMSService(
  token: 'YOUR_JUSTCMS_API_TOKEN',
  projectId: 'YOUR_JUSTCMS_PROJECT_ID',
);

Once you create this instance, you can use it throughout your app to interact with JustCMS. It's recommended to create the service instance at a high level in your app's widget tree or in your state management solution for easy access.

Keep Credentials Secure

Store your API token and project ID in a secure configuration file, not directly in the code

Single Instance

Create one instance of JustCMSService and reuse it across your app

Easy Access

Initialize the service where it can be easily accessed by your app's components

Best Practice: To keep your credentials secure, consider storing them in an environment configuration file or using Flutter's asset system. This makes it easier to manage different credentials for development and production environments.

Using the JustCMS Service

Let's walk through a practical example of how to use the JustCMS service in your Flutter application. We'll create a simple screen that fetches and displays categories from your JustCMS project.

Creating the Categories Screen

First, we'll create a stateful widget that will handle fetching and displaying the categories. The widget includes proper error handling and loading states to ensure a smooth user experience.

import 'package:flutter/material.dart';
import 'just_cms_service.dart'; // Adjust import path as needed

class CategoriesScreen extends StatefulWidget {
  @override
  _CategoriesScreenState createState() => _CategoriesScreenState();
}

class _CategoriesScreenState extends State<CategoriesScreen> {
  final justCmsService = JustCMSService(
    token: 'YOUR_JUSTCMS_API_TOKEN',
    projectId: 'YOUR_JUSTCMS_PROJECT_ID',
  );
  late Future<List<Category>> _categoriesFuture;

  @override
  void initState() {
    super.initState();
    _categoriesFuture = justCmsService.getCategories();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Categories')),
      body: FutureBuilder<List<Category>>(
        future: _categoriesFuture,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return Center(child: CircularProgressIndicator());
          } else if (snapshot.hasError) {
            return Center(child: Text('Error: ${snapshot.error}'));
          } else if (!snapshot.hasData || snapshot.data!.isEmpty) {
            return Center(child: Text('No categories found.'));
          }
          final categories = snapshot.data!;
          return ListView.builder(
            itemCount: categories.length,
            itemBuilder: (context, index) {
              final cat = categories[index];
              return ListTile(
                title: Text(cat.name),
              );
            },
          );
        },
      ),
    );
  }
}

Code Breakdown

Service Initialization

Create JustCMSService instance with your API token and project ID

Future Declaration

Define _categoriesFuture to store the API call result

Data Fetching

Call getCategories() in initState to fetch data when widget initializes

Error Handling

Handle loading, error, and empty states with FutureBuilder

Data Display

Show categories in a ListView when data is available

The example above demonstrates several important concepts:

  • Proper state management using StatefulWidget
  • Async data handling with FutureBuilder
  • Error handling for different states
  • Clean UI presentation with loading indicators

Implementation Tips

When implementing this example in your project, remember to:

  • Replace 'YOUR_JUSTCMS_API_TOKEN' and 'YOUR_JUSTCMS_PROJECT_ID' with your actual credentials
  • Ensure the just_cms_service.dart file is properly imported
  • Consider adding error retry functionality for better user experience
  • Add custom styling to the ListTile widgets to match your app's design

Available Methods in JustCMS Service

The JustCMSService class provides several core methods to fetch different types of content from your JustCMS project. Let's explore each method and see how to use them effectively.

Fetching Categories

The getCategories() method allows you to retrieve all categories from your JustCMS project. This method returns a Future containing a list of Category objects.

Future<List<Category>> categories = justCmsService.getCategories();

Working with Pages

The getPages() method fetches pages with flexible options for filtering and pagination. You can filter pages by category and control the number of results returned.

filterCategorySlug

Filter pages by category slug

start

Starting index for pagination

offset

Number of items to return

Future<PagesResponse> pagesResponse = justCmsService.getPages(
  filterCategorySlug: 'blog',
  start: 0,
  offset: 10,
);

Getting Page Details

Use the getPageBySlug() method to fetch detailed information about a specific page using its slug. You can optionally specify a version parameter to fetch draft content.

Future<PageDetail> pageDetail = justCmsService.getPageBySlug('about-us');

// To fetch a draft version
Future<PageDetail> draftPage = justCmsService.getPageBySlug(
  'about-us',
  version: 'draft'
);

Menu Retrieval

The getMenuById() method allows you to fetch a menu and its items using the menu's ID. This is useful for building navigation structures in your app.

Future<Menu> menu = justCmsService.getMenuById('main-menu');

Type Safety

All methods return strongly-typed objects for better development experience

Async Operations

Methods return Futures for proper async handling

Error Handling

Built-in error handling for failed API requests

When using these methods, remember to properly handle the Future responses using async/await or .then() syntax, and implement appropriate error handling for your use case.

Utility Functions in JustCMS Flutter Integration

JustCMS provides several utility functions that make it easier to work with different content elements in your Flutter application. These helper methods handle common tasks like checking content block styles, managing image variants, and verifying category assignments.

Style Checking for Content Blocks

The isBlockHasStyle function allows you to check if a content block has a specific style. This is particularly useful when you need to apply different rendering logic based on block styles.

bool hasStyle = justCmsService.isBlockHasStyle(block, 'highlighted');
if (hasStyle) {
  // Apply special styling
}

Image Handling Functions

getLargeImageVariant

Retrieves the large variant of an image, typically the second variant if available

getFirstImage

Gets the first image from an image block, simplifying image access

// Get large image variant
CmsImage? largeImage = justCmsService.getLargeImageVariant(image);

// Get first image from block
CmsImage? firstImage = justCmsService.getFirstImage(imageBlock);

Category Verification

The hasCategory utility function helps you check if a page belongs to a specific category. This is particularly useful when filtering or organizing content.

bool belongsToCategory = justCmsService.hasCategory(page, 'blog');
if (belongsToCategory) {
  // Handle blog category content
}

Case-Insensitive Style Checking

Style comparisons are case-insensitive for more flexible matching

Null-Safe Operations

All utility functions handle null values safely to prevent runtime errors

Easy Integration

Functions are available directly through the JustCMSService instance

These utility functions are designed to streamline common content management tasks in your Flutter application. By using these helper methods, you can write cleaner, more maintainable code while handling JustCMS content effectively.