Generate AI images in your Flutter apps with Cloudflare Workers AI

avatar Manan Gandhi

Published on May 20, 2024

1 min read

Cloudflare Workers AI is a very powerful set of APIs, which allows anyone to run machine learning models using serverless GPUs. They have a generous free tier, with which you can rapidly add AI capabilities to your apps.

This is what we will be building:

We will use these APIs through the cloudflare_ai package (co-developed by me 🙂), and generate images according to the prompt the user enters. To start out, create a new Flutter project. Then install the dependencies

$ flutter pub add cloudflare_ai gal

Next, make a new Dart file presentation/home_page.dart and set it as the home in the MaterialApp widget. In the file, initialise a StatefulWidget. In the widget, define an TextToImageModel. You will need an Account ID and API Key, which you can generate from your Cloudflare Dashboard.

import 'package:cloudflare_ai/cloudflare_ai.dart'

TextToImageModel model = TextToImageModel(
    accountId: "Your Account ID",
    apiKey: "Your API Key"
    model: TextToImageModels.DREAMSHAPER_8_LCM,
);

Define 2 other variables,

Uint8List? image; // Image bytes
bool isLoading = false;

Next, make a User Interface, where the user will enter a prompt, and the generated image will be shown.

Scaffold(
  appBar: AppBar(
    title: const Text("Image Generation"),
  ),
  body: Padding(
    padding: const EdgeInsets.all(8.0),
    child: SingleChildScrollView(
      child: Column(
        children: [
          TextField(
            controller: _promptController,
            decoration: InputDecoration(
              label: const Text("Prompt"),
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(10),
                borderSide: const BorderSide(
                  color: Colors.white10,
                ),
              ),
            ),
            maxLines: null,
          ),
          ElevatedButton(
            onPressed: () {
              generateImage(_promptController.text);
            },
            child: const Text("Generate Image"),
          ),
          image != null
              ? Image.memory(image!)
              : isLoading
                  ? const Padding(
                      padding: EdgeInsets.all(8.0),
                      child: CircularProgressIndicator(),
                    )
                  : Container(),
          image != null
              ? ElevatedButton(
                  onPressed: () {
                    saveToGallery(image!);
                  },
                  child: const Text("Save to Gallery"),
                )
              : Container(),
        ],
      ),
    ),
  ),
);

Now, create the functions generateImage() and saveToGallery()

import 'package:gal/gal.dart';

// This goes above the build function
void generateImage(String prompt) async {
  if (prompt != "") {
    try {
      setState(() {
        image = null;
        isLoading = true;
      });
      Uint8List imageRes = await model.generateImage(prompt);
      setState(() {
        image = imageRes;
        isLoading = false;
      });
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(e.toString()),
        ),
      );
    }
  }
}

void saveToGallery(Uint8List image) async {
  await Gal.putImageBytes(image);
  ScaffoldMessenger.of(context).showSnackBar(
    const SnackBar(
      content: Text("Image saved to gallery"),
    ),
  );
}

All code in this article is available on this GitHub repository - https://github.com/MananGandhi1810/cloudflare-ai-image-gen

Thank you for reading, and do let me know your doubts, or if you make any projects by following this article, on my website.


Maybe even subscribe to our newsletter

Previous Post

Bridging the Gap Between Hardware and Software: Virtual Machines

Next Post

Basic concepts of generative AI

Find Us Here!