OpenAI Image Generation In Flutter

Hi Guy’s Welcome to Proto Coders Point. In this Flutter Article we will make use of OpenAI DALL-E 2 API and explore the super power of OpenAI, By creating an flutter application that can convert a given Text into an AI image. You will learn how to we make use of OpenAI API to generate a unique & stunning AI realistic image , and how to implement it into our Flutter app to generate AI Image from a given Text Sentence.

In below Flutter Video Tutorial on Youtube, I have cover everything from setting up the API, to making API calls and displaying the generated images in the flutter app. By the end of this tutorial, You will learn how to use OpenAI DALL-E 2 API to convert text to AI generated image and show it in your own flutter app and create a beautiful & realistic AI images.

Creating an Account

Step 1: Create an account in openai.com

In browser, search for openai.com and SignIn using Google account or any other account.

Step 2: You need to activity a billing

Added your credit card for billing, Initially OpenAI gives you $15 free to generate images from Text. Then you will be charged.

Here are charges depending on the Image Size you order for:

RESOLUTIONPRICE
1024×1024$0.020 / image
512×512$0.018 / image
256×256$0.016 / image

Step 3: Generate a openai API key

Create a Flutter App to Generate an AI Image from Text by using open ai image generation

Implementing OpenAI in Flutter App

Step 1: Install http package

As we are going to make internet call in our flutter app generate an AI Image to open ai API, we need a http package to do so.

In flutter project, open pubspec.yaml file and under dependencies section add http package.

dependencies:
  flutter:
    sdk: flutter
  http:

Step 2: Import the http class

In main.dart file of flutter project, Import http.dart file

import 'package:http/http.dart' as http;

Step 3: Create a async function

Now, Create a function generateAIImage() that makes a HTTP call to OpenAI DALL-E Image Generation API by passing desired Text of which you want AI to generate a Image.

void generateAIImage() async{
    if(inputText.text.isNotEmpty){
      
      var data ={
        "prompt": inputText.text,
        "n": 1,
        "size": "256x256",
      };
      
      var res = await http.post(Uri.parse(url),
          headers: {"Authorization":"Bearer ${apikey}","Content-Type": "application/json"},
          body:jsonEncode(data));

      var jsonResponse = jsonDecode(res.body);

      image = jsonResponse['data'][0]['url'];
      setState(() {

      });
      
    }else{
      print("Enter something");
    }
  }

The above function will make a http post request to openai, so in this http request we are passing the data and in header we are passing openai authorization api key.

In request body we need to pass this parameters

prompt: a Text of which AI should generate an image.

n: Number of different image to be generate of the given text.

size: The size of the generated images.

Step 4: Show the image response in app

Once the above function return the response, we need to parse the JSON response from the API and extract only url of the generate image.

And thus make use of Image.network() flutter widget to display the AI generated image in flutter app.

Complete Source Code – Flutter open ai image generation

main.dart

import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  TextEditingController inputText = TextEditingController();
  String apikey = 'tsk-nTRcf1113XPQht7r22T3Bvadapavlb5kFJYz1yz5b4xifuyzpoiyom2ooNIQehy';
  String url = 'https://api.openai.com/v1/images/generations';
  String? image;
  void getAIImage() async{
    if(inputText.text.isNotEmpty){
      
      var data ={
        "prompt": inputText.text,
        "n": 1,
        "size": "256x256",
      };
      
      var res = await http.post(Uri.parse(url),
          headers: {"Authorization":"Bearer ${apikey}","Content-Type": "application/json"},
          body:jsonEncode(data));

      var jsonResponse = jsonDecode(res.body);

      image = jsonResponse['data'][0]['url'];
      setState(() {

      });
      
    }else{
      print("Enter something");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Open AI DALL.E"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            image != null ? Image.network(image!,width: 256,height: 265) : Container(child: Text("Please Enter Text To Generate AI image"),),
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: TextField(
                controller: inputText,
                decoration: InputDecoration(
                    hintText: "Enter Text to Generate AI Image",
                    filled: true,
                    fillColor: Colors.blue.shade100,
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(10),
                      borderSide: BorderSide.none,
                    )
                ),
              ),
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: (){
          getAIImage();
        },
        tooltip: 'Generate AI Image',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}