Special Credits for This Workshop

Visit https://trygcp.dev/claim/gdg-other-road-to-devfest to sign up with your Google Account and get access to the Free Tier.

Gemini screenshot

Explore Gemini's image capabilities with a short, practical focus on image filters.

You'll learn how to:

Applications of Gemini Image capabilities

Gemini screenshot

Before we start, make sure you have:

Tools

Free credits

Gemini API Key

If you don't want to set up your machine with Flutter at the moment, you can use FirebaseStudio (https://studio.firebase.google.com), an entirely web-based workspace for full-stack application development, complete with the latest generative AI from Gemini, and full-fidelity app previews, powered by cloud emulators.

Gemini screenshot

Step 1: Create and Run the App

You can create a Flutter project from Android Studio UI.

Android Studio screenshot

Or if you prefer commandline. Run following commands:

flutter create build_with_ai_25
cd build_with_ai_25
flutter run

Verify the app runs on your web / simulator or device.

Let's update some UI to include:

Create a new file called gallery_screen.dart and copy and paste following:

import 'package:flutter/material.dart';

class GalleryScreen extends StatelessWidget {
  const GalleryScreen({super.key});

  // AI Style names
  static const List<String> aiStyles = [
    'Cyberpunk',
    'Oil Painting',
    'Watercolor',
    'Anime',
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Flitters Gallery'),
      ),
      body: _buildFilterGrid(context, aiStyles),
    );
  }

  Widget _buildFilterGrid(BuildContext context, List<String> styleList) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Padding(
            padding: EdgeInsets.all(16.0),
            child: Text('Transform your photos with AI-powered styles'),
          ),
          Expanded(
            child: GridView.count(
              crossAxisCount: 2,
              mainAxisSpacing: 8,
              crossAxisSpacing: 8,
              childAspectRatio: 2.0,
              children: styleList.map((styleName) {
                return GestureDetector(
                  onTap: () {
                    
                  },
                  child: Card(
                    child: Center(
                      child: Text(
                        styleName,
                        textAlign: TextAlign.center,
                      ),
                    ),
                  ),
                );
              }).toList(),
            ),
          ),
        ],
      ),
    );
  }
}

now Open lib/main.dart and make it open GalleryScreen ui.

add import statement like:

import 'gallery_screen.dart';

find home key in build function and point it to load GalleryScreen

...

      home: const GalleryScreen(),

...

It should load some UI like below:

Preview Gen Text

Firebase AI Logic gives you access to the latest generative AI models from Google: the Gemini models and Imagen models.

If you need to call the Gemini API or Imagen API directly from your mobile, you can use the Firebase AI Logic client SDKs.

Flutter 3.35.0 introduced firebase_ai formerly called "Vertex AI in Firebase". It is a client sdk for Flutter Apps. When working in production environment. You should definitely use firebase_ai.

Step 1: Add Generative AI

Add the Firebase AI Logic Dart SDK:

dependencies:
  firebase_core: ^4.2.1
  firebase_ai: ^3.6.0

Then do flutter pub get in the UI or from Terminal, run:

flutter pub get

Step 2: Firebase Setup

Createa firebase project and download your configuration file called google-service.json.

Place the google-service.json file in android/app directory.

In your lib/main.dart file, import the Firebase core plugin, the Firebase AI Logic plugin, and the configuration file you generated earlier:

import 'package:firebase_core/firebase_core.dart';

Also in your lib/main.dart file, initialize Firebase using the DefaultFirebaseOptions object exported by the configuration file:

const FirebaseOptions android = FirebaseOptions(
  apiKey: 'api_key from google-service.json',
  appId: 'mobilesdk_app_id from google-service.json',
  messagingSenderId: 'project_number from google-service.json',
  projectId: 'project_id from google-service.json',
  storageBucket: 'storage_bucket from google-service.json',
);

then use this to initialize firebase in your main() function.

WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(options: android);

Rebuild your Flutter application:

flutter run

Let's add a new screen that will have will be open when clicking on Gallery screen:

Filter Screen

Image Picker Dep

So first lets add the dependency to pubspec.yaml file as below:

dependencies:
  image_picker: ^1.2.1

Then do flutter pub get in the UI or from Terminal, run:

flutter pub get

Add Filter Screen UI

Create a new file called filter_screen.dart and copy and paste following:

import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'gemini_service.dart';

class FilterScreen extends StatefulWidget {
  final String styleName;

  const FilterScreen({super.key, required this.styleName});

  @override
  State<FilterScreen> createState() => _FilterScreenState();
}

class _FilterScreenState extends State<FilterScreen> {
  File? _imageFile;
  Uint8List? _imageBytes;
  bool _isLoading = false;
  Uint8List? _generatedImageBytes;
  
  final ImagePicker _picker = ImagePicker();



