├── LICENSE
├── README.md
├── TalkG (20-12-23).zip
├── analysis_options.yaml
├── android
├── app
│ ├── build.gradle
│ ├── google-services.json
│ └── src
│ │ ├── debug
│ │ └── AndroidManifest.xml
│ │ ├── main
│ │ ├── AndroidManifest.xml
│ │ ├── kotlin
│ │ │ └── com
│ │ │ │ └── example
│ │ │ │ └── talkg
│ │ │ │ └── MainActivity.kt
│ │ └── res
│ │ │ ├── drawable-v21
│ │ │ └── launch_background.xml
│ │ │ ├── drawable
│ │ │ └── launch_background.xml
│ │ │ ├── mipmap-hdpi
│ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-mdpi
│ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-xhdpi
│ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-xxhdpi
│ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-xxxhdpi
│ │ │ └── ic_launcher.png
│ │ │ ├── values-night
│ │ │ └── styles.xml
│ │ │ └── values
│ │ │ └── styles.xml
│ │ └── profile
│ │ └── AndroidManifest.xml
├── build.gradle
├── gradle.properties
├── gradle
│ └── wrapper
│ │ ├── gradle-wrapper.jar
│ │ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── local.properties
├── settings.gradle
└── talkg_android.iml
├── images
├── add_image.png
├── camera.png
├── google.png
└── icon.png
├── ios
├── Flutter
│ ├── AppFrameworkInfo.plist
│ ├── Debug.xcconfig
│ └── Release.xcconfig
├── Runner
│ ├── AppDelegate.swift
│ └── Assets.xcassets
│ │ └── AppIcon.appiconset
│ │ ├── Contents.json
│ │ ├── Icon-App-1024x1024@1x.png
│ │ ├── Icon-App-20x20@1x.png
│ │ ├── Icon-App-20x20@2x.png
│ │ ├── Icon-App-20x20@3x.png
│ │ ├── Icon-App-29x29@1x.png
│ │ └── Icon-App-29x29@2x.png
└── firebase_app_id_file.json
├── lib
├── api
│ └── apis.dart
├── firebase_options.dart
├── helper
│ ├── dialogs.dart
│ └── my_date_util.dart
├── main.dart
├── models
│ ├── chat_user.dart
│ └── message.dart
├── screens
│ ├── auth
│ │ └── login_screen.dart
│ ├── chat_screen.dart
│ ├── home_screen.dart
│ ├── profile_screen.dart
│ ├── splash_screen.dart
│ └── view_profile_screen.dart
└── widgets
│ ├── chat_user_card.dart
│ ├── dialogs
│ └── profile_dialog.dart
│ └── message_card.dart
├── linux
├── CMakeLists.txt
├── flutter
│ └── CMakeLists.txt
├── main.cc
├── my_application.cc
└── my_application.h
├── macos
├── Flutter
│ ├── Flutter-Debug.xcconfig
│ └── Flutter-Release.xcconfig
├── Runner.xcodeproj
│ ├── project.pbxproj
│ ├── project.xcworkspace
│ │ └── xcshareddata
│ │ │ └── IDEWorkspaceChecks.plist
│ └── xcshareddata
│ │ └── xcschemes
│ │ └── Runner.xcscheme
├── Runner.xcworkspace
│ ├── contents.xcworkspacedata
│ └── xcshareddata
│ │ └── IDEWorkspaceChecks.plist
├── Runner
│ ├── AppDelegate.swift
│ ├── Assets.xcassets
│ │ └── AppIcon.appiconset
│ │ │ ├── Contents.json
│ │ │ ├── app_icon_1024.png
│ │ │ ├── app_icon_128.png
│ │ │ ├── app_icon_16.png
│ │ │ ├── app_icon_256.png
│ │ │ ├── app_icon_32.png
│ │ │ ├── app_icon_512.png
│ │ │ └── app_icon_64.png
│ ├── Base.lproj
│ │ └── MainMenu.xib
│ ├── Configs
│ │ ├── AppInfo.xcconfig
│ │ ├── Debug.xcconfig
│ │ ├── Release.xcconfig
│ │ └── Warnings.xcconfig
│ ├── DebugProfile.entitlements
│ ├── GoogleService-Info.plist
│ ├── Info.plist
│ ├── MainFlutterWindow.swift
│ └── Release.entitlements
├── RunnerTests
│ └── RunnerTests.swift
└── firebase_app_id_file.json
├── pubspec.lock
├── pubspec.yaml
├── screenshots
├── 1.jpg
├── 2.jpg
├── 3.jpg
├── 4.jpg
├── 5.jpg
├── 6.jpg
├── 7.jpg
└── 8.jpg
├── talkg.iml
├── test
└── widget_test.dart
├── web
├── favicon.png
├── icons
│ ├── Icon-192.png
│ ├── Icon-512.png
│ ├── Icon-maskable-192.png
│ └── Icon-maskable-512.png
├── index.html
└── manifest.json
└── windows
├── CMakeLists.txt
├── flutter
└── CMakeLists.txt
└── runner
├── CMakeLists.txt
├── Runner.rc
├── flutter_window.cpp
├── flutter_window.h
├── main.cpp
├── resource.h
├── resources
└── app_icon.ico
├── runner.exe.manifest
├── utils.cpp
├── utils.h
├── win32_window.cpp
└── win32_window.h
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2025 Kartik Gosai
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # 💬 TalkG - Chat App
2 |
3 | TalkG is a **real-time, cross-platform chat application** built using **Flutter**.
4 | Designed with simplicity and speed in mind, TalkG enables users to communicate seamlessly across **Android, iOS, and Web** platforms.
5 |
6 | ---
7 |
8 | ## 🚀 Features
9 |
10 | - ⚡ Real-Time Messaging
11 | - 📱 Cross-Platform Support (**Android, iOS, Web**)
12 | - 🔐 User Authentication (**Using Firebase Auth**)
13 | - 👥 One-on-One & Group Chats, **Chat with AI**
14 | - 🟢 Activity Status
15 | - 🌙 Dark & Light Themes
16 |
17 | ---
18 |
19 | ## 🛠️ Tech Stack
20 |
21 | - **Frontend**: Flutter (Dart)
22 | - **Backend**: Firebase (Firestore, Firebase Auth, etc.)
23 |
24 | ---
25 |
26 | ## 📥 Download TalkG
27 |
28 | 📱 **Android APK** → [Download Now](https://github.com/Warrior-Gosai/Download-TalkG-App)
29 |
30 | 🌍 **Visit Website** → [http://talkg.rf.gd](http://talkg.rf.gd)
31 |
32 | ---
33 |
34 | ## 📸 Screenshots
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 | ---
51 |
52 | ## 🤝 Contributing
53 |
54 | Contributions are always welcome!
55 | If you’d like to improve the app, feel free to fork the repo and submit a pull request.
56 |
57 | ---
58 |
59 | ## 📜 License
60 |
61 | This project is licensed under the MIT License.
62 |
63 | ---
64 |
65 | ## 👤 Author
66 |
67 | **Warrior Gosai** & **SUPREME**
68 | - GitHub: [@Warrior-Gosai](https://github.com/Warrior-Gosai)
69 | - GitHub: [@SHC-SUPREME](https://github.com/SHC-SUPREME)
70 | - Website: [http://talkg.rf.gd](http://talkg.rf.gd)
71 |
72 | ---
73 |
74 | ✨ Share with your friends and enjoy chatting with **TalkG**!
75 |
--------------------------------------------------------------------------------
/TalkG (20-12-23).zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Warrior-Gosai/TalkG/2e965c5edc1735850f3db8f0fbd101c4121fee4e/TalkG (20-12-23).zip
--------------------------------------------------------------------------------
/analysis_options.yaml:
--------------------------------------------------------------------------------
1 | # This file configures the analyzer, which statically analyzes Dart code to
2 | # check for errors, warnings, and lints.
3 | #
4 | # The issues identified by the analyzer are surfaced in the UI of Dart-enabled
5 | # IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be
6 | # invoked from the command line by running `flutter analyze`.
7 |
8 | # The following line activates a set of recommended lints for Flutter apps,
9 | # packages, and plugins designed to encourage good coding practices.
10 | include: package:flutter_lints/flutter.yaml
11 |
12 | linter:
13 | # The lint rules applied to this project can be customized in the
14 | # section below to disable rules from the `package:flutter_lints/flutter.yaml`
15 | # included above or to enable additional rules. A list of all available lints
16 | # and their documentation is published at
17 | # https://dart-lang.github.io/linter/lints/index.html.
18 | #
19 | # Instead of disabling a lint rule for the entire project in the
20 | # section below, it can also be suppressed for a single line of code
21 | # or a specific dart file by using the `// ignore: name_of_lint` and
22 | # `// ignore_for_file: name_of_lint` syntax on the line or in the file
23 | # producing the lint.
24 | rules:
25 | # avoid_print: false # Uncomment to disable the `avoid_print` rule
26 | # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule
27 |
28 | # Additional information about this file can be found at
29 | # https://dart.dev/guides/language/analysis-options
30 |
--------------------------------------------------------------------------------
/android/app/build.gradle:
--------------------------------------------------------------------------------
1 | def localProperties = new Properties()
2 | def localPropertiesFile = rootProject.file('local.properties')
3 | if (localPropertiesFile.exists()) {
4 | localPropertiesFile.withReader('UTF-8') { reader ->
5 | localProperties.load(reader)
6 | }
7 | }
8 |
9 | def flutterRoot = localProperties.getProperty('flutter.sdk')
10 | if (flutterRoot == null) {
11 | throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
12 | }
13 |
14 | def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
15 | if (flutterVersionCode == null) {
16 | flutterVersionCode = '1'
17 | }
18 |
19 | def flutterVersionName = localProperties.getProperty('flutter.versionName')
20 | if (flutterVersionName == null) {
21 | flutterVersionName = '1.0'
22 | }
23 |
24 | apply plugin: 'com.android.application'
25 | apply plugin: 'kotlin-android'
26 | apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
27 |
28 | android {
29 | namespace "com.example.talkg"
30 | compileSdkVersion flutter.compileSdkVersion
31 | ndkVersion flutter.ndkVersion
32 |
33 | compileOptions {
34 | sourceCompatibility JavaVersion.VERSION_1_8
35 | targetCompatibility JavaVersion.VERSION_1_8
36 | }
37 |
38 | kotlinOptions {
39 | jvmTarget = '1.8'
40 | }
41 |
42 | sourceSets {
43 | main.java.srcDirs += 'src/main/kotlin'
44 | }
45 |
46 | defaultConfig {
47 | // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
48 | applicationId "com.example.talkg"
49 | // You can update the following values to match your application needs.
50 | // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-gradle-build-configuration.
51 | minSdkVersion flutter.minSdkVersion
52 | targetSdkVersion flutter.targetSdkVersion
53 | versionCode flutterVersionCode.toInteger()
54 | versionName flutterVersionName
55 | }
56 |
57 | buildTypes {
58 | release {
59 | // TODO: Add your own signing config for the release build.
60 | // Signing with the debug keys for now, so `flutter run --release` works.
61 | signingConfig signingConfigs.debug
62 | }
63 | }
64 | }
65 |
66 | flutter {
67 | source '../..'
68 | }
69 |
70 | dependencies {
71 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
72 | }
73 |
--------------------------------------------------------------------------------
/android/app/google-services.json:
--------------------------------------------------------------------------------
1 | {
2 | "project_info": {
3 | "project_number": "488443205841",
4 | "firebase_url": "https://talkg-app-default-rtdb.asia-southeast1.firebasedatabase.app",
5 | "project_id": "talkg-app",
6 | "storage_bucket": "talkg-app.appspot.com"
7 | },
8 | "client": [
9 | {
10 | "client_info": {
11 | "mobilesdk_app_id": "1:488443205841:android:9f61c87f4b95636c3f8df0",
12 | "android_client_info": {
13 | "package_name": "com.example.talkg"
14 | }
15 | },
16 | "oauth_client": [
17 | {
18 | "client_id": "488443205841-kfa6crqh3dlp8pmfpln7gfvkqlvnri0e.apps.googleusercontent.com",
19 | "client_type": 1,
20 | "android_info": {
21 | "package_name": "com.example.talkg",
22 | "certificate_hash": "a369478e55e2ff4052c23bf47b480c7bfbd77957"
23 | }
24 | },
25 | {
26 | "client_id": "488443205841-rt5a4baskigkv23nb659vfpfjopmdtnr.apps.googleusercontent.com",
27 | "client_type": 3
28 | }
29 | ],
30 | "api_key": [
31 | {
32 | "current_key": "AIzaSyDFzN3k6a6KWXDrbc7NQTS26lljmFrbzJY"
33 | }
34 | ],
35 | "services": {
36 | "appinvite_service": {
37 | "other_platform_oauth_client": [
38 | {
39 | "client_id": "488443205841-btda9p3vmlsh3bkusjgnt6bff47i51id.apps.googleusercontent.com",
40 | "client_type": 3
41 | },
42 | {
43 | "client_id": "488443205841-oaoru8vbmu6crv5bq9ovcfmmho1hpdij.apps.googleusercontent.com",
44 | "client_type": 2,
45 | "ios_info": {
46 | "bundle_id": "com.example.talkg.RunnerTests"
47 | }
48 | }
49 | ]
50 | }
51 | }
52 | }
53 | ],
54 | "configuration_version": "1"
55 | }
--------------------------------------------------------------------------------
/android/app/src/debug/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/android/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
14 |
18 |
22 |
23 |
24 |
25 |
26 |
27 |
29 |
32 |
33 |
34 |
--------------------------------------------------------------------------------
/android/app/src/main/kotlin/com/example/talkg/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.example.talkg
2 |
3 | import io.flutter.embedding.android.FlutterActivity
4 |
5 | class MainActivity: FlutterActivity() {
6 | }
7 |
--------------------------------------------------------------------------------
/android/app/src/main/res/drawable-v21/launch_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
12 |
13 |
--------------------------------------------------------------------------------
/android/app/src/main/res/drawable/launch_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
12 |
13 |
--------------------------------------------------------------------------------
/android/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Warrior-Gosai/TalkG/2e965c5edc1735850f3db8f0fbd101c4121fee4e/android/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/android/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Warrior-Gosai/TalkG/2e965c5edc1735850f3db8f0fbd101c4121fee4e/android/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Warrior-Gosai/TalkG/2e965c5edc1735850f3db8f0fbd101c4121fee4e/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Warrior-Gosai/TalkG/2e965c5edc1735850f3db8f0fbd101c4121fee4e/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Warrior-Gosai/TalkG/2e965c5edc1735850f3db8f0fbd101c4121fee4e/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/android/app/src/main/res/values-night/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
9 |
15 |
18 |
19 |
--------------------------------------------------------------------------------
/android/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
9 |
15 |
18 |
19 |
--------------------------------------------------------------------------------
/android/app/src/profile/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/android/build.gradle:
--------------------------------------------------------------------------------
1 | buildscript {
2 | ext.kotlin_version = '1.7.10'
3 | repositories {
4 | google()
5 | mavenCentral()
6 | }
7 |
8 | dependencies {
9 | classpath 'com.android.tools.build:gradle:7.3.0'
10 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
11 | }
12 | }
13 |
14 | allprojects {
15 | repositories {
16 | google()
17 | mavenCentral()
18 | }
19 | }
20 |
21 | rootProject.buildDir = '../build'
22 | subprojects {
23 | project.buildDir = "${rootProject.buildDir}/${project.name}"
24 | }
25 | subprojects {
26 | project.evaluationDependsOn(':app')
27 | }
28 |
29 | tasks.register("clean", Delete) {
30 | delete rootProject.buildDir
31 | }
32 |
--------------------------------------------------------------------------------
/android/gradle.properties:
--------------------------------------------------------------------------------
1 | org.gradle.jvmargs=-Xmx1536M
2 | android.useAndroidX=true
3 | android.enableJetifier=true
4 |
--------------------------------------------------------------------------------
/android/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Warrior-Gosai/TalkG/2e965c5edc1735850f3db8f0fbd101c4121fee4e/android/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/android/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | zipStoreBase=GRADLE_USER_HOME
4 | zipStorePath=wrapper/dists
5 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.5-all.zip
6 |
--------------------------------------------------------------------------------
/android/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/android/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/android/local.properties:
--------------------------------------------------------------------------------
1 | sdk.dir=C:\\Users\\OK\\AppData\\Local\\Android\\Sdk
2 | flutter.sdk=F:\\flutter
--------------------------------------------------------------------------------
/android/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app'
2 |
3 | def localPropertiesFile = new File(rootProject.projectDir, "local.properties")
4 | def properties = new Properties()
5 |
6 | assert localPropertiesFile.exists()
7 | localPropertiesFile.withReader("UTF-8") { reader -> properties.load(reader) }
8 |
9 | def flutterSdkPath = properties.getProperty("flutter.sdk")
10 | assert flutterSdkPath != null, "flutter.sdk not set in local.properties"
11 | apply from: "$flutterSdkPath/packages/flutter_tools/gradle/app_plugin_loader.gradle"
12 |
--------------------------------------------------------------------------------
/android/talkg_android.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/images/add_image.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Warrior-Gosai/TalkG/2e965c5edc1735850f3db8f0fbd101c4121fee4e/images/add_image.png
--------------------------------------------------------------------------------
/images/camera.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Warrior-Gosai/TalkG/2e965c5edc1735850f3db8f0fbd101c4121fee4e/images/camera.png
--------------------------------------------------------------------------------
/images/google.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Warrior-Gosai/TalkG/2e965c5edc1735850f3db8f0fbd101c4121fee4e/images/google.png
--------------------------------------------------------------------------------
/images/icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Warrior-Gosai/TalkG/2e965c5edc1735850f3db8f0fbd101c4121fee4e/images/icon.png
--------------------------------------------------------------------------------
/ios/Flutter/AppFrameworkInfo.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleDevelopmentRegion
6 | en
7 | CFBundleExecutable
8 | App
9 | CFBundleIdentifier
10 | io.flutter.flutter.app
11 | CFBundleInfoDictionaryVersion
12 | 6.0
13 | CFBundleName
14 | App
15 | CFBundlePackageType
16 | FMWK
17 | CFBundleShortVersionString
18 | 1.0
19 | CFBundleSignature
20 | ????
21 | CFBundleVersion
22 | 1.0
23 | MinimumOSVersion
24 | 11.0
25 |
26 |
27 |
--------------------------------------------------------------------------------
/ios/Flutter/Debug.xcconfig:
--------------------------------------------------------------------------------
1 | #include "Generated.xcconfig"
2 |
--------------------------------------------------------------------------------
/ios/Flutter/Release.xcconfig:
--------------------------------------------------------------------------------
1 | #include "Generated.xcconfig"
2 |
--------------------------------------------------------------------------------
/ios/Runner/AppDelegate.swift:
--------------------------------------------------------------------------------
1 | import UIKit
2 | import Flutter
3 |
4 | @UIApplicationMain
5 | @objc class AppDelegate: FlutterAppDelegate {
6 | override func application(
7 | _ application: UIApplication,
8 | didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
9 | ) -> Bool {
10 | GeneratedPluginRegistrant.register(with: self)
11 | return super.application(application, didFinishLaunchingWithOptions: launchOptions)
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "images" : [
3 | {
4 | "size" : "20x20",
5 | "idiom" : "iphone",
6 | "filename" : "Icon-App-20x20@2x.png",
7 | "scale" : "2x"
8 | },
9 | {
10 | "size" : "20x20",
11 | "idiom" : "iphone",
12 | "filename" : "Icon-App-20x20@3x.png",
13 | "scale" : "3x"
14 | },
15 | {
16 | "size" : "29x29",
17 | "idiom" : "iphone",
18 | "filename" : "Icon-App-29x29@1x.png",
19 | "scale" : "1x"
20 | },
21 | {
22 | "size" : "29x29",
23 | "idiom" : "iphone",
24 | "filename" : "Icon-App-29x29@2x.png",
25 | "scale" : "2x"
26 | },
27 | {
28 | "size" : "29x29",
29 | "idiom" : "iphone",
30 | "filename" : "Icon-App-29x29@3x.png",
31 | "scale" : "3x"
32 | },
33 | {
34 | "size" : "40x40",
35 | "idiom" : "iphone",
36 | "filename" : "Icon-App-40x40@2x.png",
37 | "scale" : "2x"
38 | },
39 | {
40 | "size" : "40x40",
41 | "idiom" : "iphone",
42 | "filename" : "Icon-App-40x40@3x.png",
43 | "scale" : "3x"
44 | },
45 | {
46 | "size" : "60x60",
47 | "idiom" : "iphone",
48 | "filename" : "Icon-App-60x60@2x.png",
49 | "scale" : "2x"
50 | },
51 | {
52 | "size" : "60x60",
53 | "idiom" : "iphone",
54 | "filename" : "Icon-App-60x60@3x.png",
55 | "scale" : "3x"
56 | },
57 | {
58 | "size" : "20x20",
59 | "idiom" : "ipad",
60 | "filename" : "Icon-App-20x20@1x.png",
61 | "scale" : "1x"
62 | },
63 | {
64 | "size" : "20x20",
65 | "idiom" : "ipad",
66 | "filename" : "Icon-App-20x20@2x.png",
67 | "scale" : "2x"
68 | },
69 | {
70 | "size" : "29x29",
71 | "idiom" : "ipad",
72 | "filename" : "Icon-App-29x29@1x.png",
73 | "scale" : "1x"
74 | },
75 | {
76 | "size" : "29x29",
77 | "idiom" : "ipad",
78 | "filename" : "Icon-App-29x29@2x.png",
79 | "scale" : "2x"
80 | },
81 | {
82 | "size" : "40x40",
83 | "idiom" : "ipad",
84 | "filename" : "Icon-App-40x40@1x.png",
85 | "scale" : "1x"
86 | },
87 | {
88 | "size" : "40x40",
89 | "idiom" : "ipad",
90 | "filename" : "Icon-App-40x40@2x.png",
91 | "scale" : "2x"
92 | },
93 | {
94 | "size" : "76x76",
95 | "idiom" : "ipad",
96 | "filename" : "Icon-App-76x76@1x.png",
97 | "scale" : "1x"
98 | },
99 | {
100 | "size" : "76x76",
101 | "idiom" : "ipad",
102 | "filename" : "Icon-App-76x76@2x.png",
103 | "scale" : "2x"
104 | },
105 | {
106 | "size" : "83.5x83.5",
107 | "idiom" : "ipad",
108 | "filename" : "Icon-App-83.5x83.5@2x.png",
109 | "scale" : "2x"
110 | },
111 | {
112 | "size" : "1024x1024",
113 | "idiom" : "ios-marketing",
114 | "filename" : "Icon-App-1024x1024@1x.png",
115 | "scale" : "1x"
116 | }
117 | ],
118 | "info" : {
119 | "version" : 1,
120 | "author" : "xcode"
121 | }
122 | }
123 |
--------------------------------------------------------------------------------
/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Warrior-Gosai/TalkG/2e965c5edc1735850f3db8f0fbd101c4121fee4e/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png
--------------------------------------------------------------------------------
/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Warrior-Gosai/TalkG/2e965c5edc1735850f3db8f0fbd101c4121fee4e/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png
--------------------------------------------------------------------------------
/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Warrior-Gosai/TalkG/2e965c5edc1735850f3db8f0fbd101c4121fee4e/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png
--------------------------------------------------------------------------------
/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Warrior-Gosai/TalkG/2e965c5edc1735850f3db8f0fbd101c4121fee4e/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png
--------------------------------------------------------------------------------
/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Warrior-Gosai/TalkG/2e965c5edc1735850f3db8f0fbd101c4121fee4e/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png
--------------------------------------------------------------------------------
/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Warrior-Gosai/TalkG/2e965c5edc1735850f3db8f0fbd101c4121fee4e/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png
--------------------------------------------------------------------------------
/ios/firebase_app_id_file.json:
--------------------------------------------------------------------------------
1 | {
2 | "file_generated_by": "FlutterFire CLI",
3 | "purpose": "FirebaseAppID & ProjectID for this Firebase app in this directory",
4 | "GOOGLE_APP_ID": "1:488443205841:ios:8546e84e04c2a4e53f8df0",
5 | "FIREBASE_PROJECT_ID": "talkg-app",
6 | "GCM_SENDER_ID": "488443205841"
7 | }
--------------------------------------------------------------------------------
/lib/api/apis.dart:
--------------------------------------------------------------------------------
1 | import 'dart:convert';
2 | import 'dart:developer';
3 | import 'dart:io';
4 |
5 | import 'package:cloud_firestore/cloud_firestore.dart';
6 | import 'package:firebase_auth/firebase_auth.dart';
7 | import 'package:firebase_messaging/firebase_messaging.dart';
8 | import 'package:firebase_storage/firebase_storage.dart';
9 | import 'package:http/http.dart';
10 |
11 | import '../models/chat_user.dart';
12 | import '../models/message.dart';
13 |
14 | class APIs {
15 | // for authentication
16 | static FirebaseAuth auth = FirebaseAuth.instance;
17 |
18 | // for accessing cloud firestore database
19 | static FirebaseFirestore firestore = FirebaseFirestore.instance;
20 |
21 | // for accessing firebase storage
22 | static FirebaseStorage storage = FirebaseStorage.instance;
23 |
24 | // for storing self information
25 | static late ChatUser me;
26 |
27 | // to return current user
28 | static User get user => auth.currentUser!;
29 |
30 | // for accessing firebase messaging (Push Notification)
31 | static FirebaseMessaging fMessaging = FirebaseMessaging.instance;
32 |
33 | // for getting firebase messaging token
34 | static Future getFirebaseMessagingToken() async {
35 | await fMessaging.requestPermission();
36 |
37 | await fMessaging.getToken().then((t) {
38 | if (t != null) {
39 | me.pushToken = t;
40 | log('Push Token: $t');
41 | }
42 | });
43 |
44 | // for handling foreground messages
45 | // FirebaseMessaging.onMessage.listen((RemoteMessage message) {
46 | // log('Got a message whilst in the foreground!');
47 | // log('Message data: ${message.data}');
48 |
49 | // if (message.notification != null) {
50 | // log('Message also contained a notification: ${message.notification}');
51 | // }
52 | // });
53 | }
54 |
55 | // for sending push notification
56 | static Future sendPushNotification(
57 | ChatUser chatUser, String msg) async {
58 | try {
59 | final body = {
60 | "to": chatUser.pushToken,
61 | "notification": {
62 | "title": me.name, //our name should be send
63 | "body": msg,
64 | "android_channel_id": "chats"
65 | },
66 | // "data": {
67 | // "some_data": "User ID: ${me.id}",
68 | // },
69 | };
70 |
71 | var res = await post(Uri.parse('https://fcm.googleapis.com/fcm/send'),
72 | headers: {
73 | HttpHeaders.contentTypeHeader: 'application/json',
74 | HttpHeaders.authorizationHeader:
75 | 'key=REPLACE WITH YOUR API KEY'
76 | },
77 | body: jsonEncode(body));
78 | log('Response status: ${res.statusCode}');
79 | log('Response body: ${res.body}');
80 | } catch (e) {
81 | log('\nsendPushNotificationE: $e');
82 | }
83 | }
84 |
85 | // for checking if user exists or not?
86 | static Future userExists() async {
87 | return (await firestore.collection('users').doc(user.uid).get()).exists;
88 | }
89 |
90 | // for adding an chat user for our conversation
91 | static Future addChatUser(String email) async {
92 | final data = await firestore
93 | .collection('users')
94 | .where('email', isEqualTo: email)
95 | .get();
96 |
97 | log('data: ${data.docs}');
98 |
99 | if (data.docs.isNotEmpty && data.docs.first.id != user.uid) {
100 | //user exists
101 |
102 | log('user exists: ${data.docs.first.data()}');
103 |
104 | firestore
105 | .collection('users')
106 | .doc(user.uid)
107 | .collection('my_users')
108 | .doc(data.docs.first.id)
109 | .set({});
110 |
111 | return true;
112 | } else {
113 | //user doesn't exists
114 |
115 | return false;
116 | }
117 | }
118 |
119 | // for getting current user info
120 | static Future getSelfInfo() async {
121 | await firestore.collection('users').doc(user.uid).get().then((user) async {
122 | if (user.exists) {
123 | me = ChatUser.fromJson(user.data()!);
124 | await getFirebaseMessagingToken();
125 |
126 | //for setting user status to active
127 | APIs.updateActiveStatus(true);
128 | log('My Data: ${user.data()}');
129 | } else {
130 | await createUser().then((value) => getSelfInfo());
131 | }
132 | });
133 | }
134 |
135 | // for creating a new user
136 | static Future createUser() async {
137 | final time = DateTime.now().millisecondsSinceEpoch.toString();
138 |
139 | final chatUser = ChatUser(
140 | id: user.uid,
141 | name: user.displayName.toString(),
142 | email: user.email.toString(),
143 | about: "Hey, I'm using We Chat!",
144 | image: user.photoURL.toString(),
145 | createdAt: time,
146 | isOnline: false,
147 | lastActive: time,
148 | pushToken: '');
149 |
150 | return await firestore
151 | .collection('users')
152 | .doc(user.uid)
153 | .set(chatUser.toJson());
154 | }
155 |
156 | // for getting id's of known users from firestore database
157 | static Stream>> getMyUsersId() {
158 | return firestore
159 | .collection('users')
160 | .doc(user.uid)
161 | .collection('my_users')
162 | .snapshots();
163 | }
164 |
165 | // for getting all users from firestore database
166 | static Stream>> getAllUsers(
167 | List userIds) {
168 | log('\nUserIds: $userIds');
169 |
170 | return firestore
171 | .collection('users')
172 | .where('id',
173 | whereIn: userIds.isEmpty
174 | ? ['']
175 | : userIds) //because empty list throws an error
176 | // .where('id', isNotEqualTo: user.uid)
177 | .snapshots();
178 | }
179 |
180 | // for adding an user to my user when first message is send
181 | static Future sendFirstMessage(
182 | ChatUser chatUser, String msg, Type type) async {
183 | await firestore
184 | .collection('users')
185 | .doc(chatUser.id)
186 | .collection('my_users')
187 | .doc(user.uid)
188 | .set({}).then((value) => sendMessage(chatUser, msg, type));
189 | }
190 |
191 | // for updating user information
192 | static Future updateUserInfo() async {
193 | await firestore.collection('users').doc(user.uid).update({
194 | 'name': me.name,
195 | 'about': me.about,
196 | });
197 | }
198 |
199 | // update profile picture of user
200 | static Future updateProfilePicture(File file) async {
201 | //getting image file extension
202 | final ext = file.path.split('.').last;
203 | log('Extension: $ext');
204 |
205 | //storage file ref with path
206 | final ref = storage.ref().child('profile_pictures/${user.uid}.$ext');
207 |
208 | //uploading image
209 | await ref
210 | .putFile(file, SettableMetadata(contentType: 'image/$ext'))
211 | .then((p0) {
212 | log('Data Transferred: ${p0.bytesTransferred / 1000} kb');
213 | });
214 |
215 | //updating image in firestore database
216 | me.image = await ref.getDownloadURL();
217 | await firestore
218 | .collection('users')
219 | .doc(user.uid)
220 | .update({'image': me.image});
221 | }
222 |
223 | // for getting specific user info
224 | static Stream>> getUserInfo(
225 | ChatUser chatUser) {
226 | return firestore
227 | .collection('users')
228 | .where('id', isEqualTo: chatUser.id)
229 | .snapshots();
230 | }
231 |
232 | // update online or last active status of user
233 | static Future updateActiveStatus(bool isOnline) async {
234 | firestore.collection('users').doc(user.uid).update({
235 | 'is_online': isOnline,
236 | 'last_active': DateTime.now().millisecondsSinceEpoch.toString(),
237 | 'push_token': me.pushToken,
238 | });
239 | }
240 |
241 | ///************** Chat Screen Related APIs **************
242 |
243 | // chats (collection) --> conversation_id (doc) --> messages (collection) --> message (doc)
244 |
245 | // useful for getting conversation id
246 | static String getConversationID(String id) => user.uid.hashCode <= id.hashCode
247 | ? '${user.uid}_$id'
248 | : '${id}_${user.uid}';
249 |
250 | // for getting all messages of a specific conversation from firestore database
251 | static Stream>> getAllMessages(
252 | ChatUser user) {
253 | return firestore
254 | .collection('chats/${getConversationID(user.id)}/messages/')
255 | .orderBy('sent', descending: true)
256 | .snapshots();
257 | }
258 |
259 | // for sending message
260 | static Future sendMessage(
261 | ChatUser chatUser, String msg, Type type) async {
262 | //message sending time (also used as id)
263 | final time = DateTime.now().millisecondsSinceEpoch.toString();
264 |
265 | //message to send
266 | final Message message = Message(
267 | toId: chatUser.id,
268 | msg: msg,
269 | read: '',
270 | type: type,
271 | fromId: user.uid,
272 | sent: time);
273 |
274 | final ref = firestore
275 | .collection('chats/${getConversationID(chatUser.id)}/messages/');
276 | await ref.doc(time).set(message.toJson()).then((value) =>
277 | sendPushNotification(chatUser, type == Type.text ? msg : 'image'));
278 | }
279 |
280 | //update read status of message
281 | static Future updateMessageReadStatus(Message message) async {
282 | firestore
283 | .collection('chats/${getConversationID(message.fromId)}/messages/')
284 | .doc(message.sent)
285 | .update({'read': DateTime.now().millisecondsSinceEpoch.toString()});
286 | }
287 |
288 | //get only last message of a specific chat
289 | static Stream>> getLastMessage(
290 | ChatUser user) {
291 | return firestore
292 | .collection('chats/${getConversationID(user.id)}/messages/')
293 | .orderBy('sent', descending: true)
294 | .limit(1)
295 | .snapshots();
296 | }
297 |
298 | //send chat image
299 | static Future sendChatImage(ChatUser chatUser, File file) async {
300 | //getting image file extension
301 | final ext = file.path.split('.').last;
302 |
303 | //storage file ref with path
304 | final ref = storage.ref().child(
305 | 'images/${getConversationID(chatUser.id)}/${DateTime.now().millisecondsSinceEpoch}.$ext');
306 |
307 | //uploading image
308 | await ref
309 | .putFile(file, SettableMetadata(contentType: 'image/$ext'))
310 | .then((p0) {
311 | log('Data Transferred: ${p0.bytesTransferred / 1000} kb');
312 | });
313 |
314 | //updating image in firestore database
315 | final imageUrl = await ref.getDownloadURL();
316 | await sendMessage(chatUser, imageUrl, Type.image);
317 | }
318 |
319 | //delete message
320 | static Future deleteMessage(Message message) async {
321 | await firestore
322 | .collection('chats/${getConversationID(message.toId)}/messages/')
323 | .doc(message.sent)
324 | .delete();
325 |
326 | if (message.type == Type.image) {
327 | await storage.refFromURL(message.msg).delete();
328 | }
329 | }
330 |
331 | //update message
332 | static Future updateMessage(Message message, String updatedMsg) async {
333 | await firestore
334 | .collection('chats/${getConversationID(message.toId)}/messages/')
335 | .doc(message.sent)
336 | .update({'msg': updatedMsg});
337 | }
338 | }
339 |
--------------------------------------------------------------------------------
/lib/firebase_options.dart:
--------------------------------------------------------------------------------
1 | // File generated by FlutterFire CLI.
2 | // ignore_for_file: lines_longer_than_80_chars, avoid_classes_with_only_static_members
3 | import 'package:firebase_core/firebase_core.dart' show FirebaseOptions;
4 | import 'package:flutter/foundation.dart'
5 | show defaultTargetPlatform, kIsWeb, TargetPlatform;
6 |
7 | /// Default [FirebaseOptions] for use with your Firebase apps.
8 | ///
9 | /// Example:
10 | /// ```dart
11 | /// import 'firebase_options.dart';
12 | /// // ...
13 | /// await Firebase.initializeApp(
14 | /// options: DefaultFirebaseOptions.currentPlatform,
15 | /// );
16 | /// ```
17 | class DefaultFirebaseOptions {
18 | static FirebaseOptions get currentPlatform {
19 | if (kIsWeb) {
20 | return web;
21 | }
22 | switch (defaultTargetPlatform) {
23 | case TargetPlatform.android:
24 | return android;
25 | case TargetPlatform.iOS:
26 | return ios;
27 | case TargetPlatform.macOS:
28 | return macos;
29 | case TargetPlatform.windows:
30 | throw UnsupportedError(
31 | 'DefaultFirebaseOptions have not been configured for windows - '
32 | 'you can reconfigure this by running the FlutterFire CLI again.',
33 | );
34 | case TargetPlatform.linux:
35 | throw UnsupportedError(
36 | 'DefaultFirebaseOptions have not been configured for linux - '
37 | 'you can reconfigure this by running the FlutterFire CLI again.',
38 | );
39 | default:
40 | throw UnsupportedError(
41 | 'DefaultFirebaseOptions are not supported for this platform.',
42 | );
43 | }
44 | }
45 |
46 | static const FirebaseOptions web = FirebaseOptions(
47 | apiKey: 'YOUR KEY',
48 | appId: '1:488443205841:web:7db10f23594664cc3f8df0',
49 | messagingSenderId: '488443205841',
50 | projectId: 'talkg-app',
51 | authDomain: 'talkg-app.firebaseapp.com',
52 | databaseURL: 'https://talkg-app-default-rtdb.asia-southeast1.firebasedatabase.app',
53 | storageBucket: 'talkg-app.appspot.com',
54 | );
55 |
56 | static const FirebaseOptions android = FirebaseOptions(
57 | apiKey: 'YOUR KEY',
58 | appId: '1:488443205841:android:9f61c87f4b95636c3f8df0',
59 | messagingSenderId: '488443205841',
60 | projectId: 'talkg-app',
61 | databaseURL: 'https://talkg-app-default-rtdb.asia-southeast1.firebasedatabase.app',
62 | storageBucket: 'talkg-app.appspot.com',
63 | );
64 |
65 | static const FirebaseOptions ios = FirebaseOptions(
66 | apiKey: '',
67 | appId: '1:488443205841:ios:8546e84e04c2a4e53f8df0',
68 | messagingSenderId: '488443205841',
69 | projectId: 'talkg-app',
70 | databaseURL: 'https://talkg-app-default-rtdb.asia-southeast1.firebasedatabase.app',
71 | storageBucket: 'talkg-app.appspot.com',
72 | androidClientId: '488443205841-kfa6crqh3dlp8pmfpln7gfvkqlvnri0e.apps.googleusercontent.com',
73 | iosClientId: '488443205841-ppb981j9ng25bqljlhctguq561o2snjn.apps.googleusercontent.com',
74 | iosBundleId: 'com.example.talkg',
75 | );
76 |
77 | static const FirebaseOptions macos = FirebaseOptions(
78 | apiKey: '',
79 | appId: '1:488443205841:ios:272d9a2c614b90ee3f8df0',
80 | messagingSenderId: '488443205841',
81 | projectId: 'talkg-app',
82 | databaseURL: 'https://talkg-app-default-rtdb.asia-southeast1.firebasedatabase.app',
83 | storageBucket: 'talkg-app.appspot.com',
84 | androidClientId: '488443205841-kfa6crqh3dlp8pmfpln7gfvkqlvnri0e.apps.googleusercontent.com',
85 | iosClientId: '488443205841-oaoru8vbmu6crv5bq9ovcfmmho1hpdij.apps.googleusercontent.com',
86 | iosBundleId: 'com.example.talkg.RunnerTests',
87 | );
88 | }
89 |
--------------------------------------------------------------------------------
/lib/helper/dialogs.dart:
--------------------------------------------------------------------------------
1 | import 'package:flutter/material.dart';
2 |
3 | class Dialogs {
4 | static void showSnackbar(BuildContext context, String msg) {
5 | ScaffoldMessenger.of(context).showSnackBar(SnackBar(
6 | content: Text(msg),
7 | backgroundColor: Colors.blue.withOpacity(.8),
8 | behavior: SnackBarBehavior.floating));
9 | }
10 |
11 | static void showProgressBar(BuildContext context) {
12 | showDialog(
13 | context: context,
14 | builder: (_) => const Center(child: CircularProgressIndicator()));
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/lib/helper/my_date_util.dart:
--------------------------------------------------------------------------------
1 | import 'package:flutter/material.dart';
2 |
3 | class MyDateUtil {
4 | // for getting formatted time from milliSecondsSinceEpochs String
5 | static String getFormattedTime(
6 | {required BuildContext context, required String time}) {
7 | final date = DateTime.fromMillisecondsSinceEpoch(int.parse(time));
8 | return TimeOfDay.fromDateTime(date).format(context);
9 | }
10 |
11 | // for getting formatted time for sent & read
12 | static String getMessageTime(
13 | {required BuildContext context, required String time}) {
14 | final DateTime sent = DateTime.fromMillisecondsSinceEpoch(int.parse(time));
15 | final DateTime now = DateTime.now();
16 |
17 | final formattedTime = TimeOfDay.fromDateTime(sent).format(context);
18 | if (now.day == sent.day &&
19 | now.month == sent.month &&
20 | now.year == sent.year) {
21 | return formattedTime;
22 | }
23 |
24 | return now.year == sent.year
25 | ? '$formattedTime - ${sent.day} ${_getMonth(sent)}'
26 | : '$formattedTime - ${sent.day} ${_getMonth(sent)} ${sent.year}';
27 | }
28 |
29 | //get last message time (used in chat user card)
30 | static String getLastMessageTime(
31 | {required BuildContext context,
32 | required String time,
33 | bool showYear = false}) {
34 | final DateTime sent = DateTime.fromMillisecondsSinceEpoch(int.parse(time));
35 | final DateTime now = DateTime.now();
36 |
37 | if (now.day == sent.day &&
38 | now.month == sent.month &&
39 | now.year == sent.year) {
40 | return TimeOfDay.fromDateTime(sent).format(context);
41 | }
42 |
43 | return showYear
44 | ? '${sent.day} ${_getMonth(sent)} ${sent.year}'
45 | : '${sent.day} ${_getMonth(sent)}';
46 | }
47 |
48 | //get formatted last active time of user in chat screen
49 | static String getLastActiveTime(
50 | {required BuildContext context, required String lastActive}) {
51 | final int i = int.tryParse(lastActive) ?? -1;
52 |
53 | //if time is not available then return below statement
54 | if (i == -1) return 'Last seen not available';
55 |
56 | DateTime time = DateTime.fromMillisecondsSinceEpoch(i);
57 | DateTime now = DateTime.now();
58 |
59 | String formattedTime = TimeOfDay.fromDateTime(time).format(context);
60 | if (time.day == now.day &&
61 | time.month == now.month &&
62 | time.year == time.year) {
63 | return 'Last seen today at $formattedTime';
64 | }
65 |
66 | if ((now.difference(time).inHours / 24).round() == 1) {
67 | return 'Last seen yesterday at $formattedTime';
68 | }
69 |
70 | String month = _getMonth(time);
71 |
72 | return 'Last seen on ${time.day} $month on $formattedTime';
73 | }
74 |
75 | // get month name from month no. or index
76 | static String _getMonth(DateTime date) {
77 | switch (date.month) {
78 | case 1:
79 | return 'Jan';
80 | case 2:
81 | return 'Feb';
82 | case 3:
83 | return 'Mar';
84 | case 4:
85 | return 'Apr';
86 | case 5:
87 | return 'May';
88 | case 6:
89 | return 'Jun';
90 | case 7:
91 | return 'Jul';
92 | case 8:
93 | return 'Aug';
94 | case 9:
95 | return 'Sept';
96 | case 10:
97 | return 'Oct';
98 | case 11:
99 | return 'Nov';
100 | case 12:
101 | return 'Dec';
102 | }
103 | return 'NA';
104 | }
105 | }
106 |
--------------------------------------------------------------------------------
/lib/main.dart:
--------------------------------------------------------------------------------
1 | import 'dart:developer';
2 |
3 | import 'package:flutter/material.dart';
4 | import 'package:flutter/services.dart';
5 | import 'package:flutter_notification_channel/flutter_notification_channel.dart';
6 | import 'package:flutter_notification_channel/notification_importance.dart';
7 | import 'screens/splash_screen.dart';
8 |
9 | import 'package:firebase_core/firebase_core.dart';
10 | import 'firebase_options.dart';
11 |
12 | //global object for accessing device screen size
13 | late Size mq;
14 |
15 | void main() {
16 | WidgetsFlutterBinding.ensureInitialized();
17 |
18 | //enter full-screen
19 | SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);
20 |
21 | //for setting orientation to portrait only
22 | SystemChrome.setPreferredOrientations(
23 | [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown])
24 | .then((value) {
25 | _initializeFirebase();
26 | runApp(const MyApp());
27 | });
28 | }
29 |
30 | class MyApp extends StatelessWidget {
31 | const MyApp({super.key});
32 |
33 | @override
34 | Widget build(BuildContext context) {
35 | return MaterialApp(
36 | title: 'TalkG',
37 | debugShowCheckedModeBanner: false,
38 | theme: ThemeData(
39 | appBarTheme: const AppBarTheme(
40 | centerTitle: true,
41 | elevation: 1,
42 | iconTheme: IconThemeData(color: Colors.black),
43 | titleTextStyle: TextStyle(
44 | color: Colors.black, fontWeight: FontWeight.normal, fontSize: 19),
45 | backgroundColor: Colors.white,
46 | )),
47 | home: const SplashScreen());
48 | }
49 | }
50 |
51 | _initializeFirebase() async {
52 | await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
53 |
54 | var result = await FlutterNotificationChannel.registerNotificationChannel(
55 | description: 'For Showing Message Notification',
56 | id: 'chats',
57 | importance: NotificationImportance.IMPORTANCE_HIGH,
58 | name: 'Chats');
59 | log('\nNotification Channel Result: $result');
60 | }
61 |
--------------------------------------------------------------------------------
/lib/models/chat_user.dart:
--------------------------------------------------------------------------------
1 | class ChatUser {
2 | ChatUser({
3 | required this.image,
4 | required this.about,
5 | required this.name,
6 | required this.createdAt,
7 | required this.isOnline,
8 | required this.id,
9 | required this.lastActive,
10 | required this.email,
11 | required this.pushToken,
12 | });
13 | late String image;
14 | late String about;
15 | late String name;
16 | late String createdAt;
17 | late bool isOnline;
18 | late String id;
19 | late String lastActive;
20 | late String email;
21 | late String pushToken;
22 |
23 | ChatUser.fromJson(Map json) {
24 | image = json['image'] ?? '';
25 | about = json['about'] ?? '';
26 | name = json['name'] ?? '';
27 | createdAt = json['created_at'] ?? '';
28 | isOnline = json['is_online'] ?? '';
29 | id = json['id'] ?? '';
30 | lastActive = json['last_active'] ?? '';
31 | email = json['email'] ?? '';
32 | pushToken = json['push_token'] ?? '';
33 | }
34 |
35 | Map toJson() {
36 | final data = {};
37 | data['image'] = image;
38 | data['about'] = about;
39 | data['name'] = name;
40 | data['created_at'] = createdAt;
41 | data['is_online'] = isOnline;
42 | data['id'] = id;
43 | data['last_active'] = lastActive;
44 | data['email'] = email;
45 | data['push_token'] = pushToken;
46 | return data;
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/lib/models/message.dart:
--------------------------------------------------------------------------------
1 | class Message {
2 | Message({
3 | required this.toId,
4 | required this.msg,
5 | required this.read,
6 | required this.type,
7 | required this.fromId,
8 | required this.sent,
9 | });
10 |
11 | late final String toId;
12 | late final String msg;
13 | late final String read;
14 | late final String fromId;
15 | late final String sent;
16 | late final Type type;
17 |
18 | Message.fromJson(Map json) {
19 | toId = json['toId'].toString();
20 | msg = json['msg'].toString();
21 | read = json['read'].toString();
22 | type = json['type'].toString() == Type.image.name ? Type.image : Type.text;
23 | fromId = json['fromId'].toString();
24 | sent = json['sent'].toString();
25 | }
26 |
27 | Map toJson() {
28 | final data = {};
29 | data['toId'] = toId;
30 | data['msg'] = msg;
31 | data['read'] = read;
32 | data['type'] = type.name;
33 | data['fromId'] = fromId;
34 | data['sent'] = sent;
35 | return data;
36 | }
37 | }
38 |
39 | enum Type { text, image }
40 |
--------------------------------------------------------------------------------
/lib/screens/auth/login_screen.dart:
--------------------------------------------------------------------------------
1 | import 'dart:developer';
2 | import 'dart:io';
3 |
4 | import 'package:firebase_auth/firebase_auth.dart';
5 | import 'package:flutter/material.dart';
6 | import 'package:google_sign_in/google_sign_in.dart';
7 |
8 | import '../../api/apis.dart';
9 | import '../../helper/dialogs.dart';
10 | import '../../main.dart';
11 | import '../home_screen.dart';
12 |
13 | //login screen -- implements google sign in or sign up feature for app
14 | class LoginScreen extends StatefulWidget {
15 | const LoginScreen({super.key});
16 |
17 | @override
18 | State createState() => _LoginScreenState();
19 | }
20 |
21 | class _LoginScreenState extends State {
22 | bool _isAnimate = false;
23 |
24 | @override
25 | void initState() {
26 | super.initState();
27 |
28 | //for auto triggering animation
29 | Future.delayed(const Duration(milliseconds: 500), () {
30 | setState(() => _isAnimate = true);
31 | });
32 | }
33 |
34 | // handles google login button click
35 | _handleGoogleBtnClick() {
36 | //for showing progress bar
37 | Dialogs.showProgressBar(context);
38 |
39 | _signInWithGoogle().then((user) async {
40 | //for hiding progress bar
41 | Navigator.pop(context);
42 |
43 | if (user != null) {
44 | log('\nUser: ${user.user}');
45 | log('\nUserAdditionalInfo: ${user.additionalUserInfo}');
46 |
47 | if ((await APIs.userExists())) {
48 | // ignore: use_build_context_synchronously
49 | Navigator.pushReplacement(
50 | context, MaterialPageRoute(builder: (_) => const HomeScreen()));
51 | } else {
52 | await APIs.createUser().then((value) {
53 | Navigator.pushReplacement(
54 | context, MaterialPageRoute(builder: (_) => const HomeScreen()));
55 | });
56 | }
57 | }
58 | });
59 | }
60 |
61 | Future _signInWithGoogle() async {
62 | try {
63 | await InternetAddress.lookup('google.com');
64 | // Trigger the authentication flow
65 | final GoogleSignInAccount? googleUser = await GoogleSignIn().signIn();
66 |
67 | // Obtain the auth details from the request
68 | final GoogleSignInAuthentication? googleAuth =
69 | await googleUser?.authentication;
70 |
71 | // Create a new credential
72 | final credential = GoogleAuthProvider.credential(
73 | accessToken: googleAuth?.accessToken,
74 | idToken: googleAuth?.idToken,
75 | );
76 |
77 | // Once signed in, return the UserCredential
78 | return await APIs.auth.signInWithCredential(credential);
79 | } catch (e) {
80 | log('\n_signInWithGoogle: $e');
81 | Dialogs.showSnackbar(context, 'Something Went Wrong (Check Internet!)');
82 | return null;
83 | }
84 | }
85 |
86 | //sign out function
87 | // _signOut() async {
88 | // await FirebaseAuth.instance.signOut();
89 | // await GoogleSignIn().signOut();
90 | // }
91 |
92 | @override
93 | Widget build(BuildContext context) {
94 | //initializing media query (for getting device screen size)
95 | // mq = MediaQuery.of(context).size;
96 |
97 | return Scaffold(
98 | //app bar
99 | appBar: AppBar(
100 | automaticallyImplyLeading: false,
101 | title: const Text('Welcome to We Chat'),
102 | ),
103 |
104 | //body
105 | body: Stack(children: [
106 | //app logo
107 | AnimatedPositioned(
108 | top: mq.height * .15,
109 | right: _isAnimate ? mq.width * .25 : -mq.width * .5,
110 | width: mq.width * .5,
111 | duration: const Duration(seconds: 1),
112 | child: Image.asset('images/icon.png')),
113 |
114 | //google login button
115 | Positioned(
116 | bottom: mq.height * .15,
117 | left: mq.width * .05,
118 | width: mq.width * .9,
119 | height: mq.height * .06,
120 | child: ElevatedButton.icon(
121 | style: ElevatedButton.styleFrom(
122 | backgroundColor: const Color.fromARGB(255, 223, 255, 187),
123 | shape: const StadiumBorder(),
124 | elevation: 1),
125 | onPressed: () {
126 | _handleGoogleBtnClick();
127 | },
128 |
129 | //google icon
130 | icon: Image.asset('images/google.png', height: mq.height * .03),
131 |
132 | //login with google label
133 | label: RichText(
134 | text: const TextSpan(
135 | style: TextStyle(color: Colors.black, fontSize: 16),
136 | children: [
137 | TextSpan(text: 'Login with '),
138 | TextSpan(
139 | text: 'Google',
140 | style: TextStyle(fontWeight: FontWeight.w500)),
141 | ]),
142 | ))),
143 | ]),
144 | );
145 | }
146 | }
147 |
--------------------------------------------------------------------------------
/lib/screens/chat_screen.dart:
--------------------------------------------------------------------------------
1 | import 'dart:developer';
2 | import 'dart:io';
3 |
4 | import 'package:cached_network_image/cached_network_image.dart';
5 | import 'package:emoji_picker_flutter/emoji_picker_flutter.dart';
6 | import 'package:flutter/cupertino.dart';
7 | import 'package:flutter/material.dart';
8 | import 'package:image_picker/image_picker.dart';
9 |
10 | import '../api/apis.dart';
11 | import '../helper/my_date_util.dart';
12 | import '../main.dart';
13 | import '../models/chat_user.dart';
14 | import '../models/message.dart';
15 | import '../widgets/message_card.dart';
16 | import 'view_profile_screen.dart';
17 |
18 | class ChatScreen extends StatefulWidget {
19 | final ChatUser user;
20 |
21 | const ChatScreen({super.key, required this.user});
22 |
23 | @override
24 | State createState() => _ChatScreenState();
25 | }
26 |
27 | class _ChatScreenState extends State {
28 | //for storing all messages
29 | List _list = [];
30 |
31 | //for handling message text changes
32 | final _textController = TextEditingController();
33 |
34 | //showEmoji -- for storing value of showing or hiding emoji
35 | //isUploading -- for checking if image is uploading or not?
36 | bool _showEmoji = false, _isUploading = false;
37 |
38 | @override
39 | Widget build(BuildContext context) {
40 | return GestureDetector(
41 | onTap: () => FocusScope.of(context).unfocus(),
42 | child: SafeArea(
43 | child: WillPopScope(
44 | //if emojis are shown & back button is pressed then hide emojis
45 | //or else simple close current screen on back button click
46 | onWillPop: () {
47 | if (_showEmoji) {
48 | setState(() => _showEmoji = !_showEmoji);
49 | return Future.value(false);
50 | } else {
51 | return Future.value(true);
52 | }
53 | },
54 | child: Scaffold(
55 | //app bar
56 | appBar: AppBar(
57 | automaticallyImplyLeading: false,
58 | flexibleSpace: _appBar(),
59 | ),
60 |
61 | backgroundColor: const Color.fromARGB(255, 234, 248, 255),
62 |
63 | //body
64 | body: Column(
65 | children: [
66 | Expanded(
67 | child: StreamBuilder(
68 | stream: APIs.getAllMessages(widget.user),
69 | builder: (context, snapshot) {
70 | switch (snapshot.connectionState) {
71 | //if data is loading
72 | case ConnectionState.waiting:
73 | case ConnectionState.none:
74 | return const SizedBox();
75 |
76 | //if some or all data is loaded then show it
77 | case ConnectionState.active:
78 | case ConnectionState.done:
79 | final data = snapshot.data?.docs;
80 | _list = data
81 | ?.map((e) => Message.fromJson(e.data()))
82 | .toList() ??
83 | [];
84 |
85 | if (_list.isNotEmpty) {
86 | return ListView.builder(
87 | reverse: true,
88 | itemCount: _list.length,
89 | padding: EdgeInsets.only(top: mq.height * .01),
90 | physics: const BouncingScrollPhysics(),
91 | itemBuilder: (context, index) {
92 | return MessageCard(message: _list[index]);
93 | });
94 | } else {
95 | return const Center(
96 | child: Text('Say Hii! 👋',
97 | style: TextStyle(fontSize: 20)),
98 | );
99 | }
100 | }
101 | },
102 | ),
103 | ),
104 |
105 | //progress indicator for showing uploading
106 | if (_isUploading)
107 | const Align(
108 | alignment: Alignment.centerRight,
109 | child: Padding(
110 | padding:
111 | EdgeInsets.symmetric(vertical: 8, horizontal: 20),
112 | child: CircularProgressIndicator(strokeWidth: 2))),
113 |
114 | //chat input filed
115 | _chatInput(),
116 |
117 | //show emojis on keyboard emoji button click & vice versa
118 | if (_showEmoji)
119 | SizedBox(
120 | height: mq.height * .35,
121 | child: EmojiPicker(
122 | textEditingController: _textController,
123 | config: Config(
124 | bgColor: const Color.fromARGB(255, 234, 248, 255),
125 | columns: 8,
126 | emojiSizeMax: 32 * (Platform.isIOS ? 1.30 : 1.0),
127 | ),
128 | ),
129 | )
130 | ],
131 | ),
132 | ),
133 | ),
134 | ),
135 | );
136 | }
137 |
138 | // app bar widget
139 | Widget _appBar() {
140 | return InkWell(
141 | onTap: () {
142 | Navigator.push(
143 | context,
144 | MaterialPageRoute(
145 | builder: (_) => ViewProfileScreen(user: widget.user)));
146 | },
147 | child: StreamBuilder(
148 | stream: APIs.getUserInfo(widget.user),
149 | builder: (context, snapshot) {
150 | final data = snapshot.data?.docs;
151 | final list =
152 | data?.map((e) => ChatUser.fromJson(e.data())).toList() ?? [];
153 |
154 | return Row(
155 | children: [
156 | //back button
157 | IconButton(
158 | onPressed: () => Navigator.pop(context),
159 | icon:
160 | const Icon(Icons.arrow_back, color: Colors.black54)),
161 |
162 | //user profile picture
163 | ClipRRect(
164 | borderRadius: BorderRadius.circular(mq.height * .03),
165 | child: CachedNetworkImage(
166 | width: mq.height * .05,
167 | height: mq.height * .05,
168 | imageUrl:
169 | list.isNotEmpty ? list[0].image : widget.user.image,
170 | errorWidget: (context, url, error) => const CircleAvatar(
171 | child: Icon(CupertinoIcons.person)),
172 | ),
173 | ),
174 |
175 | //for adding some space
176 | const SizedBox(width: 10),
177 |
178 | //user name & last seen time
179 | Column(
180 | mainAxisAlignment: MainAxisAlignment.center,
181 | crossAxisAlignment: CrossAxisAlignment.start,
182 | children: [
183 | //user name
184 | Text(list.isNotEmpty ? list[0].name : widget.user.name,
185 | style: const TextStyle(
186 | fontSize: 16,
187 | color: Colors.black87,
188 | fontWeight: FontWeight.w500)),
189 |
190 | //for adding some space
191 | const SizedBox(height: 2),
192 |
193 | //last seen time of user
194 | Text(
195 | list.isNotEmpty
196 | ? list[0].isOnline
197 | ? 'Online'
198 | : MyDateUtil.getLastActiveTime(
199 | context: context,
200 | lastActive: list[0].lastActive)
201 | : MyDateUtil.getLastActiveTime(
202 | context: context,
203 | lastActive: widget.user.lastActive),
204 | style: const TextStyle(
205 | fontSize: 13, color: Colors.black54)),
206 | ],
207 | )
208 | ],
209 | );
210 | }));
211 | }
212 |
213 | // bottom chat input field
214 | Widget _chatInput() {
215 | return Padding(
216 | padding: EdgeInsets.symmetric(
217 | vertical: mq.height * .01, horizontal: mq.width * .025),
218 | child: Row(
219 | children: [
220 | //input field & buttons
221 | Expanded(
222 | child: Card(
223 | shape: RoundedRectangleBorder(
224 | borderRadius: BorderRadius.circular(15)),
225 | child: Row(
226 | children: [
227 | //emoji button
228 | IconButton(
229 | onPressed: () {
230 | FocusScope.of(context).unfocus();
231 | setState(() => _showEmoji = !_showEmoji);
232 | },
233 | icon: const Icon(Icons.emoji_emotions,
234 | color: Colors.blueAccent, size: 25)),
235 |
236 | Expanded(
237 | child: TextField(
238 | controller: _textController,
239 | keyboardType: TextInputType.multiline,
240 | maxLines: null,
241 | onTap: () {
242 | if (_showEmoji) setState(() => _showEmoji = !_showEmoji);
243 | },
244 | decoration: const InputDecoration(
245 | hintText: 'Type Something...',
246 | hintStyle: TextStyle(color: Colors.blueAccent),
247 | border: InputBorder.none),
248 | )),
249 |
250 | //pick image from gallery button
251 | IconButton(
252 | onPressed: () async {
253 | final ImagePicker picker = ImagePicker();
254 |
255 | // Picking multiple images
256 | final List images =
257 | await picker.pickMultiImage(imageQuality: 70);
258 |
259 | // uploading & sending image one by one
260 | for (var i in images) {
261 | log('Image Path: ${i.path}');
262 | setState(() => _isUploading = true);
263 | await APIs.sendChatImage(widget.user, File(i.path));
264 | setState(() => _isUploading = false);
265 | }
266 | },
267 | icon: const Icon(Icons.image,
268 | color: Colors.blueAccent, size: 26)),
269 |
270 | //take image from camera button
271 | IconButton(
272 | onPressed: () async {
273 | final ImagePicker picker = ImagePicker();
274 |
275 | // Pick an image
276 | final XFile? image = await picker.pickImage(
277 | source: ImageSource.camera, imageQuality: 70);
278 | if (image != null) {
279 | log('Image Path: ${image.path}');
280 | setState(() => _isUploading = true);
281 |
282 | await APIs.sendChatImage(
283 | widget.user, File(image.path));
284 | setState(() => _isUploading = false);
285 | }
286 | },
287 | icon: const Icon(Icons.camera_alt_rounded,
288 | color: Colors.blueAccent, size: 26)),
289 |
290 | //adding some space
291 | SizedBox(width: mq.width * .02),
292 | ],
293 | ),
294 | ),
295 | ),
296 |
297 | //send message button
298 | MaterialButton(
299 | onPressed: () {
300 | if (_textController.text.isNotEmpty) {
301 | if (_list.isEmpty) {
302 | //on first message (add user to my_user collection of chat user)
303 | APIs.sendFirstMessage(
304 | widget.user, _textController.text, Type.text);
305 | } else {
306 | //simply send message
307 | APIs.sendMessage(
308 | widget.user, _textController.text, Type.text);
309 | }
310 | _textController.text = '';
311 | }
312 | },
313 | minWidth: 0,
314 | padding:
315 | const EdgeInsets.only(top: 10, bottom: 10, right: 5, left: 10),
316 | shape: const CircleBorder(),
317 | color: Colors.green,
318 | child: const Icon(Icons.send, color: Colors.white, size: 28),
319 | )
320 | ],
321 | ),
322 | );
323 | }
324 | }
325 |
--------------------------------------------------------------------------------
/lib/screens/home_screen.dart:
--------------------------------------------------------------------------------
1 | import 'dart:developer';
2 |
3 | import 'package:flutter/cupertino.dart';
4 | import 'package:flutter/material.dart';
5 | import 'package:flutter/services.dart';
6 |
7 | import '../api/apis.dart';
8 | import '../helper/dialogs.dart';
9 | import '../main.dart';
10 | import '../models/chat_user.dart';
11 | import '../widgets/chat_user_card.dart';
12 | import 'profile_screen.dart';
13 |
14 | //home screen -- where all available contacts are shown
15 | class HomeScreen extends StatefulWidget {
16 | const HomeScreen({super.key});
17 |
18 | @override
19 | State createState() => _HomeScreenState();
20 | }
21 |
22 | class _HomeScreenState extends State {
23 | // for storing all users
24 | List _list = [];
25 |
26 | // for storing searched items
27 | final List _searchList = [];
28 | // for storing search status
29 | bool _isSearching = false;
30 |
31 | @override
32 | void initState() {
33 | super.initState();
34 | APIs.getSelfInfo();
35 |
36 | //for updating user active status according to lifecycle events
37 | //resume -- active or online
38 | //pause -- inactive or offline
39 | SystemChannels.lifecycle.setMessageHandler((message) {
40 | log('Message: $message');
41 |
42 | if (APIs.auth.currentUser != null) {
43 | if (message.toString().contains('resume')) {
44 | APIs.updateActiveStatus(true);
45 | }
46 | if (message.toString().contains('pause')) {
47 | APIs.updateActiveStatus(false);
48 | }
49 | }
50 |
51 | return Future.value(message);
52 | });
53 | }
54 |
55 | @override
56 | Widget build(BuildContext context) {
57 | return GestureDetector(
58 | //for hiding keyboard when a tap is detected on screen
59 | onTap: () => FocusScope.of(context).unfocus(),
60 | child: WillPopScope(
61 | //if search is on & back button is pressed then close search
62 | //or else simple close current screen on back button click
63 | onWillPop: () {
64 | if (_isSearching) {
65 | setState(() {
66 | _isSearching = !_isSearching;
67 | });
68 | return Future.value(false);
69 | } else {
70 | return Future.value(true);
71 | }
72 | },
73 | child: Scaffold(
74 | //app bar
75 | appBar: AppBar(
76 | leading: const Icon(CupertinoIcons.home),
77 | title: _isSearching
78 | ? TextField(
79 | decoration: const InputDecoration(
80 | border: InputBorder.none, hintText: 'Name, Email, ...'),
81 | autofocus: true,
82 | style: const TextStyle(fontSize: 17, letterSpacing: 0.5),
83 | //when search text changes then updated search list
84 | onChanged: (val) {
85 | //search logic
86 | _searchList.clear();
87 |
88 | for (var i in _list) {
89 | if (i.name.toLowerCase().contains(val.toLowerCase()) ||
90 | i.email.toLowerCase().contains(val.toLowerCase())) {
91 | _searchList.add(i);
92 | setState(() {
93 | _searchList;
94 | });
95 | }
96 | }
97 | },
98 | )
99 | : const Text('We Chat'),
100 | actions: [
101 | //search user button
102 | IconButton(
103 | onPressed: () {
104 | setState(() {
105 | _isSearching = !_isSearching;
106 | });
107 | },
108 | icon: Icon(_isSearching
109 | ? CupertinoIcons.clear_circled_solid
110 | : Icons.search)),
111 |
112 | //more features button
113 | IconButton(
114 | onPressed: () {
115 | Navigator.push(
116 | context,
117 | MaterialPageRoute(
118 | builder: (_) => ProfileScreen(user: APIs.me)));
119 | },
120 | icon: const Icon(Icons.more_vert))
121 | ],
122 | ),
123 |
124 | //floating button to add new user
125 | floatingActionButton: Padding(
126 | padding: const EdgeInsets.only(bottom: 10),
127 | child: FloatingActionButton(
128 | onPressed: () {
129 | _addChatUserDialog();
130 | },
131 | child: const Icon(Icons.add_comment_rounded)),
132 | ),
133 |
134 | //body
135 | body: StreamBuilder(
136 | stream: APIs.getMyUsersId(),
137 |
138 | //get id of only known users
139 | builder: (context, snapshot) {
140 | switch (snapshot.connectionState) {
141 | //if data is loading
142 | case ConnectionState.waiting:
143 | case ConnectionState.none:
144 | return const Center(child: CircularProgressIndicator());
145 |
146 | //if some or all data is loaded then show it
147 | case ConnectionState.active:
148 | case ConnectionState.done:
149 | return StreamBuilder(
150 | stream: APIs.getAllUsers(
151 | snapshot.data?.docs.map((e) => e.id).toList() ?? []),
152 |
153 | //get only those user, who's ids are provided
154 | builder: (context, snapshot) {
155 | switch (snapshot.connectionState) {
156 | //if data is loading
157 | case ConnectionState.waiting:
158 | case ConnectionState.none:
159 | // return const Center(
160 | // child: CircularProgressIndicator());
161 |
162 | //if some or all data is loaded then show it
163 | case ConnectionState.active:
164 | case ConnectionState.done:
165 | final data = snapshot.data?.docs;
166 | _list = data
167 | ?.map((e) => ChatUser.fromJson(e.data()))
168 | .toList() ??
169 | [];
170 |
171 | if (_list.isNotEmpty) {
172 | return ListView.builder(
173 | itemCount: _isSearching
174 | ? _searchList.length
175 | : _list.length,
176 | padding: EdgeInsets.only(top: mq.height * .01),
177 | physics: const BouncingScrollPhysics(),
178 | itemBuilder: (context, index) {
179 | return ChatUserCard(
180 | user: _isSearching
181 | ? _searchList[index]
182 | : _list[index]);
183 | });
184 | } else {
185 | return const Center(
186 | child: Text('No Connections Found!',
187 | style: TextStyle(fontSize: 20)),
188 | );
189 | }
190 | }
191 | },
192 | );
193 | }
194 | },
195 | ),
196 | ),
197 | ),
198 | );
199 | }
200 |
201 | // for adding new chat user
202 | void _addChatUserDialog() {
203 | String email = '';
204 |
205 | showDialog(
206 | context: context,
207 | builder: (_) => AlertDialog(
208 | contentPadding: const EdgeInsets.only(
209 | left: 24, right: 24, top: 20, bottom: 10),
210 |
211 | shape: RoundedRectangleBorder(
212 | borderRadius: BorderRadius.circular(20)),
213 |
214 | //title
215 | title: const Row(
216 | children: [
217 | Icon(
218 | Icons.person_add,
219 | color: Colors.blue,
220 | size: 28,
221 | ),
222 | Text(' Add User')
223 | ],
224 | ),
225 |
226 | //content
227 | content: TextFormField(
228 | maxLines: null,
229 | onChanged: (value) => email = value,
230 | decoration: InputDecoration(
231 | hintText: 'Email Id',
232 | prefixIcon: const Icon(Icons.email, color: Colors.blue),
233 | border: OutlineInputBorder(
234 | borderRadius: BorderRadius.circular(15))),
235 | ),
236 |
237 | //actions
238 | actions: [
239 | //cancel button
240 | MaterialButton(
241 | onPressed: () {
242 | //hide alert dialog
243 | Navigator.pop(context);
244 | },
245 | child: const Text('Cancel',
246 | style: TextStyle(color: Colors.blue, fontSize: 16))),
247 |
248 | //add button
249 | MaterialButton(
250 | onPressed: () async {
251 | //hide alert dialog
252 | Navigator.pop(context);
253 | if (email.isNotEmpty) {
254 | await APIs.addChatUser(email).then((value) {
255 | if (!value) {
256 | Dialogs.showSnackbar(
257 | context, 'User does not Exists!');
258 | }
259 | });
260 | }
261 | },
262 | child: const Text(
263 | 'Add',
264 | style: TextStyle(color: Colors.blue, fontSize: 16),
265 | ))
266 | ],
267 | ));
268 | }
269 | }
270 |
--------------------------------------------------------------------------------
/lib/screens/profile_screen.dart:
--------------------------------------------------------------------------------
1 | // ignore_for_file: use_build_context_synchronously
2 |
3 | import 'dart:developer';
4 | import 'dart:io';
5 |
6 | import 'package:cached_network_image/cached_network_image.dart';
7 | import 'package:firebase_auth/firebase_auth.dart';
8 | import 'package:flutter/cupertino.dart';
9 | import 'package:flutter/material.dart';
10 | import 'package:google_sign_in/google_sign_in.dart';
11 | import 'package:image_picker/image_picker.dart';
12 |
13 | import '../api/apis.dart';
14 | import '../helper/dialogs.dart';
15 | import '../main.dart';
16 | import '../models/chat_user.dart';
17 | import 'auth/login_screen.dart';
18 |
19 | //profile screen -- to show signed in user info
20 | class ProfileScreen extends StatefulWidget {
21 | final ChatUser user;
22 |
23 | const ProfileScreen({super.key, required this.user});
24 |
25 | @override
26 | State createState() => _ProfileScreenState();
27 | }
28 |
29 | class _ProfileScreenState extends State {
30 | final _formKey = GlobalKey();
31 | String? _image;
32 |
33 | @override
34 | Widget build(BuildContext context) {
35 | return GestureDetector(
36 | // for hiding keyboard
37 | onTap: () => FocusScope.of(context).unfocus(),
38 | child: Scaffold(
39 | //app bar
40 | appBar: AppBar(title: const Text('Profile Screen')),
41 |
42 | //floating button to log out
43 | floatingActionButton: Padding(
44 | padding: const EdgeInsets.only(bottom: 10),
45 | child: FloatingActionButton.extended(
46 | backgroundColor: Colors.redAccent,
47 | onPressed: () async {
48 | //for showing progress dialog
49 | Dialogs.showProgressBar(context);
50 |
51 | await APIs.updateActiveStatus(false);
52 |
53 | //sign out from app
54 | await APIs.auth.signOut().then((value) async {
55 | await GoogleSignIn().signOut().then((value) {
56 | //for hiding progress dialog
57 | Navigator.pop(context);
58 |
59 | //for moving to home screen
60 | Navigator.pop(context);
61 |
62 | APIs.auth = FirebaseAuth.instance;
63 |
64 | //replacing home screen with login screen
65 | Navigator.pushReplacement(
66 | context,
67 | MaterialPageRoute(
68 | builder: (_) => const LoginScreen()));
69 | });
70 | });
71 | },
72 | icon: const Icon(Icons.logout),
73 | label: const Text('Logout')),
74 | ),
75 |
76 | //body
77 | body: Form(
78 | key: _formKey,
79 | child: Padding(
80 | padding: EdgeInsets.symmetric(horizontal: mq.width * .05),
81 | child: SingleChildScrollView(
82 | child: Column(
83 | children: [
84 | // for adding some space
85 | SizedBox(width: mq.width, height: mq.height * .03),
86 |
87 | //user profile picture
88 | Stack(
89 | children: [
90 | //profile picture
91 | _image != null
92 | ?
93 |
94 | //local image
95 | ClipRRect(
96 | borderRadius:
97 | BorderRadius.circular(mq.height * .1),
98 | child: Image.file(File(_image!),
99 | width: mq.height * .2,
100 | height: mq.height * .2,
101 | fit: BoxFit.cover))
102 | :
103 |
104 | //image from server
105 | ClipRRect(
106 | borderRadius:
107 | BorderRadius.circular(mq.height * .1),
108 | child: CachedNetworkImage(
109 | width: mq.height * .2,
110 | height: mq.height * .2,
111 | fit: BoxFit.cover,
112 | imageUrl: widget.user.image,
113 | errorWidget: (context, url, error) =>
114 | const CircleAvatar(
115 | child: Icon(CupertinoIcons.person)),
116 | ),
117 | ),
118 |
119 | //edit image button
120 | Positioned(
121 | bottom: 0,
122 | right: 0,
123 | child: MaterialButton(
124 | elevation: 1,
125 | onPressed: () {
126 | _showBottomSheet();
127 | },
128 | shape: const CircleBorder(),
129 | color: Colors.white,
130 | child: const Icon(Icons.edit, color: Colors.blue),
131 | ),
132 | )
133 | ],
134 | ),
135 |
136 | // for adding some space
137 | SizedBox(height: mq.height * .03),
138 |
139 | // user email label
140 | Text(widget.user.email,
141 | style: const TextStyle(
142 | color: Colors.black54, fontSize: 16)),
143 |
144 | // for adding some space
145 | SizedBox(height: mq.height * .05),
146 |
147 | // name input field
148 | TextFormField(
149 | initialValue: widget.user.name,
150 | onSaved: (val) => APIs.me.name = val ?? '',
151 | validator: (val) => val != null && val.isNotEmpty
152 | ? null
153 | : 'Required Field',
154 | decoration: InputDecoration(
155 | prefixIcon:
156 | const Icon(Icons.person, color: Colors.blue),
157 | border: OutlineInputBorder(
158 | borderRadius: BorderRadius.circular(12)),
159 | hintText: 'eg. Happy Singh',
160 | label: const Text('Name')),
161 | ),
162 |
163 | // for adding some space
164 | SizedBox(height: mq.height * .02),
165 |
166 | // about input field
167 | TextFormField(
168 | initialValue: widget.user.about,
169 | onSaved: (val) => APIs.me.about = val ?? '',
170 | validator: (val) => val != null && val.isNotEmpty
171 | ? null
172 | : 'Required Field',
173 | decoration: InputDecoration(
174 | prefixIcon: const Icon(Icons.info_outline,
175 | color: Colors.blue),
176 | border: OutlineInputBorder(
177 | borderRadius: BorderRadius.circular(12)),
178 | hintText: 'eg. Feeling Happy',
179 | label: const Text('About')),
180 | ),
181 |
182 | // for adding some space
183 | SizedBox(height: mq.height * .05),
184 |
185 | // update profile button
186 | ElevatedButton.icon(
187 | style: ElevatedButton.styleFrom(
188 | shape: const StadiumBorder(),
189 | minimumSize: Size(mq.width * .5, mq.height * .06)),
190 | onPressed: () {
191 | if (_formKey.currentState!.validate()) {
192 | _formKey.currentState!.save();
193 | APIs.updateUserInfo().then((value) {
194 | Dialogs.showSnackbar(
195 | context, 'Profile Updated Successfully!');
196 | });
197 | }
198 | },
199 | icon: const Icon(Icons.edit, size: 28),
200 | label:
201 | const Text('UPDATE', style: TextStyle(fontSize: 16)),
202 | )
203 | ],
204 | ),
205 | ),
206 | ),
207 | )),
208 | );
209 | }
210 |
211 | // bottom sheet for picking a profile picture for user
212 | void _showBottomSheet() {
213 | showModalBottomSheet(
214 | context: context,
215 | shape: const RoundedRectangleBorder(
216 | borderRadius: BorderRadius.only(
217 | topLeft: Radius.circular(20), topRight: Radius.circular(20))),
218 | builder: (_) {
219 | return ListView(
220 | shrinkWrap: true,
221 | padding:
222 | EdgeInsets.only(top: mq.height * .03, bottom: mq.height * .05),
223 | children: [
224 | //pick profile picture label
225 | const Text('Pick Profile Picture',
226 | textAlign: TextAlign.center,
227 | style: TextStyle(fontSize: 20, fontWeight: FontWeight.w500)),
228 |
229 | //for adding some space
230 | SizedBox(height: mq.height * .02),
231 |
232 | //buttons
233 | Row(
234 | mainAxisAlignment: MainAxisAlignment.spaceEvenly,
235 | children: [
236 | //pick from gallery button
237 | ElevatedButton(
238 | style: ElevatedButton.styleFrom(
239 | backgroundColor: Colors.white,
240 | shape: const CircleBorder(),
241 | fixedSize: Size(mq.width * .3, mq.height * .15)),
242 | onPressed: () async {
243 | final ImagePicker picker = ImagePicker();
244 |
245 | // Pick an image
246 | final XFile? image = await picker.pickImage(
247 | source: ImageSource.gallery, imageQuality: 80);
248 | if (image != null) {
249 | log('Image Path: ${image.path}');
250 | setState(() {
251 | _image = image.path;
252 | });
253 |
254 | APIs.updateProfilePicture(File(_image!));
255 | // for hiding bottom sheet
256 | Navigator.pop(context);
257 | }
258 | },
259 | child: Image.asset('images/add_image.png')),
260 |
261 | //take picture from camera button
262 | ElevatedButton(
263 | style: ElevatedButton.styleFrom(
264 | backgroundColor: Colors.white,
265 | shape: const CircleBorder(),
266 | fixedSize: Size(mq.width * .3, mq.height * .15)),
267 | onPressed: () async {
268 | final ImagePicker picker = ImagePicker();
269 |
270 | // Pick an image
271 | final XFile? image = await picker.pickImage(
272 | source: ImageSource.camera, imageQuality: 80);
273 | if (image != null) {
274 | log('Image Path: ${image.path}');
275 | setState(() {
276 | _image = image.path;
277 | });
278 |
279 | APIs.updateProfilePicture(File(_image!));
280 | // for hiding bottom sheet
281 | Navigator.pop(context);
282 | }
283 | },
284 | child: Image.asset('images/camera.png')),
285 | ],
286 | )
287 | ],
288 | );
289 | });
290 | }
291 | }
292 |
--------------------------------------------------------------------------------
/lib/screens/splash_screen.dart:
--------------------------------------------------------------------------------
1 | import 'dart:developer';
2 |
3 | import 'package:flutter/material.dart';
4 | import 'package:flutter/services.dart';
5 |
6 | import '../../main.dart';
7 | import '../api/apis.dart';
8 | import 'auth/login_screen.dart';
9 | import 'home_screen.dart';
10 |
11 | //splash screen
12 | class SplashScreen extends StatefulWidget {
13 | const SplashScreen({super.key});
14 |
15 | @override
16 | State createState() => _SplashScreenState();
17 | }
18 |
19 | class _SplashScreenState extends State {
20 | @override
21 | void initState() {
22 | super.initState();
23 | Future.delayed(const Duration(seconds: 2), () {
24 | //exit full-screen
25 | SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
26 | SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
27 | systemNavigationBarColor: Colors.white,
28 | statusBarColor: Colors.white));
29 |
30 | if (APIs.auth.currentUser != null) {
31 | log('\nUser: ${APIs.auth.currentUser}');
32 | //navigate to home screen
33 | Navigator.pushReplacement(
34 | context, MaterialPageRoute(builder: (_) => const HomeScreen()));
35 | } else {
36 | //navigate to login screen
37 | Navigator.pushReplacement(
38 | context, MaterialPageRoute(builder: (_) => const LoginScreen()));
39 | }
40 | });
41 | }
42 |
43 | @override
44 | Widget build(BuildContext context) {
45 | //initializing media query (for getting device screen size)
46 | mq = MediaQuery.of(context).size;
47 |
48 | return Scaffold(
49 | //body
50 | body: Stack(children: [
51 | //app logo
52 | Positioned(
53 | top: mq.height * .15,
54 | right: mq.width * .25,
55 | width: mq.width * .5,
56 | child: Image.asset('images/icon.png')),
57 |
58 | //google login button
59 | Positioned(
60 | bottom: mq.height * .15,
61 | width: mq.width,
62 | child: const Text('MADE IN INDIA WITH ❤️',
63 | textAlign: TextAlign.center,
64 | style: TextStyle(
65 | fontSize: 16, color: Colors.black87, letterSpacing: .5))),
66 | ]),
67 | );
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/lib/screens/view_profile_screen.dart:
--------------------------------------------------------------------------------
1 | import 'package:cached_network_image/cached_network_image.dart';
2 | import 'package:flutter/cupertino.dart';
3 | import 'package:flutter/material.dart';
4 |
5 | import '../helper/my_date_util.dart';
6 | import '../main.dart';
7 | import '../models/chat_user.dart';
8 |
9 | //view profile screen -- to view profile of user
10 | class ViewProfileScreen extends StatefulWidget {
11 | final ChatUser user;
12 |
13 | const ViewProfileScreen({super.key, required this.user});
14 |
15 | @override
16 | State createState() => _ViewProfileScreenState();
17 | }
18 |
19 | class _ViewProfileScreenState extends State {
20 | @override
21 | Widget build(BuildContext context) {
22 | return GestureDetector(
23 | // for hiding keyboard
24 | onTap: () => FocusScope.of(context).unfocus(),
25 | child: Scaffold(
26 | //app bar
27 | appBar: AppBar(title: Text(widget.user.name)),
28 | floatingActionButton: //user about
29 | Row(
30 | mainAxisAlignment: MainAxisAlignment.center,
31 | children: [
32 | const Text(
33 | 'Joined On: ',
34 | style: TextStyle(
35 | color: Colors.black87,
36 | fontWeight: FontWeight.w500,
37 | fontSize: 15),
38 | ),
39 | Text(
40 | MyDateUtil.getLastMessageTime(
41 | context: context,
42 | time: widget.user.createdAt,
43 | showYear: true),
44 | style: const TextStyle(color: Colors.black54, fontSize: 15)),
45 | ],
46 | ),
47 |
48 | //body
49 | body: Padding(
50 | padding: EdgeInsets.symmetric(horizontal: mq.width * .05),
51 | child: SingleChildScrollView(
52 | child: Column(
53 | children: [
54 | // for adding some space
55 | SizedBox(width: mq.width, height: mq.height * .03),
56 |
57 | //user profile picture
58 | ClipRRect(
59 | borderRadius: BorderRadius.circular(mq.height * .1),
60 | child: CachedNetworkImage(
61 | width: mq.height * .2,
62 | height: mq.height * .2,
63 | fit: BoxFit.cover,
64 | imageUrl: widget.user.image,
65 | errorWidget: (context, url, error) => const CircleAvatar(
66 | child: Icon(CupertinoIcons.person)),
67 | ),
68 | ),
69 |
70 | // for adding some space
71 | SizedBox(height: mq.height * .03),
72 |
73 | // user email label
74 | Text(widget.user.email,
75 | style:
76 | const TextStyle(color: Colors.black87, fontSize: 16)),
77 |
78 | // for adding some space
79 | SizedBox(height: mq.height * .02),
80 |
81 | //user about
82 | Row(
83 | mainAxisAlignment: MainAxisAlignment.center,
84 | children: [
85 | const Text(
86 | 'About: ',
87 | style: TextStyle(
88 | color: Colors.black87,
89 | fontWeight: FontWeight.w500,
90 | fontSize: 15),
91 | ),
92 | Text(widget.user.about,
93 | style: const TextStyle(
94 | color: Colors.black54, fontSize: 15)),
95 | ],
96 | ),
97 | ],
98 | ),
99 | ),
100 | )),
101 | );
102 | }
103 | }
104 |
--------------------------------------------------------------------------------
/lib/widgets/chat_user_card.dart:
--------------------------------------------------------------------------------
1 | import 'package:cached_network_image/cached_network_image.dart';
2 | import 'package:flutter/cupertino.dart';
3 | import 'package:flutter/material.dart';
4 |
5 | import '../api/apis.dart';
6 | import '../helper/my_date_util.dart';
7 | import '../main.dart';
8 | import '../models/chat_user.dart';
9 | import '../models/message.dart';
10 | import '../screens/chat_screen.dart';
11 | import 'dialogs/profile_dialog.dart';
12 |
13 | //card to represent a single user in home screen
14 | class ChatUserCard extends StatefulWidget {
15 | final ChatUser user;
16 |
17 | const ChatUserCard({super.key, required this.user});
18 |
19 | @override
20 | State createState() => _ChatUserCardState();
21 | }
22 |
23 | class _ChatUserCardState extends State {
24 | //last message info (if null --> no message)
25 | Message? _message;
26 |
27 | @override
28 | Widget build(BuildContext context) {
29 | return Card(
30 | margin: EdgeInsets.symmetric(horizontal: mq.width * .04, vertical: 4),
31 | // color: Colors.blue.shade100,
32 | elevation: 0.5,
33 | shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)),
34 | child: InkWell(
35 | onTap: () {
36 | //for navigating to chat screen
37 | Navigator.push(
38 | context,
39 | MaterialPageRoute(
40 | builder: (_) => ChatScreen(user: widget.user)));
41 | },
42 | child: StreamBuilder(
43 | stream: APIs.getLastMessage(widget.user),
44 | builder: (context, snapshot) {
45 | final data = snapshot.data?.docs;
46 | final list =
47 | data?.map((e) => Message.fromJson(e.data())).toList() ?? [];
48 | if (list.isNotEmpty) _message = list[0];
49 |
50 | return ListTile(
51 | //user profile picture
52 | leading: InkWell(
53 | onTap: () {
54 | showDialog(
55 | context: context,
56 | builder: (_) => ProfileDialog(user: widget.user));
57 | },
58 | child: ClipRRect(
59 | borderRadius: BorderRadius.circular(mq.height * .03),
60 | child: CachedNetworkImage(
61 | width: mq.height * .055,
62 | height: mq.height * .055,
63 | imageUrl: widget.user.image,
64 | errorWidget: (context, url, error) => const CircleAvatar(
65 | child: Icon(CupertinoIcons.person)),
66 | ),
67 | ),
68 | ),
69 |
70 | //user name
71 | title: Text(widget.user.name),
72 |
73 | //last message
74 | subtitle: Text(
75 | _message != null
76 | ? _message!.type == Type.image
77 | ? 'image'
78 | : _message!.msg
79 | : widget.user.about,
80 | maxLines: 1),
81 |
82 | //last message time
83 | trailing: _message == null
84 | ? null //show nothing when no message is sent
85 | : _message!.read.isEmpty &&
86 | _message!.fromId != APIs.user.uid
87 | ?
88 | //show for unread message
89 | Container(
90 | width: 15,
91 | height: 15,
92 | decoration: BoxDecoration(
93 | color: Colors.greenAccent.shade400,
94 | borderRadius: BorderRadius.circular(10)),
95 | )
96 | :
97 | //message sent time
98 | Text(
99 | MyDateUtil.getLastMessageTime(
100 | context: context, time: _message!.sent),
101 | style: const TextStyle(color: Colors.black54),
102 | ),
103 | );
104 | },
105 | )),
106 | );
107 | }
108 | }
109 |
--------------------------------------------------------------------------------
/lib/widgets/dialogs/profile_dialog.dart:
--------------------------------------------------------------------------------
1 | import 'package:cached_network_image/cached_network_image.dart';
2 | import 'package:flutter/cupertino.dart';
3 | import 'package:flutter/material.dart';
4 |
5 | import '../../main.dart';
6 | import '../../models/chat_user.dart';
7 | import '../../screens/view_profile_screen.dart';
8 |
9 | class ProfileDialog extends StatelessWidget {
10 | const ProfileDialog({super.key, required this.user});
11 |
12 | final ChatUser user;
13 |
14 | @override
15 | Widget build(BuildContext context) {
16 | return AlertDialog(
17 | contentPadding: EdgeInsets.zero,
18 | backgroundColor: Colors.white.withOpacity(.9),
19 | shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
20 | content: SizedBox(
21 | width: mq.width * .6,
22 | height: mq.height * .35,
23 | child: Stack(
24 | children: [
25 | //user profile picture
26 | Positioned(
27 | top: mq.height * .075,
28 | left: mq.width * .1,
29 | child: ClipRRect(
30 | borderRadius: BorderRadius.circular(mq.height * .25),
31 | child: CachedNetworkImage(
32 | width: mq.width * .5,
33 | fit: BoxFit.cover,
34 | imageUrl: user.image,
35 | errorWidget: (context, url, error) =>
36 | const CircleAvatar(child: Icon(CupertinoIcons.person)),
37 | ),
38 | ),
39 | ),
40 |
41 | //user name
42 | Positioned(
43 | left: mq.width * .04,
44 | top: mq.height * .02,
45 | width: mq.width * .55,
46 | child: Text(user.name,
47 | style: const TextStyle(
48 | fontSize: 18, fontWeight: FontWeight.w500)),
49 | ),
50 |
51 | //info button
52 | Positioned(
53 | right: 8,
54 | top: 6,
55 | child: MaterialButton(
56 | onPressed: () {
57 | //for hiding image dialog
58 | Navigator.pop(context);
59 |
60 | //move to view profile screen
61 | Navigator.push(
62 | context,
63 | MaterialPageRoute(
64 | builder: (_) => ViewProfileScreen(user: user)));
65 | },
66 | minWidth: 0,
67 | padding: const EdgeInsets.all(0),
68 | shape: const CircleBorder(),
69 | child: const Icon(Icons.info_outline,
70 | color: Colors.blue, size: 30),
71 | ))
72 | ],
73 | )),
74 | );
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/lib/widgets/message_card.dart:
--------------------------------------------------------------------------------
1 | import 'dart:developer';
2 |
3 | import 'package:cached_network_image/cached_network_image.dart';
4 | import 'package:flutter/material.dart';
5 | import 'package:flutter/services.dart';
6 | import 'package:gallery_saver/gallery_saver.dart';
7 |
8 | import '../api/apis.dart';
9 | import '../helper/dialogs.dart';
10 | import '../helper/my_date_util.dart';
11 | import '../main.dart';
12 | import '../models/message.dart';
13 |
14 | // for showing single message details
15 | class MessageCard extends StatefulWidget {
16 | const MessageCard({super.key, required this.message});
17 |
18 | final Message message;
19 |
20 | @override
21 | State createState() => _MessageCardState();
22 | }
23 |
24 | class _MessageCardState extends State {
25 | @override
26 | Widget build(BuildContext context) {
27 | bool isMe = APIs.user.uid == widget.message.fromId;
28 | return InkWell(
29 | onLongPress: () {
30 | _showBottomSheet(isMe);
31 | },
32 | child: isMe ? _greenMessage() : _blueMessage());
33 | }
34 |
35 | // sender or another user message
36 | Widget _blueMessage() {
37 | //update last read message if sender and receiver are different
38 | if (widget.message.read.isEmpty) {
39 | APIs.updateMessageReadStatus(widget.message);
40 | }
41 |
42 | return Row(
43 | mainAxisAlignment: MainAxisAlignment.spaceBetween,
44 | children: [
45 | //message content
46 | Flexible(
47 | child: Container(
48 | padding: EdgeInsets.all(widget.message.type == Type.image
49 | ? mq.width * .03
50 | : mq.width * .04),
51 | margin: EdgeInsets.symmetric(
52 | horizontal: mq.width * .04, vertical: mq.height * .01),
53 | decoration: BoxDecoration(
54 | color: const Color.fromARGB(255, 221, 245, 255),
55 | border: Border.all(color: Colors.lightBlue),
56 | //making borders curved
57 | borderRadius: const BorderRadius.only(
58 | topLeft: Radius.circular(30),
59 | topRight: Radius.circular(30),
60 | bottomRight: Radius.circular(30))),
61 | child: widget.message.type == Type.text
62 | ?
63 | //show text
64 | Text(
65 | widget.message.msg,
66 | style: const TextStyle(fontSize: 15, color: Colors.black87),
67 | )
68 | :
69 | //show image
70 | ClipRRect(
71 | borderRadius: BorderRadius.circular(15),
72 | child: CachedNetworkImage(
73 | imageUrl: widget.message.msg,
74 | placeholder: (context, url) => const Padding(
75 | padding: EdgeInsets.all(8.0),
76 | child: CircularProgressIndicator(strokeWidth: 2),
77 | ),
78 | errorWidget: (context, url, error) =>
79 | const Icon(Icons.image, size: 70),
80 | ),
81 | ),
82 | ),
83 | ),
84 |
85 | //message time
86 | Padding(
87 | padding: EdgeInsets.only(right: mq.width * .04),
88 | child: Text(
89 | MyDateUtil.getFormattedTime(
90 | context: context, time: widget.message.sent),
91 | style: const TextStyle(fontSize: 13, color: Colors.black54),
92 | ),
93 | ),
94 | ],
95 | );
96 | }
97 |
98 | // our or user message
99 | Widget _greenMessage() {
100 | return Row(
101 | mainAxisAlignment: MainAxisAlignment.spaceBetween,
102 | children: [
103 | //message time
104 | Row(
105 | children: [
106 | //for adding some space
107 | SizedBox(width: mq.width * .04),
108 |
109 | //double tick blue icon for message read
110 | if (widget.message.read.isNotEmpty)
111 | const Icon(Icons.done_all_rounded, color: Colors.blue, size: 20),
112 |
113 | //for adding some space
114 | const SizedBox(width: 2),
115 |
116 | //sent time
117 | Text(
118 | MyDateUtil.getFormattedTime(
119 | context: context, time: widget.message.sent),
120 | style: const TextStyle(fontSize: 13, color: Colors.black54),
121 | ),
122 | ],
123 | ),
124 |
125 | //message content
126 | Flexible(
127 | child: Container(
128 | padding: EdgeInsets.all(widget.message.type == Type.image
129 | ? mq.width * .03
130 | : mq.width * .04),
131 | margin: EdgeInsets.symmetric(
132 | horizontal: mq.width * .04, vertical: mq.height * .01),
133 | decoration: BoxDecoration(
134 | color: const Color.fromARGB(255, 218, 255, 176),
135 | border: Border.all(color: Colors.lightGreen),
136 | //making borders curved
137 | borderRadius: const BorderRadius.only(
138 | topLeft: Radius.circular(30),
139 | topRight: Radius.circular(30),
140 | bottomLeft: Radius.circular(30))),
141 | child: widget.message.type == Type.text
142 | ?
143 | //show text
144 | Text(
145 | widget.message.msg,
146 | style: const TextStyle(fontSize: 15, color: Colors.black87),
147 | )
148 | :
149 | //show image
150 | ClipRRect(
151 | borderRadius: BorderRadius.circular(15),
152 | child: CachedNetworkImage(
153 | imageUrl: widget.message.msg,
154 | placeholder: (context, url) => const Padding(
155 | padding: EdgeInsets.all(8.0),
156 | child: CircularProgressIndicator(strokeWidth: 2),
157 | ),
158 | errorWidget: (context, url, error) =>
159 | const Icon(Icons.image, size: 70),
160 | ),
161 | ),
162 | ),
163 | ),
164 | ],
165 | );
166 | }
167 |
168 | // bottom sheet for modifying message details
169 | void _showBottomSheet(bool isMe) {
170 | showModalBottomSheet(
171 | context: context,
172 | shape: const RoundedRectangleBorder(
173 | borderRadius: BorderRadius.only(
174 | topLeft: Radius.circular(20), topRight: Radius.circular(20))),
175 | builder: (_) {
176 | return ListView(
177 | shrinkWrap: true,
178 | children: [
179 | //black divider
180 | Container(
181 | height: 4,
182 | margin: EdgeInsets.symmetric(
183 | vertical: mq.height * .015, horizontal: mq.width * .4),
184 | decoration: BoxDecoration(
185 | color: Colors.grey, borderRadius: BorderRadius.circular(8)),
186 | ),
187 |
188 | widget.message.type == Type.text
189 | ?
190 | //copy option
191 | _OptionItem(
192 | icon: const Icon(Icons.copy_all_rounded,
193 | color: Colors.blue, size: 26),
194 | name: 'Copy Text',
195 | onTap: () async {
196 | await Clipboard.setData(
197 | ClipboardData(text: widget.message.msg))
198 | .then((value) {
199 | //for hiding bottom sheet
200 | Navigator.pop(context);
201 |
202 | Dialogs.showSnackbar(context, 'Text Copied!');
203 | });
204 | })
205 | :
206 | //save option
207 | _OptionItem(
208 | icon: const Icon(Icons.download_rounded,
209 | color: Colors.blue, size: 26),
210 | name: 'Save Image',
211 | onTap: () async {
212 | try {
213 | log('Image Url: ${widget.message.msg}');
214 | await GallerySaver.saveImage(widget.message.msg,
215 | albumName: 'We Chat')
216 | .then((success) {
217 | //for hiding bottom sheet
218 | Navigator.pop(context);
219 | if (success != null && success) {
220 | Dialogs.showSnackbar(
221 | context, 'Image Successfully Saved!');
222 | }
223 | });
224 | } catch (e) {
225 | log('ErrorWhileSavingImg: $e');
226 | }
227 | }),
228 |
229 | //separator or divider
230 | if (isMe)
231 | Divider(
232 | color: Colors.black54,
233 | endIndent: mq.width * .04,
234 | indent: mq.width * .04,
235 | ),
236 |
237 | //edit option
238 | if (widget.message.type == Type.text && isMe)
239 | _OptionItem(
240 | icon: const Icon(Icons.edit, color: Colors.blue, size: 26),
241 | name: 'Edit Message',
242 | onTap: () {
243 | //for hiding bottom sheet
244 | Navigator.pop(context);
245 |
246 | _showMessageUpdateDialog();
247 | }),
248 |
249 | //delete option
250 | if (isMe)
251 | _OptionItem(
252 | icon: const Icon(Icons.delete_forever,
253 | color: Colors.red, size: 26),
254 | name: 'Delete Message',
255 | onTap: () async {
256 | await APIs.deleteMessage(widget.message).then((value) {
257 | //for hiding bottom sheet
258 | Navigator.pop(context);
259 | });
260 | }),
261 |
262 | //separator or divider
263 | Divider(
264 | color: Colors.black54,
265 | endIndent: mq.width * .04,
266 | indent: mq.width * .04,
267 | ),
268 |
269 | //sent time
270 | _OptionItem(
271 | icon: const Icon(Icons.remove_red_eye, color: Colors.blue),
272 | name:
273 | 'Sent At: ${MyDateUtil.getMessageTime(context: context, time: widget.message.sent)}',
274 | onTap: () {}),
275 |
276 | //read time
277 | _OptionItem(
278 | icon: const Icon(Icons.remove_red_eye, color: Colors.green),
279 | name: widget.message.read.isEmpty
280 | ? 'Read At: Not seen yet'
281 | : 'Read At: ${MyDateUtil.getMessageTime(context: context, time: widget.message.read)}',
282 | onTap: () {}),
283 | ],
284 | );
285 | });
286 | }
287 |
288 | //dialog for updating message content
289 | void _showMessageUpdateDialog() {
290 | String updatedMsg = widget.message.msg;
291 |
292 | showDialog(
293 | context: context,
294 | builder: (_) => AlertDialog(
295 | contentPadding: const EdgeInsets.only(
296 | left: 24, right: 24, top: 20, bottom: 10),
297 |
298 | shape: RoundedRectangleBorder(
299 | borderRadius: BorderRadius.circular(20)),
300 |
301 | //title
302 | title: const Row(
303 | children: [
304 | Icon(
305 | Icons.message,
306 | color: Colors.blue,
307 | size: 28,
308 | ),
309 | Text(' Update Message')
310 | ],
311 | ),
312 |
313 | //content
314 | content: TextFormField(
315 | initialValue: updatedMsg,
316 | maxLines: null,
317 | onChanged: (value) => updatedMsg = value,
318 | decoration: InputDecoration(
319 | border: OutlineInputBorder(
320 | borderRadius: BorderRadius.circular(15))),
321 | ),
322 |
323 | //actions
324 | actions: [
325 | //cancel button
326 | MaterialButton(
327 | onPressed: () {
328 | //hide alert dialog
329 | Navigator.pop(context);
330 | },
331 | child: const Text(
332 | 'Cancel',
333 | style: TextStyle(color: Colors.blue, fontSize: 16),
334 | )),
335 |
336 | //update button
337 | MaterialButton(
338 | onPressed: () {
339 | //hide alert dialog
340 | Navigator.pop(context);
341 | APIs.updateMessage(widget.message, updatedMsg);
342 | },
343 | child: const Text(
344 | 'Update',
345 | style: TextStyle(color: Colors.blue, fontSize: 16),
346 | ))
347 | ],
348 | ));
349 | }
350 | }
351 |
352 | //custom options card (for copy, edit, delete, etc.)
353 | class _OptionItem extends StatelessWidget {
354 | final Icon icon;
355 | final String name;
356 | final VoidCallback onTap;
357 |
358 | const _OptionItem(
359 | {required this.icon, required this.name, required this.onTap});
360 |
361 | @override
362 | Widget build(BuildContext context) {
363 | return InkWell(
364 | onTap: () => onTap(),
365 | child: Padding(
366 | padding: EdgeInsets.only(
367 | left: mq.width * .05,
368 | top: mq.height * .015,
369 | bottom: mq.height * .015),
370 | child: Row(children: [
371 | icon,
372 | Flexible(
373 | child: Text(' $name',
374 | style: const TextStyle(
375 | fontSize: 15,
376 | color: Colors.black54,
377 | letterSpacing: 0.5)))
378 | ]),
379 | ));
380 | }
381 | }
382 |
--------------------------------------------------------------------------------
/linux/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | # Project-level configuration.
2 | cmake_minimum_required(VERSION 3.10)
3 | project(runner LANGUAGES CXX)
4 |
5 | # The name of the executable created for the application. Change this to change
6 | # the on-disk name of your application.
7 | set(BINARY_NAME "talkg")
8 | # The unique GTK application identifier for this application. See:
9 | # https://wiki.gnome.org/HowDoI/ChooseApplicationID
10 | set(APPLICATION_ID "com.example.talkg")
11 |
12 | # Explicitly opt in to modern CMake behaviors to avoid warnings with recent
13 | # versions of CMake.
14 | cmake_policy(SET CMP0063 NEW)
15 |
16 | # Load bundled libraries from the lib/ directory relative to the binary.
17 | set(CMAKE_INSTALL_RPATH "$ORIGIN/lib")
18 |
19 | # Root filesystem for cross-building.
20 | if(FLUTTER_TARGET_PLATFORM_SYSROOT)
21 | set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT})
22 | set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT})
23 | set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
24 | set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
25 | set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
26 | set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
27 | endif()
28 |
29 | # Define build configuration options.
30 | if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
31 | set(CMAKE_BUILD_TYPE "Debug" CACHE
32 | STRING "Flutter build mode" FORCE)
33 | set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS
34 | "Debug" "Profile" "Release")
35 | endif()
36 |
37 | # Compilation settings that should be applied to most targets.
38 | #
39 | # Be cautious about adding new options here, as plugins use this function by
40 | # default. In most cases, you should add new options to specific targets instead
41 | # of modifying this function.
42 | function(APPLY_STANDARD_SETTINGS TARGET)
43 | target_compile_features(${TARGET} PUBLIC cxx_std_14)
44 | target_compile_options(${TARGET} PRIVATE -Wall -Werror)
45 | target_compile_options(${TARGET} PRIVATE "$<$>:-O3>")
46 | target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>")
47 | endfunction()
48 |
49 | # Flutter library and tool build rules.
50 | set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter")
51 | add_subdirectory(${FLUTTER_MANAGED_DIR})
52 |
53 | # System-level dependencies.
54 | find_package(PkgConfig REQUIRED)
55 | pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0)
56 |
57 | add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}")
58 |
59 | # Define the application target. To change its name, change BINARY_NAME above,
60 | # not the value here, or `flutter run` will no longer work.
61 | #
62 | # Any new source files that you add to the application should be added here.
63 | add_executable(${BINARY_NAME}
64 | "main.cc"
65 | "my_application.cc"
66 | "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc"
67 | )
68 |
69 | # Apply the standard set of build settings. This can be removed for applications
70 | # that need different build settings.
71 | apply_standard_settings(${BINARY_NAME})
72 |
73 | # Add dependency libraries. Add any application-specific dependencies here.
74 | target_link_libraries(${BINARY_NAME} PRIVATE flutter)
75 | target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK)
76 |
77 | # Run the Flutter tool portions of the build. This must not be removed.
78 | add_dependencies(${BINARY_NAME} flutter_assemble)
79 |
80 | # Only the install-generated bundle's copy of the executable will launch
81 | # correctly, since the resources must in the right relative locations. To avoid
82 | # people trying to run the unbundled copy, put it in a subdirectory instead of
83 | # the default top-level location.
84 | set_target_properties(${BINARY_NAME}
85 | PROPERTIES
86 | RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run"
87 | )
88 |
89 |
90 | # Generated plugin build rules, which manage building the plugins and adding
91 | # them to the application.
92 | include(flutter/generated_plugins.cmake)
93 |
94 |
95 | # === Installation ===
96 | # By default, "installing" just makes a relocatable bundle in the build
97 | # directory.
98 | set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle")
99 | if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT)
100 | set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE)
101 | endif()
102 |
103 | # Start with a clean build bundle directory every time.
104 | install(CODE "
105 | file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\")
106 | " COMPONENT Runtime)
107 |
108 | set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data")
109 | set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib")
110 |
111 | install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}"
112 | COMPONENT Runtime)
113 |
114 | install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}"
115 | COMPONENT Runtime)
116 |
117 | install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
118 | COMPONENT Runtime)
119 |
120 | foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES})
121 | install(FILES "${bundled_library}"
122 | DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
123 | COMPONENT Runtime)
124 | endforeach(bundled_library)
125 |
126 | # Fully re-copy the assets directory on each build to avoid having stale files
127 | # from a previous install.
128 | set(FLUTTER_ASSET_DIR_NAME "flutter_assets")
129 | install(CODE "
130 | file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\")
131 | " COMPONENT Runtime)
132 | install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}"
133 | DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime)
134 |
135 | # Install the AOT library on non-Debug builds only.
136 | if(NOT CMAKE_BUILD_TYPE MATCHES "Debug")
137 | install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
138 | COMPONENT Runtime)
139 | endif()
140 |
--------------------------------------------------------------------------------
/linux/flutter/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | # This file controls Flutter-level build steps. It should not be edited.
2 | cmake_minimum_required(VERSION 3.10)
3 |
4 | set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral")
5 |
6 | # Configuration provided via flutter tool.
7 | include(${EPHEMERAL_DIR}/generated_config.cmake)
8 |
9 | # TODO: Move the rest of this into files in ephemeral. See
10 | # https://github.com/flutter/flutter/issues/57146.
11 |
12 | # Serves the same purpose as list(TRANSFORM ... PREPEND ...),
13 | # which isn't available in 3.10.
14 | function(list_prepend LIST_NAME PREFIX)
15 | set(NEW_LIST "")
16 | foreach(element ${${LIST_NAME}})
17 | list(APPEND NEW_LIST "${PREFIX}${element}")
18 | endforeach(element)
19 | set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE)
20 | endfunction()
21 |
22 | # === Flutter Library ===
23 | # System-level dependencies.
24 | find_package(PkgConfig REQUIRED)
25 | pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0)
26 | pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0)
27 | pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0)
28 |
29 | set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so")
30 |
31 | # Published to parent scope for install step.
32 | set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE)
33 | set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE)
34 | set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE)
35 | set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE)
36 |
37 | list(APPEND FLUTTER_LIBRARY_HEADERS
38 | "fl_basic_message_channel.h"
39 | "fl_binary_codec.h"
40 | "fl_binary_messenger.h"
41 | "fl_dart_project.h"
42 | "fl_engine.h"
43 | "fl_json_message_codec.h"
44 | "fl_json_method_codec.h"
45 | "fl_message_codec.h"
46 | "fl_method_call.h"
47 | "fl_method_channel.h"
48 | "fl_method_codec.h"
49 | "fl_method_response.h"
50 | "fl_plugin_registrar.h"
51 | "fl_plugin_registry.h"
52 | "fl_standard_message_codec.h"
53 | "fl_standard_method_codec.h"
54 | "fl_string_codec.h"
55 | "fl_value.h"
56 | "fl_view.h"
57 | "flutter_linux.h"
58 | )
59 | list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/")
60 | add_library(flutter INTERFACE)
61 | target_include_directories(flutter INTERFACE
62 | "${EPHEMERAL_DIR}"
63 | )
64 | target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}")
65 | target_link_libraries(flutter INTERFACE
66 | PkgConfig::GTK
67 | PkgConfig::GLIB
68 | PkgConfig::GIO
69 | )
70 | add_dependencies(flutter flutter_assemble)
71 |
72 | # === Flutter tool backend ===
73 | # _phony_ is a non-existent file to force this command to run every time,
74 | # since currently there's no way to get a full input/output list from the
75 | # flutter tool.
76 | add_custom_command(
77 | OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS}
78 | ${CMAKE_CURRENT_BINARY_DIR}/_phony_
79 | COMMAND ${CMAKE_COMMAND} -E env
80 | ${FLUTTER_TOOL_ENVIRONMENT}
81 | "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh"
82 | ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE}
83 | VERBATIM
84 | )
85 | add_custom_target(flutter_assemble DEPENDS
86 | "${FLUTTER_LIBRARY}"
87 | ${FLUTTER_LIBRARY_HEADERS}
88 | )
89 |
--------------------------------------------------------------------------------
/linux/main.cc:
--------------------------------------------------------------------------------
1 | #include "my_application.h"
2 |
3 | int main(int argc, char** argv) {
4 | g_autoptr(MyApplication) app = my_application_new();
5 | return g_application_run(G_APPLICATION(app), argc, argv);
6 | }
7 |
--------------------------------------------------------------------------------
/linux/my_application.cc:
--------------------------------------------------------------------------------
1 | #include "my_application.h"
2 |
3 | #include
4 | #ifdef GDK_WINDOWING_X11
5 | #include
6 | #endif
7 |
8 | #include "flutter/generated_plugin_registrant.h"
9 |
10 | struct _MyApplication {
11 | GtkApplication parent_instance;
12 | char** dart_entrypoint_arguments;
13 | };
14 |
15 | G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION)
16 |
17 | // Implements GApplication::activate.
18 | static void my_application_activate(GApplication* application) {
19 | MyApplication* self = MY_APPLICATION(application);
20 | GtkWindow* window =
21 | GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application)));
22 |
23 | // Use a header bar when running in GNOME as this is the common style used
24 | // by applications and is the setup most users will be using (e.g. Ubuntu
25 | // desktop).
26 | // If running on X and not using GNOME then just use a traditional title bar
27 | // in case the window manager does more exotic layout, e.g. tiling.
28 | // If running on Wayland assume the header bar will work (may need changing
29 | // if future cases occur).
30 | gboolean use_header_bar = TRUE;
31 | #ifdef GDK_WINDOWING_X11
32 | GdkScreen* screen = gtk_window_get_screen(window);
33 | if (GDK_IS_X11_SCREEN(screen)) {
34 | const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen);
35 | if (g_strcmp0(wm_name, "GNOME Shell") != 0) {
36 | use_header_bar = FALSE;
37 | }
38 | }
39 | #endif
40 | if (use_header_bar) {
41 | GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new());
42 | gtk_widget_show(GTK_WIDGET(header_bar));
43 | gtk_header_bar_set_title(header_bar, "talkg");
44 | gtk_header_bar_set_show_close_button(header_bar, TRUE);
45 | gtk_window_set_titlebar(window, GTK_WIDGET(header_bar));
46 | } else {
47 | gtk_window_set_title(window, "talkg");
48 | }
49 |
50 | gtk_window_set_default_size(window, 1280, 720);
51 | gtk_widget_show(GTK_WIDGET(window));
52 |
53 | g_autoptr(FlDartProject) project = fl_dart_project_new();
54 | fl_dart_project_set_dart_entrypoint_arguments(project, self->dart_entrypoint_arguments);
55 |
56 | FlView* view = fl_view_new(project);
57 | gtk_widget_show(GTK_WIDGET(view));
58 | gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view));
59 |
60 | fl_register_plugins(FL_PLUGIN_REGISTRY(view));
61 |
62 | gtk_widget_grab_focus(GTK_WIDGET(view));
63 | }
64 |
65 | // Implements GApplication::local_command_line.
66 | static gboolean my_application_local_command_line(GApplication* application, gchar*** arguments, int* exit_status) {
67 | MyApplication* self = MY_APPLICATION(application);
68 | // Strip out the first argument as it is the binary name.
69 | self->dart_entrypoint_arguments = g_strdupv(*arguments + 1);
70 |
71 | g_autoptr(GError) error = nullptr;
72 | if (!g_application_register(application, nullptr, &error)) {
73 | g_warning("Failed to register: %s", error->message);
74 | *exit_status = 1;
75 | return TRUE;
76 | }
77 |
78 | g_application_activate(application);
79 | *exit_status = 0;
80 |
81 | return TRUE;
82 | }
83 |
84 | // Implements GObject::dispose.
85 | static void my_application_dispose(GObject* object) {
86 | MyApplication* self = MY_APPLICATION(object);
87 | g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev);
88 | G_OBJECT_CLASS(my_application_parent_class)->dispose(object);
89 | }
90 |
91 | static void my_application_class_init(MyApplicationClass* klass) {
92 | G_APPLICATION_CLASS(klass)->activate = my_application_activate;
93 | G_APPLICATION_CLASS(klass)->local_command_line = my_application_local_command_line;
94 | G_OBJECT_CLASS(klass)->dispose = my_application_dispose;
95 | }
96 |
97 | static void my_application_init(MyApplication* self) {}
98 |
99 | MyApplication* my_application_new() {
100 | return MY_APPLICATION(g_object_new(my_application_get_type(),
101 | "application-id", APPLICATION_ID,
102 | "flags", G_APPLICATION_NON_UNIQUE,
103 | nullptr));
104 | }
105 |
--------------------------------------------------------------------------------
/linux/my_application.h:
--------------------------------------------------------------------------------
1 | #ifndef FLUTTER_MY_APPLICATION_H_
2 | #define FLUTTER_MY_APPLICATION_H_
3 |
4 | #include
5 |
6 | G_DECLARE_FINAL_TYPE(MyApplication, my_application, MY, APPLICATION,
7 | GtkApplication)
8 |
9 | /**
10 | * my_application_new:
11 | *
12 | * Creates a new Flutter-based application.
13 | *
14 | * Returns: a new #MyApplication.
15 | */
16 | MyApplication* my_application_new();
17 |
18 | #endif // FLUTTER_MY_APPLICATION_H_
19 |
--------------------------------------------------------------------------------
/macos/Flutter/Flutter-Debug.xcconfig:
--------------------------------------------------------------------------------
1 | #include "ephemeral/Flutter-Generated.xcconfig"
2 |
--------------------------------------------------------------------------------
/macos/Flutter/Flutter-Release.xcconfig:
--------------------------------------------------------------------------------
1 | #include "ephemeral/Flutter-Generated.xcconfig"
2 |
--------------------------------------------------------------------------------
/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | IDEDidComputeMac32BitWarning
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme:
--------------------------------------------------------------------------------
1 |
2 |
5 |
8 |
9 |
15 |
21 |
22 |
23 |
24 |
25 |
30 |
31 |
37 |
38 |
39 |
40 |
43 |
49 |
50 |
51 |
52 |
53 |
63 |
65 |
71 |
72 |
73 |
74 |
80 |
82 |
88 |
89 |
90 |
91 |
93 |
94 |
97 |
98 |
99 |
--------------------------------------------------------------------------------
/macos/Runner.xcworkspace/contents.xcworkspacedata:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | IDEDidComputeMac32BitWarning
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/macos/Runner/AppDelegate.swift:
--------------------------------------------------------------------------------
1 | import Cocoa
2 | import FlutterMacOS
3 |
4 | @NSApplicationMain
5 | class AppDelegate: FlutterAppDelegate {
6 | override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
7 | return true
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "images" : [
3 | {
4 | "size" : "16x16",
5 | "idiom" : "mac",
6 | "filename" : "app_icon_16.png",
7 | "scale" : "1x"
8 | },
9 | {
10 | "size" : "16x16",
11 | "idiom" : "mac",
12 | "filename" : "app_icon_32.png",
13 | "scale" : "2x"
14 | },
15 | {
16 | "size" : "32x32",
17 | "idiom" : "mac",
18 | "filename" : "app_icon_32.png",
19 | "scale" : "1x"
20 | },
21 | {
22 | "size" : "32x32",
23 | "idiom" : "mac",
24 | "filename" : "app_icon_64.png",
25 | "scale" : "2x"
26 | },
27 | {
28 | "size" : "128x128",
29 | "idiom" : "mac",
30 | "filename" : "app_icon_128.png",
31 | "scale" : "1x"
32 | },
33 | {
34 | "size" : "128x128",
35 | "idiom" : "mac",
36 | "filename" : "app_icon_256.png",
37 | "scale" : "2x"
38 | },
39 | {
40 | "size" : "256x256",
41 | "idiom" : "mac",
42 | "filename" : "app_icon_256.png",
43 | "scale" : "1x"
44 | },
45 | {
46 | "size" : "256x256",
47 | "idiom" : "mac",
48 | "filename" : "app_icon_512.png",
49 | "scale" : "2x"
50 | },
51 | {
52 | "size" : "512x512",
53 | "idiom" : "mac",
54 | "filename" : "app_icon_512.png",
55 | "scale" : "1x"
56 | },
57 | {
58 | "size" : "512x512",
59 | "idiom" : "mac",
60 | "filename" : "app_icon_1024.png",
61 | "scale" : "2x"
62 | }
63 | ],
64 | "info" : {
65 | "version" : 1,
66 | "author" : "xcode"
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Warrior-Gosai/TalkG/2e965c5edc1735850f3db8f0fbd101c4121fee4e/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png
--------------------------------------------------------------------------------
/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Warrior-Gosai/TalkG/2e965c5edc1735850f3db8f0fbd101c4121fee4e/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png
--------------------------------------------------------------------------------
/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Warrior-Gosai/TalkG/2e965c5edc1735850f3db8f0fbd101c4121fee4e/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png
--------------------------------------------------------------------------------
/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Warrior-Gosai/TalkG/2e965c5edc1735850f3db8f0fbd101c4121fee4e/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png
--------------------------------------------------------------------------------
/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Warrior-Gosai/TalkG/2e965c5edc1735850f3db8f0fbd101c4121fee4e/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png
--------------------------------------------------------------------------------
/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Warrior-Gosai/TalkG/2e965c5edc1735850f3db8f0fbd101c4121fee4e/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png
--------------------------------------------------------------------------------
/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Warrior-Gosai/TalkG/2e965c5edc1735850f3db8f0fbd101c4121fee4e/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png
--------------------------------------------------------------------------------
/macos/Runner/Configs/AppInfo.xcconfig:
--------------------------------------------------------------------------------
1 | // Application-level settings for the Runner target.
2 | //
3 | // This may be replaced with something auto-generated from metadata (e.g., pubspec.yaml) in the
4 | // future. If not, the values below would default to using the project name when this becomes a
5 | // 'flutter create' template.
6 |
7 | // The application's name. By default this is also the title of the Flutter window.
8 | PRODUCT_NAME = talkg
9 |
10 | // The application's bundle identifier
11 | PRODUCT_BUNDLE_IDENTIFIER = com.example.talkg
12 |
13 | // The copyright displayed in application information
14 | PRODUCT_COPYRIGHT = Copyright © 2023 com.example. All rights reserved.
15 |
--------------------------------------------------------------------------------
/macos/Runner/Configs/Debug.xcconfig:
--------------------------------------------------------------------------------
1 | #include "../../Flutter/Flutter-Debug.xcconfig"
2 | #include "Warnings.xcconfig"
3 |
--------------------------------------------------------------------------------
/macos/Runner/Configs/Release.xcconfig:
--------------------------------------------------------------------------------
1 | #include "../../Flutter/Flutter-Release.xcconfig"
2 | #include "Warnings.xcconfig"
3 |
--------------------------------------------------------------------------------
/macos/Runner/Configs/Warnings.xcconfig:
--------------------------------------------------------------------------------
1 | WARNING_CFLAGS = -Wall -Wconditional-uninitialized -Wnullable-to-nonnull-conversion -Wmissing-method-return-type -Woverlength-strings
2 | GCC_WARN_UNDECLARED_SELECTOR = YES
3 | CLANG_UNDEFINED_BEHAVIOR_SANITIZER_NULLABILITY = YES
4 | CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE
5 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES
6 | CLANG_WARN_PRAGMA_PACK = YES
7 | CLANG_WARN_STRICT_PROTOTYPES = YES
8 | CLANG_WARN_COMMA = YES
9 | GCC_WARN_STRICT_SELECTOR_MATCH = YES
10 | CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES
11 | CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES
12 | GCC_WARN_SHADOW = YES
13 | CLANG_WARN_UNREACHABLE_CODE = YES
14 |
--------------------------------------------------------------------------------
/macos/Runner/DebugProfile.entitlements:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | com.apple.security.app-sandbox
6 |
7 | com.apple.security.cs.allow-jit
8 |
9 | com.apple.security.network.server
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/macos/Runner/GoogleService-Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CLIENT_ID
6 | 488443205841-oaoru8vbmu6crv5bq9ovcfmmho1hpdij.apps.googleusercontent.com
7 | REVERSED_CLIENT_ID
8 | com.googleusercontent.apps.488443205841-oaoru8vbmu6crv5bq9ovcfmmho1hpdij
9 | API_KEY
10 | AIzaSyD6j31BYYWvfT9TWsUavRpbMqBnImUQySE
11 | GCM_SENDER_ID
12 | 488443205841
13 | PLIST_VERSION
14 | 1
15 | BUNDLE_ID
16 | com.example.talkg.RunnerTests
17 | PROJECT_ID
18 | talkg-app
19 | STORAGE_BUCKET
20 | talkg-app.appspot.com
21 | IS_ADS_ENABLED
22 |
23 | IS_ANALYTICS_ENABLED
24 |
25 | IS_APPINVITE_ENABLED
26 |
27 | IS_GCM_ENABLED
28 |
29 | IS_SIGNIN_ENABLED
30 |
31 | GOOGLE_APP_ID
32 | 1:488443205841:ios:272d9a2c614b90ee3f8df0
33 | DATABASE_URL
34 | https://talkg-app-default-rtdb.asia-southeast1.firebasedatabase.app
35 |
36 |
--------------------------------------------------------------------------------
/macos/Runner/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleDevelopmentRegion
6 | $(DEVELOPMENT_LANGUAGE)
7 | CFBundleExecutable
8 | $(EXECUTABLE_NAME)
9 | CFBundleIconFile
10 |
11 | CFBundleIdentifier
12 | $(PRODUCT_BUNDLE_IDENTIFIER)
13 | CFBundleInfoDictionaryVersion
14 | 6.0
15 | CFBundleName
16 | $(PRODUCT_NAME)
17 | CFBundlePackageType
18 | APPL
19 | CFBundleShortVersionString
20 | $(FLUTTER_BUILD_NAME)
21 | CFBundleVersion
22 | $(FLUTTER_BUILD_NUMBER)
23 | LSMinimumSystemVersion
24 | $(MACOSX_DEPLOYMENT_TARGET)
25 | NSHumanReadableCopyright
26 | $(PRODUCT_COPYRIGHT)
27 | NSMainNibFile
28 | MainMenu
29 | NSPrincipalClass
30 | NSApplication
31 |
32 |
33 |
--------------------------------------------------------------------------------
/macos/Runner/MainFlutterWindow.swift:
--------------------------------------------------------------------------------
1 | import Cocoa
2 | import FlutterMacOS
3 |
4 | class MainFlutterWindow: NSWindow {
5 | override func awakeFromNib() {
6 | let flutterViewController = FlutterViewController()
7 | let windowFrame = self.frame
8 | self.contentViewController = flutterViewController
9 | self.setFrame(windowFrame, display: true)
10 |
11 | RegisterGeneratedPlugins(registry: flutterViewController)
12 |
13 | super.awakeFromNib()
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/macos/Runner/Release.entitlements:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | com.apple.security.app-sandbox
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/macos/RunnerTests/RunnerTests.swift:
--------------------------------------------------------------------------------
1 | import FlutterMacOS
2 | import Cocoa
3 | import XCTest
4 |
5 | class RunnerTests: XCTestCase {
6 |
7 | func testExample() {
8 | // If you add code to the Runner application, consider adding tests here.
9 | // See https://developer.apple.com/documentation/xctest for more information about using XCTest.
10 | }
11 |
12 | }
13 |
--------------------------------------------------------------------------------
/macos/firebase_app_id_file.json:
--------------------------------------------------------------------------------
1 | {
2 | "file_generated_by": "FlutterFire CLI",
3 | "purpose": "FirebaseAppID & ProjectID for this Firebase app in this directory",
4 | "GOOGLE_APP_ID": "1:488443205841:ios:272d9a2c614b90ee3f8df0",
5 | "FIREBASE_PROJECT_ID": "talkg-app",
6 | "GCM_SENDER_ID": "488443205841"
7 | }
--------------------------------------------------------------------------------
/pubspec.yaml:
--------------------------------------------------------------------------------
1 | name: talkg
2 | description: A new Flutter project.
3 |
4 | publish_to: 'none' # Remove this line if you wish to publish to pub.dev
5 |
6 | version: 1.0.0+1
7 |
8 | environment:
9 | sdk: '>=3.0.0 <4.0.0'
10 |
11 | dependencies:
12 | flutter:
13 | sdk: flutter
14 |
15 |
16 | # For using cupertino icons
17 | cupertino_icons: ^1.0.2
18 |
19 | # For integrating firebase
20 | firebase_core: ^2.2.0
21 |
22 | # For handling firebase authentication
23 | firebase_auth: ^4.1.3
24 |
25 | # For handling google sign in
26 | google_sign_in: ^5.4.2
27 |
28 | # For accessing cloud firestore database
29 | cloud_firestore: ^4.1.0
30 |
31 | # For showing network images
32 | cached_network_image: ^3.2.3
33 |
34 | # For picking images
35 | image_picker: ^0.8.6
36 |
37 | # For accessing Firebase Storage (for uploading files)
38 | firebase_storage: ^11.0.6
39 |
40 | # For showing Emojis
41 | emoji_picker_flutter: ^1.5.1
42 |
43 | # For accessing firebase messaging (Push Notification)
44 | firebase_messaging: ^14.2.0
45 |
46 | # For calling RestAPIs
47 | http: ^0.13.5
48 |
49 | # For creating notification channel
50 | flutter_notification_channel: ^2.0.0
51 |
52 | # For storing images into gallery
53 | gallery_saver: ^2.3.2
54 |
55 | dev_dependencies:
56 | flutter_test:
57 | sdk: flutter
58 |
59 | # flutter_launcher_icons: "^0.10.0"
60 |
61 | # flutter_icons:
62 | # android: "ic_launcher"
63 | # ios: true
64 | # image_path: "images/icon.png"
65 | # min_sdk_android: 21
66 | # remove_alpha_ios: true
67 |
68 | flutter_lints: ^2.0.0
69 |
70 | # For information on the generic Dart part of this file, see the
71 | # following page: https://dart.dev/tools/pub/pubspec
72 |
73 | # The following section is specific to Flutter packages.
74 | flutter:
75 |
76 | # The following line ensures that the Material Icons font is
77 | # included with your application, so that you can use the icons in
78 | # the material Icons class.
79 | uses-material-design: true
80 |
81 | # To add assets to your application, add an assets section, like this:
82 | assets:
83 | - images/
84 | # - images/a_dot_ham.jpeg
85 |
86 | # An image asset can refer to one or more resolution-specific "variants", see
87 | # https://flutter.dev/assets-and-images/#resolution-aware
88 |
89 | # For details regarding adding assets from package dependencies, see
90 | # https://flutter.dev/assets-and-images/#from-packages
91 |
92 | # To add custom fonts to your application, add a fonts section here,
93 | # in this "flutter" section. Each entry in this list should have a
94 | # "family" key with the font family name, and a "fonts" key with a
95 | # list giving the asset and other descriptors for the font. For
96 | # example:
97 | # fonts:
98 | # - family: Schyler
99 | # fonts:
100 | # - asset: fonts/Schyler-Regular.ttf
101 | # - asset: fonts/Schyler-Italic.ttf
102 | # style: italic
103 | # - family: Trajan Pro
104 | # fonts:
105 | # - asset: fonts/TrajanPro.ttf
106 | # - asset: fonts/TrajanPro_Bold.ttf
107 | # weight: 700
108 | #
109 | # For details regarding fonts from package dependencies,
110 | # see https://flutter.dev/custom-fonts/#from-packages
111 |
--------------------------------------------------------------------------------
/screenshots/1.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Warrior-Gosai/TalkG/2e965c5edc1735850f3db8f0fbd101c4121fee4e/screenshots/1.jpg
--------------------------------------------------------------------------------
/screenshots/2.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Warrior-Gosai/TalkG/2e965c5edc1735850f3db8f0fbd101c4121fee4e/screenshots/2.jpg
--------------------------------------------------------------------------------
/screenshots/3.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Warrior-Gosai/TalkG/2e965c5edc1735850f3db8f0fbd101c4121fee4e/screenshots/3.jpg
--------------------------------------------------------------------------------
/screenshots/4.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Warrior-Gosai/TalkG/2e965c5edc1735850f3db8f0fbd101c4121fee4e/screenshots/4.jpg
--------------------------------------------------------------------------------
/screenshots/5.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Warrior-Gosai/TalkG/2e965c5edc1735850f3db8f0fbd101c4121fee4e/screenshots/5.jpg
--------------------------------------------------------------------------------
/screenshots/6.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Warrior-Gosai/TalkG/2e965c5edc1735850f3db8f0fbd101c4121fee4e/screenshots/6.jpg
--------------------------------------------------------------------------------
/screenshots/7.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Warrior-Gosai/TalkG/2e965c5edc1735850f3db8f0fbd101c4121fee4e/screenshots/7.jpg
--------------------------------------------------------------------------------
/screenshots/8.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Warrior-Gosai/TalkG/2e965c5edc1735850f3db8f0fbd101c4121fee4e/screenshots/8.jpg
--------------------------------------------------------------------------------
/talkg.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/test/widget_test.dart:
--------------------------------------------------------------------------------
1 | // This is a basic Flutter widget test.
2 | //
3 | // To perform an interaction with a widget in your test, use the WidgetTester
4 | // utility in the flutter_test package. For example, you can send tap and scroll
5 | // gestures. You can also use WidgetTester to find child widgets in the widget
6 | // tree, read text, and verify that the values of widget properties are correct.
7 |
8 | import 'package:flutter/material.dart';
9 | import 'package:flutter_test/flutter_test.dart';
10 |
11 | import 'package:talkg/main.dart';
12 |
13 | void main() {
14 | testWidgets('Counter increments smoke test', (WidgetTester tester) async {
15 | // Build our app and trigger a frame.
16 | await tester.pumpWidget(const MyApp());
17 |
18 | // Verify that our counter starts at 0.
19 | expect(find.text('0'), findsOneWidget);
20 | expect(find.text('1'), findsNothing);
21 |
22 | // Tap the '+' icon and trigger a frame.
23 | await tester.tap(find.byIcon(Icons.add));
24 | await tester.pump();
25 |
26 | // Verify that our counter has incremented.
27 | expect(find.text('0'), findsNothing);
28 | expect(find.text('1'), findsOneWidget);
29 | });
30 | }
31 |
--------------------------------------------------------------------------------
/web/favicon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Warrior-Gosai/TalkG/2e965c5edc1735850f3db8f0fbd101c4121fee4e/web/favicon.png
--------------------------------------------------------------------------------
/web/icons/Icon-192.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Warrior-Gosai/TalkG/2e965c5edc1735850f3db8f0fbd101c4121fee4e/web/icons/Icon-192.png
--------------------------------------------------------------------------------
/web/icons/Icon-512.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Warrior-Gosai/TalkG/2e965c5edc1735850f3db8f0fbd101c4121fee4e/web/icons/Icon-512.png
--------------------------------------------------------------------------------
/web/icons/Icon-maskable-192.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Warrior-Gosai/TalkG/2e965c5edc1735850f3db8f0fbd101c4121fee4e/web/icons/Icon-maskable-192.png
--------------------------------------------------------------------------------
/web/icons/Icon-maskable-512.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Warrior-Gosai/TalkG/2e965c5edc1735850f3db8f0fbd101c4121fee4e/web/icons/Icon-maskable-512.png
--------------------------------------------------------------------------------
/web/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 | talkg
33 |
34 |
35 |
39 |
40 |
41 |
42 |
43 |
58 |
59 |
60 |
--------------------------------------------------------------------------------
/web/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "talkg",
3 | "short_name": "talkg",
4 | "start_url": ".",
5 | "display": "standalone",
6 | "background_color": "#0175C2",
7 | "theme_color": "#0175C2",
8 | "description": "A new Flutter project.",
9 | "orientation": "portrait-primary",
10 | "prefer_related_applications": false,
11 | "icons": [
12 | {
13 | "src": "icons/Icon-192.png",
14 | "sizes": "192x192",
15 | "type": "image/png"
16 | },
17 | {
18 | "src": "icons/Icon-512.png",
19 | "sizes": "512x512",
20 | "type": "image/png"
21 | },
22 | {
23 | "src": "icons/Icon-maskable-192.png",
24 | "sizes": "192x192",
25 | "type": "image/png",
26 | "purpose": "maskable"
27 | },
28 | {
29 | "src": "icons/Icon-maskable-512.png",
30 | "sizes": "512x512",
31 | "type": "image/png",
32 | "purpose": "maskable"
33 | }
34 | ]
35 | }
36 |
--------------------------------------------------------------------------------
/windows/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | # Project-level configuration.
2 | cmake_minimum_required(VERSION 3.14)
3 | project(talkg LANGUAGES CXX)
4 |
5 | # The name of the executable created for the application. Change this to change
6 | # the on-disk name of your application.
7 | set(BINARY_NAME "talkg")
8 |
9 | # Explicitly opt in to modern CMake behaviors to avoid warnings with recent
10 | # versions of CMake.
11 | cmake_policy(SET CMP0063 NEW)
12 |
13 | # Define build configuration option.
14 | get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)
15 | if(IS_MULTICONFIG)
16 | set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release"
17 | CACHE STRING "" FORCE)
18 | else()
19 | if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
20 | set(CMAKE_BUILD_TYPE "Debug" CACHE
21 | STRING "Flutter build mode" FORCE)
22 | set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS
23 | "Debug" "Profile" "Release")
24 | endif()
25 | endif()
26 | # Define settings for the Profile build mode.
27 | set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}")
28 | set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}")
29 | set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}")
30 | set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}")
31 |
32 | # Use Unicode for all projects.
33 | add_definitions(-DUNICODE -D_UNICODE)
34 |
35 | # Compilation settings that should be applied to most targets.
36 | #
37 | # Be cautious about adding new options here, as plugins use this function by
38 | # default. In most cases, you should add new options to specific targets instead
39 | # of modifying this function.
40 | function(APPLY_STANDARD_SETTINGS TARGET)
41 | target_compile_features(${TARGET} PUBLIC cxx_std_17)
42 | target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100")
43 | target_compile_options(${TARGET} PRIVATE /EHsc)
44 | target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0")
45 | target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>")
46 | endfunction()
47 |
48 | # Flutter library and tool build rules.
49 | set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter")
50 | add_subdirectory(${FLUTTER_MANAGED_DIR})
51 |
52 | # Application build; see runner/CMakeLists.txt.
53 | add_subdirectory("runner")
54 |
55 |
56 | # Generated plugin build rules, which manage building the plugins and adding
57 | # them to the application.
58 | include(flutter/generated_plugins.cmake)
59 |
60 |
61 | # === Installation ===
62 | # Support files are copied into place next to the executable, so that it can
63 | # run in place. This is done instead of making a separate bundle (as on Linux)
64 | # so that building and running from within Visual Studio will work.
65 | set(BUILD_BUNDLE_DIR "$")
66 | # Make the "install" step default, as it's required to run.
67 | set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1)
68 | if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT)
69 | set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE)
70 | endif()
71 |
72 | set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data")
73 | set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}")
74 |
75 | install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}"
76 | COMPONENT Runtime)
77 |
78 | install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}"
79 | COMPONENT Runtime)
80 |
81 | install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
82 | COMPONENT Runtime)
83 |
84 | if(PLUGIN_BUNDLED_LIBRARIES)
85 | install(FILES "${PLUGIN_BUNDLED_LIBRARIES}"
86 | DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
87 | COMPONENT Runtime)
88 | endif()
89 |
90 | # Fully re-copy the assets directory on each build to avoid having stale files
91 | # from a previous install.
92 | set(FLUTTER_ASSET_DIR_NAME "flutter_assets")
93 | install(CODE "
94 | file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\")
95 | " COMPONENT Runtime)
96 | install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}"
97 | DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime)
98 |
99 | # Install the AOT library on non-Debug builds only.
100 | install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}"
101 | CONFIGURATIONS Profile;Release
102 | COMPONENT Runtime)
103 |
--------------------------------------------------------------------------------
/windows/flutter/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | # This file controls Flutter-level build steps. It should not be edited.
2 | cmake_minimum_required(VERSION 3.14)
3 |
4 | set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral")
5 |
6 | # Configuration provided via flutter tool.
7 | include(${EPHEMERAL_DIR}/generated_config.cmake)
8 |
9 | # TODO: Move the rest of this into files in ephemeral. See
10 | # https://github.com/flutter/flutter/issues/57146.
11 | set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper")
12 |
13 | # === Flutter Library ===
14 | set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll")
15 |
16 | # Published to parent scope for install step.
17 | set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE)
18 | set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE)
19 | set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE)
20 | set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE)
21 |
22 | list(APPEND FLUTTER_LIBRARY_HEADERS
23 | "flutter_export.h"
24 | "flutter_windows.h"
25 | "flutter_messenger.h"
26 | "flutter_plugin_registrar.h"
27 | "flutter_texture_registrar.h"
28 | )
29 | list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/")
30 | add_library(flutter INTERFACE)
31 | target_include_directories(flutter INTERFACE
32 | "${EPHEMERAL_DIR}"
33 | )
34 | target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib")
35 | add_dependencies(flutter flutter_assemble)
36 |
37 | # === Wrapper ===
38 | list(APPEND CPP_WRAPPER_SOURCES_CORE
39 | "core_implementations.cc"
40 | "standard_codec.cc"
41 | )
42 | list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/")
43 | list(APPEND CPP_WRAPPER_SOURCES_PLUGIN
44 | "plugin_registrar.cc"
45 | )
46 | list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/")
47 | list(APPEND CPP_WRAPPER_SOURCES_APP
48 | "flutter_engine.cc"
49 | "flutter_view_controller.cc"
50 | )
51 | list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/")
52 |
53 | # Wrapper sources needed for a plugin.
54 | add_library(flutter_wrapper_plugin STATIC
55 | ${CPP_WRAPPER_SOURCES_CORE}
56 | ${CPP_WRAPPER_SOURCES_PLUGIN}
57 | )
58 | apply_standard_settings(flutter_wrapper_plugin)
59 | set_target_properties(flutter_wrapper_plugin PROPERTIES
60 | POSITION_INDEPENDENT_CODE ON)
61 | set_target_properties(flutter_wrapper_plugin PROPERTIES
62 | CXX_VISIBILITY_PRESET hidden)
63 | target_link_libraries(flutter_wrapper_plugin PUBLIC flutter)
64 | target_include_directories(flutter_wrapper_plugin PUBLIC
65 | "${WRAPPER_ROOT}/include"
66 | )
67 | add_dependencies(flutter_wrapper_plugin flutter_assemble)
68 |
69 | # Wrapper sources needed for the runner.
70 | add_library(flutter_wrapper_app STATIC
71 | ${CPP_WRAPPER_SOURCES_CORE}
72 | ${CPP_WRAPPER_SOURCES_APP}
73 | )
74 | apply_standard_settings(flutter_wrapper_app)
75 | target_link_libraries(flutter_wrapper_app PUBLIC flutter)
76 | target_include_directories(flutter_wrapper_app PUBLIC
77 | "${WRAPPER_ROOT}/include"
78 | )
79 | add_dependencies(flutter_wrapper_app flutter_assemble)
80 |
81 | # === Flutter tool backend ===
82 | # _phony_ is a non-existent file to force this command to run every time,
83 | # since currently there's no way to get a full input/output list from the
84 | # flutter tool.
85 | set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_")
86 | set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE)
87 | add_custom_command(
88 | OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS}
89 | ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN}
90 | ${CPP_WRAPPER_SOURCES_APP}
91 | ${PHONY_OUTPUT}
92 | COMMAND ${CMAKE_COMMAND} -E env
93 | ${FLUTTER_TOOL_ENVIRONMENT}
94 | "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat"
95 | windows-x64 $
96 | VERBATIM
97 | )
98 | add_custom_target(flutter_assemble DEPENDS
99 | "${FLUTTER_LIBRARY}"
100 | ${FLUTTER_LIBRARY_HEADERS}
101 | ${CPP_WRAPPER_SOURCES_CORE}
102 | ${CPP_WRAPPER_SOURCES_PLUGIN}
103 | ${CPP_WRAPPER_SOURCES_APP}
104 | )
105 |
--------------------------------------------------------------------------------
/windows/runner/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | cmake_minimum_required(VERSION 3.14)
2 | project(runner LANGUAGES CXX)
3 |
4 | # Define the application target. To change its name, change BINARY_NAME in the
5 | # top-level CMakeLists.txt, not the value here, or `flutter run` will no longer
6 | # work.
7 | #
8 | # Any new source files that you add to the application should be added here.
9 | add_executable(${BINARY_NAME} WIN32
10 | "flutter_window.cpp"
11 | "main.cpp"
12 | "utils.cpp"
13 | "win32_window.cpp"
14 | "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc"
15 | "Runner.rc"
16 | "runner.exe.manifest"
17 | )
18 |
19 | # Apply the standard set of build settings. This can be removed for applications
20 | # that need different build settings.
21 | apply_standard_settings(${BINARY_NAME})
22 |
23 | # Add preprocessor definitions for the build version.
24 | target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"")
25 | target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}")
26 | target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}")
27 | target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}")
28 | target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}")
29 |
30 | # Disable Windows macros that collide with C++ standard library functions.
31 | target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX")
32 |
33 | # Add dependency libraries and include directories. Add any application-specific
34 | # dependencies here.
35 | target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app)
36 | target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib")
37 | target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}")
38 |
39 | # Run the Flutter tool portions of the build. This must not be removed.
40 | add_dependencies(${BINARY_NAME} flutter_assemble)
41 |
--------------------------------------------------------------------------------
/windows/runner/Runner.rc:
--------------------------------------------------------------------------------
1 | // Microsoft Visual C++ generated resource script.
2 | //
3 | #pragma code_page(65001)
4 | #include "resource.h"
5 |
6 | #define APSTUDIO_READONLY_SYMBOLS
7 | /////////////////////////////////////////////////////////////////////////////
8 | //
9 | // Generated from the TEXTINCLUDE 2 resource.
10 | //
11 | #include "winres.h"
12 |
13 | /////////////////////////////////////////////////////////////////////////////
14 | #undef APSTUDIO_READONLY_SYMBOLS
15 |
16 | /////////////////////////////////////////////////////////////////////////////
17 | // English (United States) resources
18 |
19 | #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
20 | LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
21 |
22 | #ifdef APSTUDIO_INVOKED
23 | /////////////////////////////////////////////////////////////////////////////
24 | //
25 | // TEXTINCLUDE
26 | //
27 |
28 | 1 TEXTINCLUDE
29 | BEGIN
30 | "resource.h\0"
31 | END
32 |
33 | 2 TEXTINCLUDE
34 | BEGIN
35 | "#include ""winres.h""\r\n"
36 | "\0"
37 | END
38 |
39 | 3 TEXTINCLUDE
40 | BEGIN
41 | "\r\n"
42 | "\0"
43 | END
44 |
45 | #endif // APSTUDIO_INVOKED
46 |
47 |
48 | /////////////////////////////////////////////////////////////////////////////
49 | //
50 | // Icon
51 | //
52 |
53 | // Icon with lowest ID value placed first to ensure application icon
54 | // remains consistent on all systems.
55 | IDI_APP_ICON ICON "resources\\app_icon.ico"
56 |
57 |
58 | /////////////////////////////////////////////////////////////////////////////
59 | //
60 | // Version
61 | //
62 |
63 | #if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD)
64 | #define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD
65 | #else
66 | #define VERSION_AS_NUMBER 1,0,0,0
67 | #endif
68 |
69 | #if defined(FLUTTER_VERSION)
70 | #define VERSION_AS_STRING FLUTTER_VERSION
71 | #else
72 | #define VERSION_AS_STRING "1.0.0"
73 | #endif
74 |
75 | VS_VERSION_INFO VERSIONINFO
76 | FILEVERSION VERSION_AS_NUMBER
77 | PRODUCTVERSION VERSION_AS_NUMBER
78 | FILEFLAGSMASK VS_FFI_FILEFLAGSMASK
79 | #ifdef _DEBUG
80 | FILEFLAGS VS_FF_DEBUG
81 | #else
82 | FILEFLAGS 0x0L
83 | #endif
84 | FILEOS VOS__WINDOWS32
85 | FILETYPE VFT_APP
86 | FILESUBTYPE 0x0L
87 | BEGIN
88 | BLOCK "StringFileInfo"
89 | BEGIN
90 | BLOCK "040904e4"
91 | BEGIN
92 | VALUE "CompanyName", "com.example" "\0"
93 | VALUE "FileDescription", "talkg" "\0"
94 | VALUE "FileVersion", VERSION_AS_STRING "\0"
95 | VALUE "InternalName", "talkg" "\0"
96 | VALUE "LegalCopyright", "Copyright (C) 2023 com.example. All rights reserved." "\0"
97 | VALUE "OriginalFilename", "talkg.exe" "\0"
98 | VALUE "ProductName", "talkg" "\0"
99 | VALUE "ProductVersion", VERSION_AS_STRING "\0"
100 | END
101 | END
102 | BLOCK "VarFileInfo"
103 | BEGIN
104 | VALUE "Translation", 0x409, 1252
105 | END
106 | END
107 |
108 | #endif // English (United States) resources
109 | /////////////////////////////////////////////////////////////////////////////
110 |
111 |
112 |
113 | #ifndef APSTUDIO_INVOKED
114 | /////////////////////////////////////////////////////////////////////////////
115 | //
116 | // Generated from the TEXTINCLUDE 3 resource.
117 | //
118 |
119 |
120 | /////////////////////////////////////////////////////////////////////////////
121 | #endif // not APSTUDIO_INVOKED
122 |
--------------------------------------------------------------------------------
/windows/runner/flutter_window.cpp:
--------------------------------------------------------------------------------
1 | #include "flutter_window.h"
2 |
3 | #include
4 |
5 | #include "flutter/generated_plugin_registrant.h"
6 |
7 | FlutterWindow::FlutterWindow(const flutter::DartProject& project)
8 | : project_(project) {}
9 |
10 | FlutterWindow::~FlutterWindow() {}
11 |
12 | bool FlutterWindow::OnCreate() {
13 | if (!Win32Window::OnCreate()) {
14 | return false;
15 | }
16 |
17 | RECT frame = GetClientArea();
18 |
19 | // The size here must match the window dimensions to avoid unnecessary surface
20 | // creation / destruction in the startup path.
21 | flutter_controller_ = std::make_unique(
22 | frame.right - frame.left, frame.bottom - frame.top, project_);
23 | // Ensure that basic setup of the controller was successful.
24 | if (!flutter_controller_->engine() || !flutter_controller_->view()) {
25 | return false;
26 | }
27 | RegisterPlugins(flutter_controller_->engine());
28 | SetChildContent(flutter_controller_->view()->GetNativeWindow());
29 |
30 | flutter_controller_->engine()->SetNextFrameCallback([&]() {
31 | this->Show();
32 | });
33 |
34 | return true;
35 | }
36 |
37 | void FlutterWindow::OnDestroy() {
38 | if (flutter_controller_) {
39 | flutter_controller_ = nullptr;
40 | }
41 |
42 | Win32Window::OnDestroy();
43 | }
44 |
45 | LRESULT
46 | FlutterWindow::MessageHandler(HWND hwnd, UINT const message,
47 | WPARAM const wparam,
48 | LPARAM const lparam) noexcept {
49 | // Give Flutter, including plugins, an opportunity to handle window messages.
50 | if (flutter_controller_) {
51 | std::optional result =
52 | flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam,
53 | lparam);
54 | if (result) {
55 | return *result;
56 | }
57 | }
58 |
59 | switch (message) {
60 | case WM_FONTCHANGE:
61 | flutter_controller_->engine()->ReloadSystemFonts();
62 | break;
63 | }
64 |
65 | return Win32Window::MessageHandler(hwnd, message, wparam, lparam);
66 | }
67 |
--------------------------------------------------------------------------------
/windows/runner/flutter_window.h:
--------------------------------------------------------------------------------
1 | #ifndef RUNNER_FLUTTER_WINDOW_H_
2 | #define RUNNER_FLUTTER_WINDOW_H_
3 |
4 | #include
5 | #include
6 |
7 | #include
8 |
9 | #include "win32_window.h"
10 |
11 | // A window that does nothing but host a Flutter view.
12 | class FlutterWindow : public Win32Window {
13 | public:
14 | // Creates a new FlutterWindow hosting a Flutter view running |project|.
15 | explicit FlutterWindow(const flutter::DartProject& project);
16 | virtual ~FlutterWindow();
17 |
18 | protected:
19 | // Win32Window:
20 | bool OnCreate() override;
21 | void OnDestroy() override;
22 | LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam,
23 | LPARAM const lparam) noexcept override;
24 |
25 | private:
26 | // The project to run.
27 | flutter::DartProject project_;
28 |
29 | // The Flutter instance hosted by this window.
30 | std::unique_ptr flutter_controller_;
31 | };
32 |
33 | #endif // RUNNER_FLUTTER_WINDOW_H_
34 |
--------------------------------------------------------------------------------
/windows/runner/main.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | #include "flutter_window.h"
6 | #include "utils.h"
7 |
8 | int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,
9 | _In_ wchar_t *command_line, _In_ int show_command) {
10 | // Attach to console when present (e.g., 'flutter run') or create a
11 | // new console when running with a debugger.
12 | if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) {
13 | CreateAndAttachConsole();
14 | }
15 |
16 | // Initialize COM, so that it is available for use in the library and/or
17 | // plugins.
18 | ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
19 |
20 | flutter::DartProject project(L"data");
21 |
22 | std::vector command_line_arguments =
23 | GetCommandLineArguments();
24 |
25 | project.set_dart_entrypoint_arguments(std::move(command_line_arguments));
26 |
27 | FlutterWindow window(project);
28 | Win32Window::Point origin(10, 10);
29 | Win32Window::Size size(1280, 720);
30 | if (!window.Create(L"talkg", origin, size)) {
31 | return EXIT_FAILURE;
32 | }
33 | window.SetQuitOnClose(true);
34 |
35 | ::MSG msg;
36 | while (::GetMessage(&msg, nullptr, 0, 0)) {
37 | ::TranslateMessage(&msg);
38 | ::DispatchMessage(&msg);
39 | }
40 |
41 | ::CoUninitialize();
42 | return EXIT_SUCCESS;
43 | }
44 |
--------------------------------------------------------------------------------
/windows/runner/resource.h:
--------------------------------------------------------------------------------
1 | //{{NO_DEPENDENCIES}}
2 | // Microsoft Visual C++ generated include file.
3 | // Used by Runner.rc
4 | //
5 | #define IDI_APP_ICON 101
6 |
7 | // Next default values for new objects
8 | //
9 | #ifdef APSTUDIO_INVOKED
10 | #ifndef APSTUDIO_READONLY_SYMBOLS
11 | #define _APS_NEXT_RESOURCE_VALUE 102
12 | #define _APS_NEXT_COMMAND_VALUE 40001
13 | #define _APS_NEXT_CONTROL_VALUE 1001
14 | #define _APS_NEXT_SYMED_VALUE 101
15 | #endif
16 | #endif
17 |
--------------------------------------------------------------------------------
/windows/runner/resources/app_icon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Warrior-Gosai/TalkG/2e965c5edc1735850f3db8f0fbd101c4121fee4e/windows/runner/resources/app_icon.ico
--------------------------------------------------------------------------------
/windows/runner/runner.exe.manifest:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | PerMonitorV2
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/windows/runner/utils.cpp:
--------------------------------------------------------------------------------
1 | #include "utils.h"
2 |
3 | #include
4 | #include
5 | #include
6 | #include
7 |
8 | #include
9 |
10 | void CreateAndAttachConsole() {
11 | if (::AllocConsole()) {
12 | FILE *unused;
13 | if (freopen_s(&unused, "CONOUT$", "w", stdout)) {
14 | _dup2(_fileno(stdout), 1);
15 | }
16 | if (freopen_s(&unused, "CONOUT$", "w", stderr)) {
17 | _dup2(_fileno(stdout), 2);
18 | }
19 | std::ios::sync_with_stdio();
20 | FlutterDesktopResyncOutputStreams();
21 | }
22 | }
23 |
24 | std::vector GetCommandLineArguments() {
25 | // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use.
26 | int argc;
27 | wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc);
28 | if (argv == nullptr) {
29 | return std::vector();
30 | }
31 |
32 | std::vector command_line_arguments;
33 |
34 | // Skip the first argument as it's the binary name.
35 | for (int i = 1; i < argc; i++) {
36 | command_line_arguments.push_back(Utf8FromUtf16(argv[i]));
37 | }
38 |
39 | ::LocalFree(argv);
40 |
41 | return command_line_arguments;
42 | }
43 |
44 | std::string Utf8FromUtf16(const wchar_t* utf16_string) {
45 | if (utf16_string == nullptr) {
46 | return std::string();
47 | }
48 | int target_length = ::WideCharToMultiByte(
49 | CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string,
50 | -1, nullptr, 0, nullptr, nullptr)
51 | -1; // remove the trailing null character
52 | int input_length = (int)wcslen(utf16_string);
53 | std::string utf8_string;
54 | if (target_length <= 0 || target_length > utf8_string.max_size()) {
55 | return utf8_string;
56 | }
57 | utf8_string.resize(target_length);
58 | int converted_length = ::WideCharToMultiByte(
59 | CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string,
60 | input_length, utf8_string.data(), target_length, nullptr, nullptr);
61 | if (converted_length == 0) {
62 | return std::string();
63 | }
64 | return utf8_string;
65 | }
66 |
--------------------------------------------------------------------------------
/windows/runner/utils.h:
--------------------------------------------------------------------------------
1 | #ifndef RUNNER_UTILS_H_
2 | #define RUNNER_UTILS_H_
3 |
4 | #include
5 | #include
6 |
7 | // Creates a console for the process, and redirects stdout and stderr to
8 | // it for both the runner and the Flutter library.
9 | void CreateAndAttachConsole();
10 |
11 | // Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string
12 | // encoded in UTF-8. Returns an empty std::string on failure.
13 | std::string Utf8FromUtf16(const wchar_t* utf16_string);
14 |
15 | // Gets the command line arguments passed in as a std::vector,
16 | // encoded in UTF-8. Returns an empty std::vector on failure.
17 | std::vector GetCommandLineArguments();
18 |
19 | #endif // RUNNER_UTILS_H_
20 |
--------------------------------------------------------------------------------
/windows/runner/win32_window.cpp:
--------------------------------------------------------------------------------
1 | #include "win32_window.h"
2 |
3 | #include
4 | #include
5 |
6 | #include "resource.h"
7 |
8 | namespace {
9 |
10 | /// Window attribute that enables dark mode window decorations.
11 | ///
12 | /// Redefined in case the developer's machine has a Windows SDK older than
13 | /// version 10.0.22000.0.
14 | /// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute
15 | #ifndef DWMWA_USE_IMMERSIVE_DARK_MODE
16 | #define DWMWA_USE_IMMERSIVE_DARK_MODE 20
17 | #endif
18 |
19 | constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW";
20 |
21 | /// Registry key for app theme preference.
22 | ///
23 | /// A value of 0 indicates apps should use dark mode. A non-zero or missing
24 | /// value indicates apps should use light mode.
25 | constexpr const wchar_t kGetPreferredBrightnessRegKey[] =
26 | L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize";
27 | constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme";
28 |
29 | // The number of Win32Window objects that currently exist.
30 | static int g_active_window_count = 0;
31 |
32 | using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd);
33 |
34 | // Scale helper to convert logical scaler values to physical using passed in
35 | // scale factor
36 | int Scale(int source, double scale_factor) {
37 | return static_cast(source * scale_factor);
38 | }
39 |
40 | // Dynamically loads the |EnableNonClientDpiScaling| from the User32 module.
41 | // This API is only needed for PerMonitor V1 awareness mode.
42 | void EnableFullDpiSupportIfAvailable(HWND hwnd) {
43 | HMODULE user32_module = LoadLibraryA("User32.dll");
44 | if (!user32_module) {
45 | return;
46 | }
47 | auto enable_non_client_dpi_scaling =
48 | reinterpret_cast(
49 | GetProcAddress(user32_module, "EnableNonClientDpiScaling"));
50 | if (enable_non_client_dpi_scaling != nullptr) {
51 | enable_non_client_dpi_scaling(hwnd);
52 | }
53 | FreeLibrary(user32_module);
54 | }
55 |
56 | } // namespace
57 |
58 | // Manages the Win32Window's window class registration.
59 | class WindowClassRegistrar {
60 | public:
61 | ~WindowClassRegistrar() = default;
62 |
63 | // Returns the singleton registrar instance.
64 | static WindowClassRegistrar* GetInstance() {
65 | if (!instance_) {
66 | instance_ = new WindowClassRegistrar();
67 | }
68 | return instance_;
69 | }
70 |
71 | // Returns the name of the window class, registering the class if it hasn't
72 | // previously been registered.
73 | const wchar_t* GetWindowClass();
74 |
75 | // Unregisters the window class. Should only be called if there are no
76 | // instances of the window.
77 | void UnregisterWindowClass();
78 |
79 | private:
80 | WindowClassRegistrar() = default;
81 |
82 | static WindowClassRegistrar* instance_;
83 |
84 | bool class_registered_ = false;
85 | };
86 |
87 | WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr;
88 |
89 | const wchar_t* WindowClassRegistrar::GetWindowClass() {
90 | if (!class_registered_) {
91 | WNDCLASS window_class{};
92 | window_class.hCursor = LoadCursor(nullptr, IDC_ARROW);
93 | window_class.lpszClassName = kWindowClassName;
94 | window_class.style = CS_HREDRAW | CS_VREDRAW;
95 | window_class.cbClsExtra = 0;
96 | window_class.cbWndExtra = 0;
97 | window_class.hInstance = GetModuleHandle(nullptr);
98 | window_class.hIcon =
99 | LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON));
100 | window_class.hbrBackground = 0;
101 | window_class.lpszMenuName = nullptr;
102 | window_class.lpfnWndProc = Win32Window::WndProc;
103 | RegisterClass(&window_class);
104 | class_registered_ = true;
105 | }
106 | return kWindowClassName;
107 | }
108 |
109 | void WindowClassRegistrar::UnregisterWindowClass() {
110 | UnregisterClass(kWindowClassName, nullptr);
111 | class_registered_ = false;
112 | }
113 |
114 | Win32Window::Win32Window() {
115 | ++g_active_window_count;
116 | }
117 |
118 | Win32Window::~Win32Window() {
119 | --g_active_window_count;
120 | Destroy();
121 | }
122 |
123 | bool Win32Window::Create(const std::wstring& title,
124 | const Point& origin,
125 | const Size& size) {
126 | Destroy();
127 |
128 | const wchar_t* window_class =
129 | WindowClassRegistrar::GetInstance()->GetWindowClass();
130 |
131 | const POINT target_point = {static_cast(origin.x),
132 | static_cast(origin.y)};
133 | HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST);
134 | UINT dpi = FlutterDesktopGetDpiForMonitor(monitor);
135 | double scale_factor = dpi / 96.0;
136 |
137 | HWND window = CreateWindow(
138 | window_class, title.c_str(), WS_OVERLAPPEDWINDOW,
139 | Scale(origin.x, scale_factor), Scale(origin.y, scale_factor),
140 | Scale(size.width, scale_factor), Scale(size.height, scale_factor),
141 | nullptr, nullptr, GetModuleHandle(nullptr), this);
142 |
143 | if (!window) {
144 | return false;
145 | }
146 |
147 | UpdateTheme(window);
148 |
149 | return OnCreate();
150 | }
151 |
152 | bool Win32Window::Show() {
153 | return ShowWindow(window_handle_, SW_SHOWNORMAL);
154 | }
155 |
156 | // static
157 | LRESULT CALLBACK Win32Window::WndProc(HWND const window,
158 | UINT const message,
159 | WPARAM const wparam,
160 | LPARAM const lparam) noexcept {
161 | if (message == WM_NCCREATE) {
162 | auto window_struct = reinterpret_cast(lparam);
163 | SetWindowLongPtr(window, GWLP_USERDATA,
164 | reinterpret_cast(window_struct->lpCreateParams));
165 |
166 | auto that = static_cast(window_struct->lpCreateParams);
167 | EnableFullDpiSupportIfAvailable(window);
168 | that->window_handle_ = window;
169 | } else if (Win32Window* that = GetThisFromHandle(window)) {
170 | return that->MessageHandler(window, message, wparam, lparam);
171 | }
172 |
173 | return DefWindowProc(window, message, wparam, lparam);
174 | }
175 |
176 | LRESULT
177 | Win32Window::MessageHandler(HWND hwnd,
178 | UINT const message,
179 | WPARAM const wparam,
180 | LPARAM const lparam) noexcept {
181 | switch (message) {
182 | case WM_DESTROY:
183 | window_handle_ = nullptr;
184 | Destroy();
185 | if (quit_on_close_) {
186 | PostQuitMessage(0);
187 | }
188 | return 0;
189 |
190 | case WM_DPICHANGED: {
191 | auto newRectSize = reinterpret_cast(lparam);
192 | LONG newWidth = newRectSize->right - newRectSize->left;
193 | LONG newHeight = newRectSize->bottom - newRectSize->top;
194 |
195 | SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth,
196 | newHeight, SWP_NOZORDER | SWP_NOACTIVATE);
197 |
198 | return 0;
199 | }
200 | case WM_SIZE: {
201 | RECT rect = GetClientArea();
202 | if (child_content_ != nullptr) {
203 | // Size and position the child window.
204 | MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left,
205 | rect.bottom - rect.top, TRUE);
206 | }
207 | return 0;
208 | }
209 |
210 | case WM_ACTIVATE:
211 | if (child_content_ != nullptr) {
212 | SetFocus(child_content_);
213 | }
214 | return 0;
215 |
216 | case WM_DWMCOLORIZATIONCOLORCHANGED:
217 | UpdateTheme(hwnd);
218 | return 0;
219 | }
220 |
221 | return DefWindowProc(window_handle_, message, wparam, lparam);
222 | }
223 |
224 | void Win32Window::Destroy() {
225 | OnDestroy();
226 |
227 | if (window_handle_) {
228 | DestroyWindow(window_handle_);
229 | window_handle_ = nullptr;
230 | }
231 | if (g_active_window_count == 0) {
232 | WindowClassRegistrar::GetInstance()->UnregisterWindowClass();
233 | }
234 | }
235 |
236 | Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept {
237 | return reinterpret_cast(
238 | GetWindowLongPtr(window, GWLP_USERDATA));
239 | }
240 |
241 | void Win32Window::SetChildContent(HWND content) {
242 | child_content_ = content;
243 | SetParent(content, window_handle_);
244 | RECT frame = GetClientArea();
245 |
246 | MoveWindow(content, frame.left, frame.top, frame.right - frame.left,
247 | frame.bottom - frame.top, true);
248 |
249 | SetFocus(child_content_);
250 | }
251 |
252 | RECT Win32Window::GetClientArea() {
253 | RECT frame;
254 | GetClientRect(window_handle_, &frame);
255 | return frame;
256 | }
257 |
258 | HWND Win32Window::GetHandle() {
259 | return window_handle_;
260 | }
261 |
262 | void Win32Window::SetQuitOnClose(bool quit_on_close) {
263 | quit_on_close_ = quit_on_close;
264 | }
265 |
266 | bool Win32Window::OnCreate() {
267 | // No-op; provided for subclasses.
268 | return true;
269 | }
270 |
271 | void Win32Window::OnDestroy() {
272 | // No-op; provided for subclasses.
273 | }
274 |
275 | void Win32Window::UpdateTheme(HWND const window) {
276 | DWORD light_mode;
277 | DWORD light_mode_size = sizeof(light_mode);
278 | LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey,
279 | kGetPreferredBrightnessRegValue,
280 | RRF_RT_REG_DWORD, nullptr, &light_mode,
281 | &light_mode_size);
282 |
283 | if (result == ERROR_SUCCESS) {
284 | BOOL enable_dark_mode = light_mode == 0;
285 | DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE,
286 | &enable_dark_mode, sizeof(enable_dark_mode));
287 | }
288 | }
289 |
--------------------------------------------------------------------------------
/windows/runner/win32_window.h:
--------------------------------------------------------------------------------
1 | #ifndef RUNNER_WIN32_WINDOW_H_
2 | #define RUNNER_WIN32_WINDOW_H_
3 |
4 | #include
5 |
6 | #include
7 | #include
8 | #include
9 |
10 | // A class abstraction for a high DPI-aware Win32 Window. Intended to be
11 | // inherited from by classes that wish to specialize with custom
12 | // rendering and input handling
13 | class Win32Window {
14 | public:
15 | struct Point {
16 | unsigned int x;
17 | unsigned int y;
18 | Point(unsigned int x, unsigned int y) : x(x), y(y) {}
19 | };
20 |
21 | struct Size {
22 | unsigned int width;
23 | unsigned int height;
24 | Size(unsigned int width, unsigned int height)
25 | : width(width), height(height) {}
26 | };
27 |
28 | Win32Window();
29 | virtual ~Win32Window();
30 |
31 | // Creates a win32 window with |title| that is positioned and sized using
32 | // |origin| and |size|. New windows are created on the default monitor. Window
33 | // sizes are specified to the OS in physical pixels, hence to ensure a
34 | // consistent size this function will scale the inputted width and height as
35 | // as appropriate for the default monitor. The window is invisible until
36 | // |Show| is called. Returns true if the window was created successfully.
37 | bool Create(const std::wstring& title, const Point& origin, const Size& size);
38 |
39 | // Show the current window. Returns true if the window was successfully shown.
40 | bool Show();
41 |
42 | // Release OS resources associated with window.
43 | void Destroy();
44 |
45 | // Inserts |content| into the window tree.
46 | void SetChildContent(HWND content);
47 |
48 | // Returns the backing Window handle to enable clients to set icon and other
49 | // window properties. Returns nullptr if the window has been destroyed.
50 | HWND GetHandle();
51 |
52 | // If true, closing this window will quit the application.
53 | void SetQuitOnClose(bool quit_on_close);
54 |
55 | // Return a RECT representing the bounds of the current client area.
56 | RECT GetClientArea();
57 |
58 | protected:
59 | // Processes and route salient window messages for mouse handling,
60 | // size change and DPI. Delegates handling of these to member overloads that
61 | // inheriting classes can handle.
62 | virtual LRESULT MessageHandler(HWND window,
63 | UINT const message,
64 | WPARAM const wparam,
65 | LPARAM const lparam) noexcept;
66 |
67 | // Called when CreateAndShow is called, allowing subclass window-related
68 | // setup. Subclasses should return false if setup fails.
69 | virtual bool OnCreate();
70 |
71 | // Called when Destroy is called.
72 | virtual void OnDestroy();
73 |
74 | private:
75 | friend class WindowClassRegistrar;
76 |
77 | // OS callback called by message pump. Handles the WM_NCCREATE message which
78 | // is passed when the non-client area is being created and enables automatic
79 | // non-client DPI scaling so that the non-client area automatically
80 | // responds to changes in DPI. All other messages are handled by
81 | // MessageHandler.
82 | static LRESULT CALLBACK WndProc(HWND const window,
83 | UINT const message,
84 | WPARAM const wparam,
85 | LPARAM const lparam) noexcept;
86 |
87 | // Retrieves a class instance pointer for |window|
88 | static Win32Window* GetThisFromHandle(HWND const window) noexcept;
89 |
90 | // Update the window frame's theme to match the system theme.
91 | static void UpdateTheme(HWND const window);
92 |
93 | bool quit_on_close_ = false;
94 |
95 | // window handle for top level window.
96 | HWND window_handle_ = nullptr;
97 |
98 | // window handle for hosted content.
99 | HWND child_content_ = nullptr;
100 | };
101 |
102 | #endif // RUNNER_WIN32_WINDOW_H_
103 |
--------------------------------------------------------------------------------