OpenAI x Flutter: How to build a gift recommender using OpenAI API

Aditya Thakur
Level Up Coding
Published in
5 min readFeb 21, 2023

--

ChatGPT has taken the world by storm. As the world inclines towards AI, it would be good to explore GPT’s integration with Flutter and build some cool projects to start with.

OpenAI-powered Flutter apps

Using the OpenAI API, we can take our Flutter apps to the next level by adding natural language processing capabilities to them. This means we can build chatbots, voice assistants, and other cool conversational interfaces that make the app way more user-friendly and fun to use.

Today we explore building a gift recommender using GPT API in this piece!

For more project ideas consider following me on GitHub below:

Getting started with OpenAI API

OpenAI Login
  • Go to your account and use the side navigation to click on ‘View API keys’ or click here.
View API keys
  • Click on ‘Create new secret key’ which should generate a SECRET KEY. Save it to use later.
API key generated

Flutter Project

Let us start by creating a new Flutter project. Run the following command in the terminal to create a new project at your desired location.

flutter create giftsbyai

Gifts by AI would use OpenAI API to recommend gifts based on relation to the person, the occasion, their gender, and their interests/hobbies.

Sample Input Field

We’ll start by building a landing page to get these inputs.

First, let us add some styles to our Flutter project. Run the following command to add the google_fonts package.

flutter pub add google_fonts

Create a file called styles.dart and add the following code:

import 'package:google_fonts/google_fonts.dart';

final primaryColor = Color(0xFFC92C6D);

TextStyle kTitleText = GoogleFonts.poppins(
color: Colors.black,
fontSize: 40.0,
fontWeight: FontWeight.bold,
);

TextStyle kSubTitleText = GoogleFonts.poppins(
color: Color(0xFF242224),
fontSize: 16.0,
);

Next, create a new folder called screens and create a new landing_screen.dart file in it.

The above code should create a landing page like below:

Gifts by AI — Landing Screen

Notice (in the above GitHub Gist) how we have added a comment at line 190. We’ll add the code there to get a response from the API and navigate to a new screen to show results.

Inside the constants folder, create a new file called open_ai.dart. In this file, we’ll save the SECRET KEY copied earlier.

String apiKey = "<YOUR SECRET KEY>";

Now, we need to add the HTTP package to make a request.

Run the command:

flutter pub add http

Now, return to the onPressed of the ElevatedButton in the landing_screen.dart and modify it with the code below:

                var url = Uri.parse('https://api.openai.com/v1/completions');

Map<String, String> headers = {
'Content-Type': 'application/json;charset=UTF-8',
'Charset': 'utf-8',
'Authorization': 'Bearer $apiKey'
};

String promptData =
"Suggest gift ideas for someone who is realted to me as $firstDropdownValue of $gender gender for the occasion of $secondDropdownValue in budget less than 10,000 rupees with ${_controller.value.text} as hobbies.";

print(promptData);
final data = jsonEncode({
"model": "text-davinci-003",
"prompt": promptData,
"temperature": 0.4,
"max_tokens": 64,
"top_p": 1,
"frequency_penalty": 0,
"presence_penalty": 0
});

if (_formKey.currentState!.validate()) {
var response =
await http.post(url, headers: headers, body: data);
if (response.statusCode == 200) {
print(response.body);

}
}

The code above creates a post request to the OpenAI API with a prompt generated using the user input and awaits a response.

We need to parse the JSON response, therefore create a folder called models and create a new file called openai_model.dart.

Based on the response the model can be made as follows:

import 'dart:convert';

GptData gptDataFromJson(String str) => GptData.fromJson(json.decode(str));

String gptDataToJson(GptData data) => json.encode(data.toJson());

class GptData {
GptData({
required this.id,
required this.object,
required this.created,
required this.model,
required this.choices,
required this.usage,
});

String id;
String object;
int created;
String model;
List<Choice> choices;
Usage usage;

factory GptData.fromJson(Map<String, dynamic> json) => GptData(
id: json["id"],
object: json["object"],
created: json["created"],
model: json["model"],
choices:
List<Choice>.from(json["choices"].map((x) => Choice.fromJson(x))),
usage: Usage.fromJson(json["usage"]),
);

Map<String, dynamic> toJson() => {
"id": id,
"object": object,
"created": created,
"model": model,
"choices": List<dynamic>.from(choices.map((x) => x.toJson())),
"usage": usage.toJson(),
};
}

class Choice {
Choice({
required this.text,
required this.index,
this.logprobs,
required this.finishReason,
});

String text;
int index;
dynamic logprobs;
String finishReason;

factory Choice.fromJson(Map<String, dynamic> json) => Choice(
text: json["text"],
index: json["index"],
logprobs: json["logprobs"],
finishReason: json["finish_reason"],
);

Map<String, dynamic> toJson() => {
"text": text,
"index": index,
"logprobs": logprobs,
"finish_reason": finishReason,
};
}

class Usage {
Usage({
required this.promptTokens,
required this.completionTokens,
required this.totalTokens,
});

int promptTokens;
int completionTokens;
int totalTokens;

factory Usage.fromJson(Map<String, dynamic> json) => Usage(
promptTokens: json["prompt_tokens"],
completionTokens: json["completion_tokens"],
totalTokens: json["total_tokens"],
);

Map<String, dynamic> toJson() => {
"prompt_tokens": promptTokens,
"completion_tokens": completionTokens,
"total_tokens": totalTokens,
};
}

Now, in the onPressed let us parse the reponse.body by adding the following line:

final gptData = gptDataFromJson(response.body);

We can pass this gptData to a new screen to display the results there using:

Navigator.of(context).push(MaterialPageRoute(
builder: (context) =>
IdeasScreen(gptReponseData: gptData)));

Create a new file called ideas_screen.dart in the screens folder and add the following code:

import 'package:flutter/material.dart';
import 'package:giftsbyai/constants/styles.dart';
import 'package:giftsbyai/models/openai_model.dart';

class IdeasScreen extends StatelessWidget {
GptData gptReponseData;
IdeasScreen({super.key, required this.gptReponseData});

@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(children: [
Padding(
padding: const EdgeInsets.only(left: 10),
child: Text(
"the AI has spoken 🥳",
style: kTitleText,
),
),
Padding(
padding: const EdgeInsets.all(10.0),
child: Text(
gptReponseData.choices[0].text,
style: kSubTitleText,
),
)
]),
);
}
}

This would display the data response from the OpenAI GPT model on screen. The project is ready to test now!

Project Demo

Gifts by AI — Demo

Voila 🥳 We have successfully created a Flutter web app using the OpenAI API to recommend gifts based on relation to the person, the occasion, their gender, and their interests/hobbies.

Find the complete project code here 👇

Level Up Coding

Thanks for being a part of our community! Before you go:

🚀👉 Join the Level Up talent collective and find an amazing job

--

--