Building an AI-Powered Bible Chat App: A Technical Journey with Gemini AI SDK and Flutter
Tags: gemini, flutter, ai, tutorial
Published: 2024-05-18 11:33:28

## Introduction

With the integration of artificial intelligence (AI) becoming a game-changer in today's world, I recently embarked on creating a mobile application – an AI-powered Bible chat experience. In this article, I’ll share my journey of creating a simple yet effective AI-powered Bible chat app using the [Gemini AI SDK](https://pub.dev/packages/google_generative_ai) and Flutter, focusing on Stacked architecture for state management and [sqflite](https://pub.dev/packages/sqflite) for local storage.

## Conceptualizing the AI Bible Chat App

The idea was to create an application which could provide users with an interactive and personalized Bible study experience. The app would leverage AI to understand natural language queries and provide contextually relevant scripture passages, interpretations, and study materials.

The app utilizes the Gemini large language model API to process these queries and generate informative responses based on the vast amount of biblical text it has been trained on.

To enhance the user experience, I implemented an SQLite local database using the sqflite package. This allows the app to store user queries and corresponding Gemini responses. This cached data enables features like revisiting past conversations and potentially offering offline functionality in the future.

Stacked, a state management solution by Filledstacks, was chosen for its ease of use and focus on reactive programming. Stacked helps manage the application state efficiently, particularly when dealing with user interactions and updates from the Gemini API.

## Choosing the Right Tools

- **Frontend**: **Flutter** – A framework from Google, emerged as the ideal framework for its cross-platform capabilities and its expressive and flexible UI, enabling the building of beautiful and performant applications for iOS, Android, Web, and Desktop (MacOS, Windows, and Linux) using a single codebase.

- **State Management**: **Stacked** – A reactive state management solution built for Flutter, simplifying app creation, state handling and data flow within the app.

- **AI Model**: **Gemini** – A large language model from Google AI, trained on a massive dataset of text and code, allowing it to generate creative text formats and answer questions in an informative way.

- **Local Database**: **sqflite** – An ORM (Object Relational Mapper) for Flutter that facilitates interaction with SQLite, a lightweight and embedded relational database engine, for storing user queries and Gemini responses on user devices.

## Designing the App with Stacked

Stacked architecture allowed for a clean separation of concerns, making the codebase more readable and easier to manage. It follows the MVVM pattern (Model-View-ViewModel), which fits perfectly with the reactive nature of Flutter apps.

```
class BibleDataService {
  final _databaseService = locator<DatabaseService>();

  Future<List<SessionConversations>?> 
     getAllSessionsWithConversations() async {
      var allSessionsWithConversations =
        await _databaseService.fetchAllSessionsWithConversations();
    return allSessionsWithConversations;
  }
}
```

```
class BibleChatViewModel extends FormViewModel {
  final _bibleDataService = locator<BibleDataService>();
  final _logger = getLogger('BibleChatViewModel');

  List<String> get books => _books;
  List<String> _books = [];

  void fetchBibleBooks() {
    _books = _bibleDataService.getBooks();
    rebuildUi();
  }
}
```

```
class BibleChatView extends StackedView<BibleChatViewModel> {
  const BibleChatView({super.key});

  @override
  Widget builder(
    BuildContext context,
    BibleChatViewModel viewModel,
    Widget? child,
  ) {
    return Scaffold(
      backgroundColor: kcChatBackground,
      appBar: ChatAppBar(
        title: viewModel.sessionConversation?.session?.title.toString() ??
            'No title',
        onHistoryPressed: viewModel.showHistoryDialog,
      ),
      body: SafeArea(
        child: Column(
          children: [
            Expanded(
                child: ChatComponent(
              conversations: viewModel.sessionConversation!.conversations!,
            )),
            const ChatBoxComponent()
          ],
        ),
      ),
    );
  }

  @override
  BibleChatViewModel viewModelBuilder(
    BuildContext context,
  ) =>
      BibleChatViewModel();
}
```

## Integrating Gemini AI SDK

The Gemini AI SDK was integrated to handle natural language inputs. It processed user queries and matched them with relevant Bible and scripture content, using a combination of machine learning models and a structured database of scriptures.

```
  GenerativeModel initializeAIModel() {
    const apiKey = 'YOUR_API_KEY';
    openModel ??= GenerativeModel(
        model: 'gemini-pro',
        apiKey: apiKey,
        generationConfig: GenerationConfig(maxOutputTokens: 1000));
    return openModel!;
  }
```

## Local Storage with sqflite

To enhance the user experience with offline capabilities, sqflite was used for local storage. It stored user chat history with Gemini, allowing for a seamless experience even without an internet connection.

```
Future<void> init() async {
    _logger.i('Initializing database');
    final directory = await getApplicationDocumentsDirectory();
    _database = await openDatabase(
      '${directory.path}/bible_chat',
      version: 1,
    );
    try {
      _logger.i('Creating database tables');
      await _databaseMigrationService.runMigration(
        _database,
        migrationFiles: [
          '1_bible_chat.sql',
        ],
        verbose: true,
      );
      _logger.i('Database tables created');
    } catch (e, s) {
      _logger.v('Error creating database tables', e, s);
    }
  }
```

## Conclusion

The development of the AI Bible chat app was a fulfilling project that combined my passion for software engineering with the power of AI. By utilizing Flutter, Gemini AI SDK, Stacked, and sqflite, I was able to create an app that not only met the technical requirements but also provided a meaningful experience to its users.

The journey doesn’t end here, though. The field of AI is constantly advancing, and there’s always room for improvement and innovation. I look forward to exploring new ways to enhance the app and bring even more value to users across the world.

This article is a high-level overview of the technical approach taken to build the AI Bible chat app. It’s intended to inspire and guide those who are interested in developing similar applications. Remember, the best technical articles are those that inform, engage, and challenge the reader to think differently about the problems they’re solving.

Here's a link to the next article titled: **[Flutter & Faith: Crafting an AI Bible Chat App with Stacked Architecture - Part 2](https://dev.to/apow/flutter-faith-crafting-an-ai-bible-chat-app-with-stacked-architecture-part-2-18no)**

Download the APK app sample (arm64) [here](https://drive.google.com/file/d/10Y4-Qy5W-mBIywQqzwLddR4z0XrtSdtI/view?usp=sharing)