  Future<void> _pickImage() async {
    final XFile? pickedFile = await _picker.pickImage(source: ImageSource.gallery);
    if (pickedFile != null) {
      final bytes = await pickedFile.readAsBytes();
      setState(() {
        _imageFile = File(pickedFile.path);
        _imageBytes = bytes;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.styleName),
      ),
      body: Column(
        children: [
          Expanded(
            child: Center(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: AspectRatio(
                  aspectRatio: 1,
                  child: _buildImageArea(),
                ),
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(24.0),
            child: Text(
              'Going to apply ${widget.styleName} to your photo',
              textAlign: TextAlign.center,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildImageArea() {
    if (_isLoading) {
      return const Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            CircularProgressIndicator(),
            SizedBox(height: 16),
            Text('Gemini is applying magic...'),
          ],
        ),
      );
    }

    if (_imageFile == null) {
      return InkWell(
        onTap: _pickImage,
        child: const Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(Icons.add_a_photo, size: 48),
              SizedBox(height: 16),
              Text('Please upload your photo'),
            ],
          ),
        ),
      );
    }

    Widget imageWidget = Image.file(_imageFile!, fit: BoxFit.cover);

    return imageWidget;
  }
}


This will show a screen where you can pick an image for a user.

Open Filter Screen from Gallery

Now Open lib/gallery_screen.dart and make it open FilterScreen ui.

add import statement like:

import 'filter_screen.dart';

find onTap() function in grid and make it to load FilterScreen

...

      onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => FilterScreen(styleName: styleName),
                  ),
                );
      }

...

Re launch and it should show the FilterScreen UI.

Let's power our app with Gemini to apply styles to the app.

Step 1: Instantiate GenerativeModel

Open lib/filter_screen.dart and add an import statement:

import 'package:firebase_ai/firebase_ai.dart';

It can be a GenerativeModel

  final model = FirebaseAI.googleAI().generativeModel(
    model: 'gemini-2.5-flash'
  );

Or it can be an ImagenModel

  final imagent = FirebaseAI.googleAI().imagenModel(
    model: 'imagen-4.0-generate-001',
  );

You can provide GenerationConfig as well:

  final model = FirebaseAI.googleAI().generativeModel(
    model: 'gemini-2.5-flash-image',
    generationConfig: GenerationConfig(
      temperature: 0.4,
      topK: 32,
      topP: 1,
      maxOutputTokens: 4096,
    ),
  );

Step 2: Send a prompt

You're now set up to send a prompt request to a Gemini model.

// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
final model =
      FirebaseAI.googleAI().generativeModel(model: 'gemini-2.5-flash');

// Provide a prompt that contains text
final prompt = [Content.text('Write a story about a magic backpack.')];

// To generate text output, call generateContent with the text input
final response = await model.generateContent(prompt);
print(response.text);

Let's create a function that takes imageBytes, sends to Gemini and gets a response:

void describeTheImage(Uint8List imageBytes) async {
  try {
    final model = FirebaseAI.googleAI().generativeModel(
        model: 'gemini-2.0-flash-lite'
    );

    final content = [
      Content.multi([
        TextPart('Describe this photo.'),
        InlineDataPart('image/jpeg', imageBytes),
      ])
    ];

    final response = await model.generateContent(content);
    print('Gemini API Response received');

    print(response.text);



  } catch (e) {
    print('Error generating response: $e');
  }
}

Hook this function to _pickImage() as below:

describeTheImage(bytes);

Step 3: Style with Gemini

Let's create a function, that takes image and style and sends to gemini and gets a photo.

We will use gemini-2.5-flash-image model for this.

Future<Uint8List?> generateStyledImage(Uint8List imageBytes, String stylePrompt) async {
    try {
      final model = FirebaseAI.googleAI().generativeModel(
        model: 'gemini-2.5-flash-image',
        generationConfig: GenerationConfig(
          temperature: 0.4,
          topK: 32,
          topP: 1,
          maxOutputTokens: 4096,
        ),
      );
      
      final content = [
        Content.multi([
          TextPart('Transform the attached image into this style: $stylePrompt. Return only the transformed image.'),
          InlineDataPart('image/jpeg', imageBytes),
        ])
      ];
      
      final response = await model.generateContent(content);
      print('Gemini API Response received');

      // Extract image from response
      if (response.candidates.isNotEmpty && 
          response.candidates.first.content.parts.isNotEmpty) {
        
        for (var part in response.candidates.first.content.parts) {
          if (part is InlineDataPart) {
            print('Found inline image data');
            return part.bytes;
          }
        }
      }
      
      print('No image data found in response');
      return null;
    } catch (e) {
      print('Error generating styled image: $e');
      return null;
    }
  }

Step 4: Hook this to pick image function.

first create a function that keeps an eye on style with gemini function and do the exception handling if any.

Future<void> _processImage(Uint8List bytes) async {
  // AI Style
  try {
    setState(() {
      _generatedImageBytes = null; // Reset generated image
      _isLoading = true;
    });
    final generatedImage = await generateStyledImage(bytes, widget.styleName);
    if (mounted) {
      setState(() {
        _generatedImageBytes = generatedImage;
        _isLoading = false;
      });
      
      if (generatedImage == null) {
          ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('Could not generate styled image. Please try again.')),
        );
      }
    }
  } catch (e) {
    if (mounted) {
      setState(() {
        _isLoading = false;
      });
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Error processing image: $e')),
      );
    }
  }
}

Now hook this to _pickImage() function.

Future<void> _pickImage() async {
  final XFile? pickedFile = await _picker.pickImage(source: ImageSource.gallery);
  if (pickedFile != null) {
    final bytes = await pickedFile.readAsBytes();
    setState(() {
      _imageFile = File(pickedFile.path);
      _imageBytes = bytes;
      
    });
    _processImage(bytes);
  }
}

Result: A smart product form that auto-generates compelling title, descriptions, types and features.

Recap of What You Did

In this codelab, you:

Key Takeaways

Resources to Explore

What's Next?

Thank you for following along.