Flutter Templates

Building a Real-Time Chat Application in Flutter with Back4App

35min

Introduction

Creating a chat application involves managing real-time data, user authentication, media handling, and efficient data storage. In this tutorial, you will learn how to build a real-time chat application in Flutter that supports one-to-one and group conversations, message statuses, and media sharing. We'll use Back4App—a backend-as-a-service powered by Parse Server—to handle the backend functionalities.

By the end of this tutorial, you will have a fully functional chat app with the following features:

  • User Authentication: Secure sign-up and login processes.
  • Real-Time Messaging: Instant message delivery using Live Queries.
  • User Presence: Tracking online/offline status of users.
  • Media Storage: Sending and receiving images in chats.
  • Message History: Persisting chat histories for users.

Prerequisites

To follow along with this tutorial, you'll need:

  • Flutter SDK installed on your machine. Follow the official Flutter installation guide.
  • Basic knowledge of Flutter and Dart.
  • An IDE or text editor such as Visual Studio Code or Android Studio.
  • A Back4App account. Sign up for a free account at Back4App.
  • Parse Server SDK for Flutter added to your project.

Overview

We will build a chat application with the following components:

  • User Authentication: Users can sign up and log in.
  • Contacts List: Display a list of users to chat with.
  • Chat Screen: Real-time messaging interface.
  • Media Sharing: Ability to send and receive images.
  • Online Status: Display online/offline status of users.

Step 1 – Setting Up the Flutter Project

1.1. Create a New Flutter Project

Open your terminal and run:

Bash


Navigate to the project directory:

Bash


1.2. Add Dependencies

Open pubspec.yaml and add the following dependencies:

YAML


Run flutter pub get to install the packages.

  • parse_server_sdk_flutter: Interact with Back4App.
  • image_picker: Pick images from the gallery or camera.
  • cached_network_image: Efficient image loading and caching.
  • uuid: Generate unique identifiers.


Step 2 – Setting Up Back4App

2.1. Create a New Back4App Application

  1. Log in to your Back4App dashboard.
  2. Click on "Create new App".
  3. Enter a name for your application, e.g., "ChatApp", and click "Create".

2.2. Configure Classes and Data Model

We'll create the following classes:

  1. User (Default Parse Class): Stores user information.
  2. Message: Stores chat messages.
  3. ChatRoom: Represents a chat between users.

2.2.1. User Class

  • Fields:
    • username: String
    • password: String
    • email: String
    • isOnline: Boolean
    • avatar: File (Optional)

The User class is built-in; we just need to ensure it has the additional fields.

2.2.2. Message Class

  • Fields:
    • sender: Pointer<_User>
    • receiver: Pointer<_User>
    • chatRoomId: String
    • content: String
    • image: File (Optional)
    • createdAt: DateTime (Automatically added)

2.2.3. ChatRoom Class

  • Fields:
    • chatRoomId: String
    • users: Array of Pointer<_User>
    • lastMessage: String
    • updatedAt: DateTime (Automatically updated)

2.3. Obtain Application Credentials

  1. Navigate to App Settings > Security & Keys.
  2. Note down your Application ID and Client Key.

Step 3 – Initializing Parse in Your Flutter App

Open lib/main.dart and modify it as follows:

Dart

  • Replace 'YOUR_APPLICATION_ID' and 'YOUR_CLIENT_KEY' with your actual Back4App credentials.

Step 4 – Implementing User Authentication

4.1. Create Authentication Service

Create a new directory called services under lib and add a file named auth_service.dart:

Dart


4.2. Create Login and Signup Screens

Create a new directory called screens under lib and add files named login_screen.dart and signup_screen.dart.

4.2.1. Login Screen

Dart


4.2.2. Signup Screen

Dart


Step 5 – Implementing User Presence

5.1. Update User Online Status

Create a method in AuthService to update the user's online status:

Dart


5.2. Set Online Status on Login and Logout

Update the login and logout methods:

Dart


Step 6 – Displaying Contacts List

6.1. Create User Service

Create user_service.dart under services:

Dart


6.2. Create Home Screen

Dart


Step 7 – Implementing Real-Time Messaging with Live Queries

7.1. Set Up Live Query Client

Add the following dependency in pubspec.yaml:

YAML


This ensures you have the latest version with Live Query support.

7.2. Initialize Live Query in main.dart

Dart

  • Replace 'YOUR_APP' with your Back4App application subdomain.

7.3. Create Chat Screen

Dart


Explanation

  • ParseLiveListWidget: A widget that listens to live query updates and rebuilds when data changes.
  • sendMessage(): Sends a text message or an image.
  • pickImage(): Uses image_picker to select an image and sends it as a message.
  • setupLiveQuery(): Sets up a live query to listen for new messages in the chat room.

Step 8 – Testing the App

8.1. Run the App

In your terminal, run:

Bash


8.2. Test Messaging

  • Open the app on two devices or emulators.
  • Sign up or log in with different user accounts.
  • From one account, select the other user from the contacts list.
  • Send messages and images; they should appear in real-time on both devices.

Conclusion

Congratulations! You have built a real-time chat application in Flutter using Back4App. This app supports:

  • User Authentication: Secure login and signup.
  • Real-Time Messaging: Instant updates using Live Queries.
  • User Presence: Online/offline status tracking.
  • Media Sharing: Sending and receiving images.
  • Message History: Persisting chat messages.

Next Steps

  • Group Chats: Extend the app to support group conversations.
  • Message Statuses: Implement read receipts and typing indicators.
  • Push Notifications: Send notifications for new messages when the app is in the background.
  • Profile Pictures: Allow users to upload avatars.
  • Security Enhancements: Secure data with ACLs and role-based permissions.

Additional Resources

Happy Coding!