Learn how to integrate JustCMS into your Flutter project in just a few simple steps
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.
Copy just_cms_service.dart to your project's services or lib directory
Add the http package to pubspec.yaml
Run flutter pub get to install required dependencies
Let's break down each step in detail to ensure a smooth setup process:
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.
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
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.
Verify that just_cms_service.dart is in your project
Confirm http package is listed in pubspec.yaml
Ensure flutter pub get completed successfully
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:
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.
Store your API token and project ID in a secure configuration file, not directly in the code
Create one instance of JustCMSService and reuse it across your app
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.
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.
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),
);
},
);
},
),
);
}
}
Create JustCMSService instance with your API token and project ID
Define _categoriesFuture to store the API call result
Call getCategories() in initState to fetch data when widget initializes
Handle loading, error, and empty states with FutureBuilder
Show categories in a ListView when data is available
The example above demonstrates several important concepts:
When implementing this example in your project, remember to:
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.
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();
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.
Filter pages by category slug
Starting index for pagination
Number of items to return
Future<PagesResponse> pagesResponse = justCmsService.getPages(
filterCategorySlug: 'blog',
start: 0,
offset: 10,
);
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'
);
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');
All methods return strongly-typed objects for better development experience
Methods return Futures for proper async 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.
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.
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
}
Retrieves the large variant of an image, typically the second variant if available
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);
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
}
Style comparisons are case-insensitive for more flexible matching
All utility functions handle null values safely to prevent runtime errors
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.