diff --git a/.flutter-plugins b/.flutter-plugins new file mode 100644 index 0000000..dba6d0a --- /dev/null +++ b/.flutter-plugins @@ -0,0 +1,17 @@ +# This is a generated file; do not edit or check into version control. +flutter_secure_storage=C:\\Users\\Oguzhan\\AppData\\Local\\Pub\\Cache\\hosted\\pub.dev\\flutter_secure_storage-8.0.0\\ +flutter_secure_storage_linux=C:\\Users\\Oguzhan\\AppData\\Local\\Pub\\Cache\\hosted\\pub.dev\\flutter_secure_storage_linux-1.1.3\\ +flutter_secure_storage_macos=C:\\Users\\Oguzhan\\AppData\\Local\\Pub\\Cache\\hosted\\pub.dev\\flutter_secure_storage_macos-3.0.0\\ +flutter_secure_storage_web=C:\\Users\\Oguzhan\\AppData\\Local\\Pub\\Cache\\hosted\\pub.dev\\flutter_secure_storage_web-1.1.1\\ +flutter_secure_storage_windows=C:\\Users\\Oguzhan\\AppData\\Local\\Pub\\Cache\\hosted\\pub.dev\\flutter_secure_storage_windows-2.0.0\\ +path_provider=C:\\Users\\Oguzhan\\AppData\\Local\\Pub\\Cache\\hosted\\pub.dev\\path_provider-2.0.14\\ +path_provider_android=C:\\Users\\Oguzhan\\AppData\\Local\\Pub\\Cache\\hosted\\pub.dev\\path_provider_android-2.0.25\\ +path_provider_foundation=C:\\Users\\Oguzhan\\AppData\\Local\\Pub\\Cache\\hosted\\pub.dev\\path_provider_foundation-2.2.2\\ +path_provider_linux=C:\\Users\\Oguzhan\\AppData\\Local\\Pub\\Cache\\hosted\\pub.dev\\path_provider_linux-2.1.10\\ +path_provider_windows=C:\\Users\\Oguzhan\\AppData\\Local\\Pub\\Cache\\hosted\\pub.dev\\path_provider_windows-2.1.5\\ +shared_preferences=C:\\Users\\Oguzhan\\AppData\\Local\\Pub\\Cache\\hosted\\pub.dev\\shared_preferences-2.1.0\\ +shared_preferences_android=C:\\Users\\Oguzhan\\AppData\\Local\\Pub\\Cache\\hosted\\pub.dev\\shared_preferences_android-2.1.2\\ +shared_preferences_foundation=C:\\Users\\Oguzhan\\AppData\\Local\\Pub\\Cache\\hosted\\pub.dev\\shared_preferences_foundation-2.2.1\\ +shared_preferences_linux=C:\\Users\\Oguzhan\\AppData\\Local\\Pub\\Cache\\hosted\\pub.dev\\shared_preferences_linux-2.2.0\\ +shared_preferences_web=C:\\Users\\Oguzhan\\AppData\\Local\\Pub\\Cache\\hosted\\pub.dev\\shared_preferences_web-2.1.0\\ +shared_preferences_windows=C:\\Users\\Oguzhan\\AppData\\Local\\Pub\\Cache\\hosted\\pub.dev\\shared_preferences_windows-2.2.0\\ diff --git a/.flutter-plugins-dependencies b/.flutter-plugins-dependencies new file mode 100644 index 0000000..058bacb --- /dev/null +++ b/.flutter-plugins-dependencies @@ -0,0 +1 @@ +{"info":"This is a generated file; do not edit or check into version control.","plugins":{"ios":[{"name":"flutter_secure_storage","path":"C:\\\\Users\\\\Oguzhan\\\\AppData\\\\Local\\\\Pub\\\\Cache\\\\hosted\\\\pub.dev\\\\flutter_secure_storage-8.0.0\\\\","native_build":true,"dependencies":[]},{"name":"path_provider_foundation","path":"C:\\\\Users\\\\Oguzhan\\\\AppData\\\\Local\\\\Pub\\\\Cache\\\\hosted\\\\pub.dev\\\\path_provider_foundation-2.2.2\\\\","native_build":true,"dependencies":[]},{"name":"shared_preferences_foundation","path":"C:\\\\Users\\\\Oguzhan\\\\AppData\\\\Local\\\\Pub\\\\Cache\\\\hosted\\\\pub.dev\\\\shared_preferences_foundation-2.2.1\\\\","native_build":true,"dependencies":[]}],"android":[{"name":"flutter_secure_storage","path":"C:\\\\Users\\\\Oguzhan\\\\AppData\\\\Local\\\\Pub\\\\Cache\\\\hosted\\\\pub.dev\\\\flutter_secure_storage-8.0.0\\\\","native_build":true,"dependencies":[]},{"name":"path_provider_android","path":"C:\\\\Users\\\\Oguzhan\\\\AppData\\\\Local\\\\Pub\\\\Cache\\\\hosted\\\\pub.dev\\\\path_provider_android-2.0.25\\\\","native_build":true,"dependencies":[]},{"name":"shared_preferences_android","path":"C:\\\\Users\\\\Oguzhan\\\\AppData\\\\Local\\\\Pub\\\\Cache\\\\hosted\\\\pub.dev\\\\shared_preferences_android-2.1.2\\\\","native_build":true,"dependencies":[]}],"macos":[{"name":"flutter_secure_storage_macos","path":"C:\\\\Users\\\\Oguzhan\\\\AppData\\\\Local\\\\Pub\\\\Cache\\\\hosted\\\\pub.dev\\\\flutter_secure_storage_macos-3.0.0\\\\","native_build":true,"dependencies":[]},{"name":"path_provider_foundation","path":"C:\\\\Users\\\\Oguzhan\\\\AppData\\\\Local\\\\Pub\\\\Cache\\\\hosted\\\\pub.dev\\\\path_provider_foundation-2.2.2\\\\","native_build":true,"dependencies":[]},{"name":"shared_preferences_foundation","path":"C:\\\\Users\\\\Oguzhan\\\\AppData\\\\Local\\\\Pub\\\\Cache\\\\hosted\\\\pub.dev\\\\shared_preferences_foundation-2.2.1\\\\","native_build":true,"dependencies":[]}],"linux":[{"name":"flutter_secure_storage_linux","path":"C:\\\\Users\\\\Oguzhan\\\\AppData\\\\Local\\\\Pub\\\\Cache\\\\hosted\\\\pub.dev\\\\flutter_secure_storage_linux-1.1.3\\\\","native_build":true,"dependencies":[]},{"name":"path_provider_linux","path":"C:\\\\Users\\\\Oguzhan\\\\AppData\\\\Local\\\\Pub\\\\Cache\\\\hosted\\\\pub.dev\\\\path_provider_linux-2.1.10\\\\","native_build":false,"dependencies":[]},{"name":"shared_preferences_linux","path":"C:\\\\Users\\\\Oguzhan\\\\AppData\\\\Local\\\\Pub\\\\Cache\\\\hosted\\\\pub.dev\\\\shared_preferences_linux-2.2.0\\\\","native_build":false,"dependencies":["path_provider_linux"]}],"windows":[{"name":"flutter_secure_storage_windows","path":"C:\\\\Users\\\\Oguzhan\\\\AppData\\\\Local\\\\Pub\\\\Cache\\\\hosted\\\\pub.dev\\\\flutter_secure_storage_windows-2.0.0\\\\","native_build":true,"dependencies":[]},{"name":"path_provider_windows","path":"C:\\\\Users\\\\Oguzhan\\\\AppData\\\\Local\\\\Pub\\\\Cache\\\\hosted\\\\pub.dev\\\\path_provider_windows-2.1.5\\\\","native_build":false,"dependencies":[]},{"name":"shared_preferences_windows","path":"C:\\\\Users\\\\Oguzhan\\\\AppData\\\\Local\\\\Pub\\\\Cache\\\\hosted\\\\pub.dev\\\\shared_preferences_windows-2.2.0\\\\","native_build":false,"dependencies":["path_provider_windows"]}],"web":[{"name":"flutter_secure_storage_web","path":"C:\\\\Users\\\\Oguzhan\\\\AppData\\\\Local\\\\Pub\\\\Cache\\\\hosted\\\\pub.dev\\\\flutter_secure_storage_web-1.1.1\\\\","dependencies":[]},{"name":"shared_preferences_web","path":"C:\\\\Users\\\\Oguzhan\\\\AppData\\\\Local\\\\Pub\\\\Cache\\\\hosted\\\\pub.dev\\\\shared_preferences_web-2.1.0\\\\","dependencies":[]}]},"dependencyGraph":[{"name":"flutter_secure_storage","dependencies":["flutter_secure_storage_linux","flutter_secure_storage_macos","flutter_secure_storage_web","flutter_secure_storage_windows"]},{"name":"flutter_secure_storage_linux","dependencies":[]},{"name":"flutter_secure_storage_macos","dependencies":[]},{"name":"flutter_secure_storage_web","dependencies":[]},{"name":"flutter_secure_storage_windows","dependencies":[]},{"name":"path_provider","dependencies":["path_provider_android","path_provider_foundation","path_provider_linux","path_provider_windows"]},{"name":"path_provider_android","dependencies":[]},{"name":"path_provider_foundation","dependencies":[]},{"name":"path_provider_linux","dependencies":[]},{"name":"path_provider_windows","dependencies":[]},{"name":"shared_preferences","dependencies":["shared_preferences_android","shared_preferences_foundation","shared_preferences_linux","shared_preferences_web","shared_preferences_windows"]},{"name":"shared_preferences_android","dependencies":[]},{"name":"shared_preferences_foundation","dependencies":[]},{"name":"shared_preferences_linux","dependencies":["path_provider_linux"]},{"name":"shared_preferences_web","dependencies":[]},{"name":"shared_preferences_windows","dependencies":["path_provider_windows"]}],"date_created":"2023-04-26 18:16:17.907544","version":"3.7.11"} \ No newline at end of file diff --git a/.gitignore b/.gitignore index dbef116..5fe43fd 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,8 @@ # Files and directories created by pub .dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies .packages build/ # If you're building an application, you may want to check-in your pubspec.lock @@ -19,3 +21,5 @@ doc/api/ *.js_ *.js.deps *.js.map +*.env +*env.g.dart diff --git a/android/app/build.gradle b/android/app/build.gradle index 4144ac2..923bd76 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -47,7 +47,7 @@ android { applicationId "com.example.chatgpt_flutter_case" // You can update the following values to match your application needs. // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-gradle-build-configuration. - minSdkVersion flutter.minSdkVersion + minSdkVersion 21 targetSdkVersion flutter.targetSdkVersion versionCode flutterVersionCode.toInteger() versionName flutterVersionName diff --git a/lib/core/constants/constants_shelf.dart b/lib/core/constants/constants_shelf.dart new file mode 100644 index 0000000..b148b63 --- /dev/null +++ b/lib/core/constants/constants_shelf.dart @@ -0,0 +1,3 @@ +export 'global_variables.dart'; +export 'shared_preferences_keys.dart'; +export 'string_constants.dart'; diff --git a/lib/core/constants/global_variables.dart b/lib/core/constants/global_variables.dart new file mode 100644 index 0000000..ff0c64d --- /dev/null +++ b/lib/core/constants/global_variables.dart @@ -0,0 +1,11 @@ +import '../core_shelf.dart'; +import '../locator.dart'; + +class GVariables { + static final navigator = NavigationService.instance; + static final context = NavigationService.instance.navigatorKey.currentContext!; + static SPService spService = getIt(); + static final DialogService dialogService = DialogService(); + static final OpenAIService openAIService = OpenAIService(); + static final SecureStorage secureStorage = SecureStorage(); +} diff --git a/lib/core/constants/shared_preferences_keys.dart b/lib/core/constants/shared_preferences_keys.dart new file mode 100644 index 0000000..52a33e3 --- /dev/null +++ b/lib/core/constants/shared_preferences_keys.dart @@ -0,0 +1,3 @@ +class SPKeys { + static const isDark = 'isDark'; +} diff --git a/lib/core/constants/string_constants.dart b/lib/core/constants/string_constants.dart new file mode 100644 index 0000000..56e77ee --- /dev/null +++ b/lib/core/constants/string_constants.dart @@ -0,0 +1,3 @@ +class StringConstants { + static String infoText = 'We’ve trained a model called ChatGPT which interacts in a conversational way.'; +} diff --git a/lib/core/core_shelf.dart b/lib/core/core_shelf.dart new file mode 100644 index 0000000..f035211 --- /dev/null +++ b/lib/core/core_shelf.dart @@ -0,0 +1,5 @@ +export 'constants/constants_shelf.dart'; +export 'providers/providers_shelf.dart'; +export 'theme/theme_shelf.dart'; +export 'services/services_shelf.dart'; +export 'widgets/widgets_shelf.dart'; diff --git a/lib/core/init/helpers/utils.dart b/lib/core/init/helpers/utils.dart new file mode 100644 index 0000000..44e6164 --- /dev/null +++ b/lib/core/init/helpers/utils.dart @@ -0,0 +1,26 @@ +import 'package:flutter/services.dart'; + +import '../../core_shelf.dart'; + +class Utils { + static final Utils _instance = Utils(); + static Utils get instance => _instance; + + void setSystemUi(bool isDark) { + SystemChrome.setSystemUIOverlayStyle( + SystemUiOverlayStyle( + statusBarBrightness: isDark ? Brightness.light : Brightness.dark, + statusBarIconBrightness: isDark ? Brightness.dark : Brightness.light, + systemNavigationBarColor: Color(isDark ? 0xffffff : 0xff121212), + statusBarColor: Color(isDark ? 0xff16151A : 0xffF6F8FA), + systemNavigationBarIconBrightness: isDark ? Brightness.dark : Brightness.light, + ), + ); + } + + Future onThemeChanged(bool isDark, ThemeProvider themeNotifier) async { + Utils.instance.setSystemUi(isDark); + isDark ? themeNotifier.theme = getDarkTheme() : themeNotifier.theme = getLightTheme(); + await GVariables.spService.setIsDark(isDark); + } +} diff --git a/lib/core/locator.dart b/lib/core/locator.dart new file mode 100644 index 0000000..7dc0b90 --- /dev/null +++ b/lib/core/locator.dart @@ -0,0 +1,8 @@ +import 'package:chatgpt_flutter_case/core/services/locale_services/sp_service.dart'; +import 'package:get_it/get_it.dart'; + +GetIt getIt = GetIt.instance; + +void setupLocators() { + getIt.registerLazySingleton(() => SPService()); +} diff --git a/lib/core/models/message_model.dart b/lib/core/models/message_model.dart new file mode 100644 index 0000000..5d9333b --- /dev/null +++ b/lib/core/models/message_model.dart @@ -0,0 +1,52 @@ +class MessageModel { + final String message; + final String sender; + final DateTime time; + + MessageModel({ + required this.message, + required this.sender, + required this.time, + }); + + factory MessageModel.fromJson(Map json) { + return MessageModel( + message: json['message'], + sender: json['sender'], + time: DateTime.parse(json['time']), + ); + } + + Map toJson() { + return { + 'message': message, + 'sender': sender, + 'time': time.toIso8601String(), + }; + } +} + +class ConversationModel { + List? messages; + + ConversationModel({ + this.messages, + }); + + ConversationModel.fromJson(Map json) { + if (json['messages'] != null) { + messages = []; + json['messages'].forEach((v) { + messages?.add(MessageModel.fromJson(v)); + }); + } + } + + Map toJson() { + final data = {}; + if (messages != null) { + data['messages'] = messages?.map((v) => v.toJson()).toList(); + } + return data; + } +} diff --git a/lib/core/providers/chat_provider.dart b/lib/core/providers/chat_provider.dart new file mode 100644 index 0000000..0c0c910 --- /dev/null +++ b/lib/core/providers/chat_provider.dart @@ -0,0 +1,28 @@ +import 'package:chatgpt_flutter_case/core/models/message_model.dart'; +import 'package:flutter/material.dart'; + +class ChatProvider extends ChangeNotifier { + ConversationModel _conversationModel = ConversationModel(messages: []); + ConversationModel get conversationModel => _conversationModel; + + bool _awaitingResponse = false; + bool get awaitingResponse => _awaitingResponse; + + bool _shouldAnimate = true; + bool get shouldAnimate => _shouldAnimate; + + void insertMessage(MessageModel message) { + _conversationModel.messages!.insert(0, message); + notifyListeners(); + } + + void setAwaitingResponse(bool value) { + _awaitingResponse = value; + notifyListeners(); + } + + void setShouldAnimate(bool value) { + _shouldAnimate = value; + notifyListeners(); + } +} diff --git a/lib/core/providers/provider_list.dart b/lib/core/providers/provider_list.dart new file mode 100644 index 0000000..35c111a --- /dev/null +++ b/lib/core/providers/provider_list.dart @@ -0,0 +1,26 @@ +import 'package:chatgpt_flutter_case/core/providers/chat_provider.dart'; +import 'package:chatgpt_flutter_case/core/providers/theme_provider.dart'; +import 'package:provider/provider.dart'; +import 'package:provider/single_child_widget.dart'; + +import '../constants/global_variables.dart'; + +class ApplicationProvider { + static ApplicationProvider? _instance; + static ApplicationProvider? get instance { + _instance ??= ApplicationProvider._init(); + return _instance; + } + + ApplicationProvider._init(); + + List dependItems = [ + ChangeNotifierProvider( + create: (context) => ThemeProvider(), + ), + ChangeNotifierProvider( + create: (context) => ChatProvider(), + ), + Provider.value(value: GVariables.navigator) + ]; +} diff --git a/lib/core/providers/providers_shelf.dart b/lib/core/providers/providers_shelf.dart new file mode 100644 index 0000000..5b0e989 --- /dev/null +++ b/lib/core/providers/providers_shelf.dart @@ -0,0 +1,3 @@ +export 'provider_list.dart'; +export 'theme_provider.dart'; +import 'package:provider/provider.dart'; diff --git a/lib/core/providers/theme_provider.dart b/lib/core/providers/theme_provider.dart new file mode 100644 index 0000000..a077400 --- /dev/null +++ b/lib/core/providers/theme_provider.dart @@ -0,0 +1,44 @@ +import 'package:chatgpt_flutter_case/core/constants/global_variables.dart'; +import 'package:flutter/material.dart'; + +import '../theme/dark_theme.dart'; +import '../theme/light_theme.dart'; + +class ThemeProvider with ChangeNotifier { + ThemeData _themeData = getLightTheme(); + static final ThemeProvider _instance = ThemeProvider(); + static ThemeProvider get instance => _instance; + + ThemeData get theme => _instance._themeData; + + set theme(ThemeData themeData) { + _instance._themeData = themeData; + GVariables.spService.setIsDark(theme == getDarkTheme()); + notifyListeners(); + } + + Future fetchLocale() async { + var isDark = GVariables.spService.getIsDark(); + if (!isDark) { + _instance._themeData = getLightTheme(); + _themeData = getLightTheme(); + } else { + _instance._themeData = getDarkTheme(); + _themeData = getDarkTheme(); + } + notifyListeners(); + } + + changeTheme() { + if (_instance.theme == getDarkTheme()) { + _instance.theme = getLightTheme(); + } else { + _instance.theme = getDarkTheme(); + } + notifyListeners(); + } + + bool isDark() { + return _instance.theme == getDarkTheme(); + } +} diff --git a/lib/core/services/locale_services/dialog_service.dart b/lib/core/services/locale_services/dialog_service.dart new file mode 100644 index 0000000..9436d65 --- /dev/null +++ b/lib/core/services/locale_services/dialog_service.dart @@ -0,0 +1,16 @@ +import 'package:chatgpt_flutter_case/core/widgets/settings_view/settings_view.dart'; +import 'package:flutter/material.dart'; + +class DialogService { + void showBottomSheet( + BuildContext context, + ) { + showModalBottomSheet( + context: context, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10.0), + ), + builder: (context) => const SettingsView(), + ); + } +} diff --git a/lib/core/services/locale_services/locale_service_shelf.dart b/lib/core/services/locale_services/locale_service_shelf.dart new file mode 100644 index 0000000..27bf965 --- /dev/null +++ b/lib/core/services/locale_services/locale_service_shelf.dart @@ -0,0 +1,4 @@ +export 'dialog_service.dart'; +export 'navigation_service.dart'; +export 'sp_service.dart'; +export 'secure_storage.dart'; diff --git a/lib/core/services/locale_services/navigation_service.dart b/lib/core/services/locale_services/navigation_service.dart new file mode 100644 index 0000000..ceb8336 --- /dev/null +++ b/lib/core/services/locale_services/navigation_service.dart @@ -0,0 +1,32 @@ +import 'package:flutter/material.dart'; + +class NavigationService { + static final NavigationService _instance = NavigationService._init(); + static NavigationService get instance => _instance; + + NavigationService._init(); + + GlobalKey navigatorKey = GlobalKey(); + // ignore: prefer_function_declarations_over_variables + final removeAllOldRoutes = (route) => false; + + Future push({ + required Widget route, + }) async { + await navigatorKey.currentState?.push(MaterialPageRoute(builder: (context) => route)); + } + + Future pushAndRemoveUntil({required Widget route}) async { + await navigatorKey.currentState + ?.pushAndRemoveUntil(MaterialPageRoute(builder: (context) => route), (route) => false); + } + + void pop({T? result}) { + return navigatorKey.currentState?.pop(result); + } + + bool canPop() { + final NavigatorState? navigator = Navigator.maybeOf(navigatorKey.currentState!.context); + return navigator != null && navigator.canPop(); + } +} diff --git a/lib/core/services/locale_services/secure_storage.dart b/lib/core/services/locale_services/secure_storage.dart new file mode 100644 index 0000000..faa2ee1 --- /dev/null +++ b/lib/core/services/locale_services/secure_storage.dart @@ -0,0 +1,40 @@ +import 'dart:convert'; + +import 'package:chatgpt_flutter_case/core/models/message_model.dart'; +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; + +class SecureStorage { + FlutterSecureStorage get getStorage { + // ignore: no_leading_underscores_for_local_identifiers + AndroidOptions _getAndroidOptions() => const AndroidOptions( + encryptedSharedPreferences: true, + ); + return FlutterSecureStorage(aOptions: _getAndroidOptions()); + } + + Future saveMessage(ConversationModel messages) async { + final storage = getStorage; + final messageList = await storage.read(key: 'messages'); + if (messageList == null) { + await storage.write(key: 'messages', value: jsonEncode([messages.toJson()])); + } else { + await storage.write(key: 'messages', value: '$messageList,${jsonEncode([messages.toJson()])}'); + } + } + + Future> getMessages() async { + final storage = getStorage; + final messageList = await storage.read(key: 'messages'); + if (messageList == null) { + return []; + } else { + final messageListDecoded = jsonDecode(messageList).cast>().toList(); + return List.generate(messageListDecoded.length, (index) => ConversationModel.fromJson(messageListDecoded[index])); + } + } + + Future clearMessages() async { + final storage = getStorage; + await storage.delete(key: 'messages'); + } +} diff --git a/lib/core/services/locale_services/sp_service.dart b/lib/core/services/locale_services/sp_service.dart new file mode 100644 index 0000000..14b8cfc --- /dev/null +++ b/lib/core/services/locale_services/sp_service.dart @@ -0,0 +1,17 @@ +import 'package:chatgpt_flutter_case/core/constants/shared_preferences_keys.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +class SPService { + late SharedPreferences prefs; + Future init() async { + prefs = await SharedPreferences.getInstance(); + } + + Future setIsDark(bool isDark) async { + return prefs.setBool(SPKeys.isDark, isDark); + } + + bool getIsDark() { + return prefs.getBool(SPKeys.isDark) ?? false; + } +} diff --git a/lib/core/services/network_services/open_ai_service.dart b/lib/core/services/network_services/open_ai_service.dart new file mode 100644 index 0000000..cdd3f41 --- /dev/null +++ b/lib/core/services/network_services/open_ai_service.dart @@ -0,0 +1,19 @@ +import 'package:chatgpt_flutter_case/core/models/message_model.dart'; +import 'package:dart_openai/openai.dart'; + +class OpenAIService { + static const _model = 'gpt-3.5-turbo'; + + Future completeChat(List messages) async { + final chatCompletion = await OpenAI.instance.chat.create( + model: _model, + messages: messages.reversed + .map((e) => OpenAIChatCompletionChoiceMessageModel( + role: e.sender == 'user' ? OpenAIChatMessageRole.user : OpenAIChatMessageRole.assistant, + content: e.message, + )) + .toList(), + ); + return chatCompletion.choices.first.message.content; + } +} diff --git a/lib/core/services/services_shelf.dart b/lib/core/services/services_shelf.dart new file mode 100644 index 0000000..a65758c --- /dev/null +++ b/lib/core/services/services_shelf.dart @@ -0,0 +1,2 @@ +export 'locale_services/locale_service_shelf.dart'; +export 'network_services/open_ai_service.dart'; diff --git a/lib/core/theme/colors.dart b/lib/core/theme/colors.dart new file mode 100644 index 0000000..77997c6 --- /dev/null +++ b/lib/core/theme/colors.dart @@ -0,0 +1,35 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +import '../providers/theme_provider.dart'; + +class MainColors { + static const Color mainGreen = Color(0xFFB6FBFF); + static const Color mainBlack = Color(0xFF000000); + static const Color mainYellow = Color(0xFFFFFFBB); + static const Color mainPurple = Color(0xFFC8B6FF); +} + +const Color bgPrimaryDark = Color(0xFF000000); +const Color bgSecondaryDark = Color(0xff1F1E25); +const Color textPrimaryDark = Color(0xffFFFFFF); +const Color textSecondaryDark = Color(0xffBDBDBD); +const Color chatBubbleDark = Color(0xff1A1A1A); + +const Color bgPrimaryLight = Color(0xffF6F8FA); +const Color bgSecondaryLight = Color(0xffFFFFFF); +const Color textPrimaryLight = Color(0xff0D1012); +const Color textSecondaryLight = Color(0xFFB6B3B3); +const Color chatBubbleLight = Color(0xffE5E5E5); + +ThemeProvider themeProvider(BuildContext context) => Provider.of(context, listen: true); + +Color textPrimary(BuildContext context) => themeProvider(context).isDark() ? textPrimaryDark : textPrimaryLight; + +Color textSecondary(BuildContext context) => themeProvider(context).isDark() ? textSecondaryDark : textSecondaryLight; + +Color bgPrimary(BuildContext context) => themeProvider(context).isDark() ? bgPrimaryDark : bgPrimaryLight; + +Color bgSecondary(BuildContext context) => themeProvider(context).isDark() ? bgSecondaryDark : bgSecondaryLight; + +Color chatBubble(BuildContext context) => themeProvider(context).isDark() ? chatBubbleDark : chatBubbleLight; diff --git a/lib/core/theme/dark_theme.dart b/lib/core/theme/dark_theme.dart new file mode 100644 index 0000000..2af0985 --- /dev/null +++ b/lib/core/theme/dark_theme.dart @@ -0,0 +1,37 @@ +import 'package:chatgpt_flutter_case/core/theme/colors.dart'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; + +final ThemeData _darkTheme = ThemeData( + scaffoldBackgroundColor: MainColors.mainBlack, + fontFamily: GoogleFonts.quicksand().fontFamily, + appBarTheme: const AppBarTheme( + backgroundColor: MainColors.mainBlack, + elevation: 0, + iconTheme: IconThemeData( + color: textPrimaryDark, + ), + ) + // inputDecorationTheme: InputDecorationTheme( + // enabledBorder: OutlineInputBorder( + // borderSide: BorderSide( + // color: borderDark, + // ), + // borderRadius: BorderRadius.all( + // Radius.circular(18), + // ), + // ), + // focusedBorder: OutlineInputBorder( + // borderSide: BorderSide( + // color: borderDark, + // ), + // borderRadius: BorderRadius.all( + // Radius.circular(18), + // ), + // ), + // contentPadding: EdgeInsets.all(15), + // hintStyle: TextStyle(fontSize: 14, color: textSecondaryDark), + // ), + ); + +ThemeData getDarkTheme() => _darkTheme; diff --git a/lib/core/theme/light_theme.dart b/lib/core/theme/light_theme.dart new file mode 100644 index 0000000..2f42af1 --- /dev/null +++ b/lib/core/theme/light_theme.dart @@ -0,0 +1,18 @@ +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; + +import 'colors.dart'; + +final ThemeData _lightTheme = ThemeData( + scaffoldBackgroundColor: const Color(0xffF6F8FA), + fontFamily: GoogleFonts.quicksand().fontFamily, + appBarTheme: const AppBarTheme( + backgroundColor: Color(0xffF6F8FA), + elevation: 0, + iconTheme: IconThemeData( + color: textPrimaryLight, + ), + ), +); + +ThemeData getLightTheme() => _lightTheme; diff --git a/lib/core/theme/theme_shelf.dart b/lib/core/theme/theme_shelf.dart new file mode 100644 index 0000000..967b397 --- /dev/null +++ b/lib/core/theme/theme_shelf.dart @@ -0,0 +1,3 @@ +export 'colors.dart'; +export 'dark_theme.dart'; +export 'light_theme.dart'; diff --git a/lib/core/widgets/custom_appbar.dart b/lib/core/widgets/custom_appbar.dart new file mode 100644 index 0000000..0223406 --- /dev/null +++ b/lib/core/widgets/custom_appbar.dart @@ -0,0 +1,62 @@ +import 'package:flutter/material.dart'; + +import '../core_shelf.dart'; + +class CustomAppbar extends StatelessWidget implements PreferredSizeWidget { + final AppBar appBar; + final List? actions; + final bool showSettings; + const CustomAppbar({ + super.key, + required this.appBar, + this.actions, + this.showSettings = true, + }); + + @override + Widget build(BuildContext context) { + return AppBar( + centerTitle: true, + title: RichText( + text: const TextSpan( + text: 'reload', + style: TextStyle( + color: MainColors.mainGreen, + fontSize: 25, + fontWeight: FontWeight.bold, + ), + children: [ + TextSpan( + text: '.', + style: TextStyle( + color: Colors.white, + )), + TextSpan( + text: 'case', + style: TextStyle( + color: MainColors.mainYellow, + ), + ), + ], + ), + ), + actions: [ + if (actions != null) ...actions!, + if (showSettings) + IconButton( + onPressed: () { + GVariables.dialogService.showBottomSheet( + context, + ); + }, + icon: const Icon( + Icons.settings, + ), + ), + ], + ); + } + + @override + Size get preferredSize => Size.fromHeight(appBar.preferredSize.height); +} diff --git a/lib/core/widgets/flicked_text.dart b/lib/core/widgets/flicked_text.dart new file mode 100644 index 0000000..752edcd --- /dev/null +++ b/lib/core/widgets/flicked_text.dart @@ -0,0 +1,133 @@ +import 'package:flutter/material.dart'; + +class BlinkText extends StatefulWidget { + /// Creates a [BlinkText] widget + const BlinkText(this.data, + {Key? key, + this.style, + this.strutStyle, + this.textAlign, + this.textDirection, + this.locale, + this.softWrap, + this.overflow, + this.textScaleFactor, + this.maxLines, + this.beginColor, + this.endColor, + this.duration, + this.times}) + : super(key: key); + + /// The text to display. + final String data; + final TextStyle? style; + final StrutStyle? strutStyle; + final TextAlign? textAlign; + final TextDirection? textDirection; + final Locale? locale; + final bool? softWrap; + final TextOverflow? overflow; + final double? textScaleFactor; + final int? maxLines; + final Duration? duration; + final int? times; + final Color? beginColor; + final Color? endColor; + + @override + BlinkTextState createState() => BlinkTextState(); +} + +class BlinkTextState extends State with SingleTickerProviderStateMixin { + late AnimationController _controller; + late Animation _colorAnimation; + int _counter = 0; + Duration? duration = Duration(milliseconds: 400); + Color? beginColor = Colors.black; + + @override + void initState() { + super.initState(); + //default duration + if (widget.duration != null) { + duration = widget.duration; + } + + //default beginColor + if (widget.beginColor != null) { + beginColor = widget.beginColor; + } else { + if (widget.style != null && widget.style!.inherit) { + beginColor = widget.style!.color; + } + } + + final endColor = widget.endColor ?? Colors.transparent; + final times = widget.times ?? 0; + + _controller = AnimationController(vsync: this, duration: duration); + _colorAnimation = ColorTween(begin: beginColor, end: endColor) + .animate(CurvedAnimation(parent: _controller, curve: Curves.linear)); + + _controller.addStatusListener((status) { + if (status == AnimationStatus.completed) { + _counter++; + _controller.reverse(); + if (_counter >= times && times > 0) { + _endTween(); + } + } else if (status == AnimationStatus.dismissed) { + _controller.forward(); + } + setState(() {}); + }); + + _controller.forward(); + } + + _endTween() { + Future.delayed(duration!, () { + _controller.stop(); + }); + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + Widget _buildWidget(TextStyle style) { + return Text( + widget.data, + style: style.copyWith(color: _colorAnimation.value), + strutStyle: widget.strutStyle, + textAlign: widget.textAlign, + textDirection: widget.textDirection, + locale: widget.locale, + softWrap: widget.softWrap, + overflow: widget.overflow, + textScaleFactor: 1, + maxLines: widget.maxLines, + ); + } + + @override + Widget build(BuildContext context) { + var defaultTextStyle = DefaultTextStyle.of(context); + var style = defaultTextStyle.style; + + if (widget.style != null) { + style = defaultTextStyle.style.merge(widget.style!); + } + if (MediaQuery.boldTextOverride(context)) style = style.merge(const TextStyle(fontWeight: FontWeight.bold)); + + return AnimatedBuilder( + animation: _controller, + builder: (context, child) { + return _buildWidget(style); + }, + ); + } +} diff --git a/lib/core/widgets/settings_view/components/generate_text_setting.dart b/lib/core/widgets/settings_view/components/generate_text_setting.dart new file mode 100644 index 0000000..d9ce3fa --- /dev/null +++ b/lib/core/widgets/settings_view/components/generate_text_setting.dart @@ -0,0 +1,45 @@ +import 'package:flutter/cupertino.dart'; +import 'package:provider/provider.dart'; +import '../../../core_shelf.dart'; +import '../../../providers/chat_provider.dart'; + +class GenerateText extends StatelessWidget { + const GenerateText({super.key}); + + @override + Widget build(BuildContext context) { + final chatProvider = Provider.of(context, listen: true); + return Container( + height: 65, + decoration: BoxDecoration( + color: bgSecondary(context), + borderRadius: BorderRadius.circular(3), + border: Border.all( + color: textSecondary(context), + width: 0.5, + ), + ), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 10), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + 'Generate Text Animation', + style: TextStyle( + color: textPrimary(context), + fontWeight: FontWeight.w500, + fontSize: 13, + ), + ), + CupertinoSwitch( + value: chatProvider.shouldAnimate, + onChanged: (a) { + chatProvider.setShouldAnimate(a); + }), + ], + ), + ), + ); + } +} diff --git a/lib/core/widgets/settings_view/components/theme_changer.dart b/lib/core/widgets/settings_view/components/theme_changer.dart new file mode 100644 index 0000000..2452dc0 --- /dev/null +++ b/lib/core/widgets/settings_view/components/theme_changer.dart @@ -0,0 +1,115 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import '../../../core_shelf.dart'; +import '../../../init/helpers/utils.dart'; + +class UserSettingsThemeChanger extends StatelessWidget { + const UserSettingsThemeChanger({ + Key? key, + }) : super(key: key); + + @override + Widget build(BuildContext context) { + final themeNotifier = Provider.of(context, listen: false); + return Container( + decoration: BoxDecoration( + color: bgSecondary(context), + borderRadius: BorderRadius.circular(3), + border: Border.all( + color: textSecondary(context), + width: 0.5, + ), + ), + height: 65, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 10.0), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + 'Theme', + style: TextStyle( + color: textPrimary(context), + fontWeight: FontWeight.w500, + fontSize: 13, + ), + ), + Container( + width: 60, + height: 30, + decoration: BoxDecoration( + color: bgSecondary(context), + borderRadius: BorderRadius.circular(4), + border: Border.all( + color: textSecondary(context), + width: 0.5, + ), + ), + child: Row( + children: [ + Expanded( + child: InkWell( + onTap: () { + Utils.instance.onThemeChanged(false, themeNotifier); + }, + child: Container( + decoration: BoxDecoration( + color: themeNotifier.theme == getLightTheme() ? Colors.blue : bgSecondary(context), + borderRadius: const BorderRadius.horizontal( + left: Radius.circular(4), + ), + border: Border.all( + color: textSecondary(context), + width: 0.5, + ), + ), + child: Center( + child: Icon( + Icons.light_mode, + color: themeNotifier.theme == getLightTheme() ? Colors.amber : textSecondary(context), + size: 16, + ), + ), + ), + ), + ), + Container( + width: 0.5, + height: 30, + color: textSecondary(context), + ), + Expanded( + child: InkWell( + onTap: () { + Utils.instance.onThemeChanged(true, themeNotifier); + }, + child: Container( + decoration: BoxDecoration( + color: themeNotifier.theme == getDarkTheme() ? Colors.red : bgSecondary(context), + borderRadius: const BorderRadius.horizontal( + right: Radius.circular(4), + ), + border: Border.all( + color: textSecondary(context), + width: 0.5, + ), + ), + child: Center( + child: Icon( + Icons.dark_mode, + color: themeNotifier.theme == getDarkTheme() ? Colors.amber : textSecondary(context), + size: 16, + ), + ), + ), + ), + ), + ], + ), + ), + ], + ), + ), + ); + } +} diff --git a/lib/core/widgets/settings_view/settings_view.dart b/lib/core/widgets/settings_view/settings_view.dart new file mode 100644 index 0000000..85b52fd --- /dev/null +++ b/lib/core/widgets/settings_view/settings_view.dart @@ -0,0 +1,49 @@ +import 'package:chatgpt_flutter_case/core/widgets/settings_view/components/generate_text_setting.dart'; +import 'package:chatgpt_flutter_case/core/widgets/settings_view/components/theme_changer.dart'; +import 'package:flutter/material.dart'; + +import '../../core_shelf.dart'; + +class SettingsView extends StatelessWidget { + const SettingsView({super.key}); + + @override + Widget build(BuildContext context) { + var size = MediaQuery.of(context).size; + + return Container( + padding: const EdgeInsets.all( + 12, + ), + decoration: BoxDecoration( + color: bgPrimary(context), + borderRadius: const BorderRadius.only( + topLeft: Radius.circular(10), + topRight: Radius.circular(10), + ), + ), + width: size.width, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'Settings', + style: TextStyle( + color: textPrimary(context), + fontSize: 20, + fontWeight: FontWeight.w500, + ), + ), + SizedBox( + height: size.height * .02, + ), + const UserSettingsThemeChanger(), + SizedBox( + height: size.height * .02, + ), + const GenerateText(), + ], + ), + ); + } +} diff --git a/lib/core/widgets/widgets_shelf.dart b/lib/core/widgets/widgets_shelf.dart new file mode 100644 index 0000000..f112116 --- /dev/null +++ b/lib/core/widgets/widgets_shelf.dart @@ -0,0 +1 @@ +export 'flicked_text.dart'; diff --git a/lib/env/env.dart b/lib/env/env.dart new file mode 100644 index 0000000..789d087 --- /dev/null +++ b/lib/env/env.dart @@ -0,0 +1,9 @@ +import 'package:envied/envied.dart'; + +part 'env.g.dart'; + +@Envied(path: '.env') +abstract class Env { + @EnviedField(varName: 'API_KEY', obfuscate: true) + static final openAIApiKey = _Env.openAIApiKey; +} diff --git a/lib/main.dart b/lib/main.dart index dda5554..fcef46a 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,125 +1,49 @@ +import 'package:chatgpt_flutter_case/core/constants/constants_shelf.dart'; +import 'package:chatgpt_flutter_case/core/services/locale_services/navigation_service.dart'; +import 'package:chatgpt_flutter_case/env/env.dart'; +import 'package:chatgpt_flutter_case/views/splash_screen.dart'; +import 'package:dart_openai/openai.dart'; import 'package:flutter/material.dart'; - -void main() { - runApp(const MyApp()); +import 'package:flutter/services.dart'; +import 'package:provider/provider.dart'; +import 'core/core_shelf.dart' as core; +import 'core/locator.dart'; + +void main() async { + WidgetsFlutterBinding.ensureInitialized(); + setupLocators(); + OpenAI.apiKey = Env.openAIApiKey; + await GVariables.spService.init(); + var themeProvider = core.ThemeProvider.instance; + await themeProvider.fetchLocale(); + await SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersive); + runApp(MultiProvider( + providers: [...?core.ApplicationProvider.instance?.dependItems], + child: const MyApp(), + )); } -class MyApp extends StatelessWidget { +class MyApp extends StatefulWidget { const MyApp({super.key}); - // This widget is the root of your application. @override - Widget build(BuildContext context) { - return MaterialApp( - title: 'Flutter Demo', - theme: ThemeData( - // This is the theme of your application. - // - // TRY THIS: Try running your application with "flutter run". You'll see - // the application has a blue toolbar. Then, without quitting the app, - // try changing the seedColor in the colorScheme below to Colors.green - // and then invoke "hot reload" (save your changes or press the "hot - // reload" button in a Flutter-supported IDE, or press "r" if you used - // the command line to start the app). - // - // Notice that the counter didn't reset back to zero; the application - // state is not lost during the reload. To reset the state, use hot - // restart instead. - // - // This works for code too, not just values: Most code changes can be - // tested with just a hot reload. - colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), - useMaterial3: true, - ), - home: const MyHomePage(title: 'Flutter Demo Home Page'), - ); - } + State createState() => _MyAppState(); } -class MyHomePage extends StatefulWidget { - const MyHomePage({super.key, required this.title}); - - // This widget is the home page of your application. It is stateful, meaning - // that it has a State object (defined below) that contains fields that affect - // how it looks. - - // This class is the configuration for the state. It holds the values (in this - // case the title) provided by the parent (in this case the App widget) and - // used by the build method of the State. Fields in a Widget subclass are - // always marked "final". - - final String title; - - @override - State createState() => _MyHomePageState(); -} - -class _MyHomePageState extends State { - int _counter = 0; - - void _incrementCounter() { - setState(() { - // This call to setState tells the Flutter framework that something has - // changed in this State, which causes it to rerun the build method below - // so that the display can reflect the updated values. If we changed - // _counter without calling setState(), then the build method would not be - // called again, and so nothing would appear to happen. - _counter++; - }); - } - +class _MyAppState extends State { @override Widget build(BuildContext context) { - // This method is rerun every time setState is called, for instance as done - // by the _incrementCounter method above. - // - // The Flutter framework has been optimized to make rerunning build methods - // fast, so that you can just rebuild anything that needs updating rather - // than having to individually change instances of widgets. - return Scaffold( - appBar: AppBar( - // TRY THIS: Try changing the color here to a specific color (to - // Colors.amber, perhaps?) and trigger a hot reload to see the AppBar - // change color while the other colors stay the same. - backgroundColor: Theme.of(context).colorScheme.inversePrimary, - // Here we take the value from the MyHomePage object that was created by - // the App.build method, and use it to set our appbar title. - title: Text(widget.title), - ), - body: Center( - // Center is a layout widget. It takes a single child and positions it - // in the middle of the parent. - child: Column( - // Column is also a layout widget. It takes a list of children and - // arranges them vertically. By default, it sizes itself to fit its - // children horizontally, and tries to be as tall as its parent. - // - // Column has various properties to control how it sizes itself and - // how it positions its children. Here we use mainAxisAlignment to - // center the children vertically; the main axis here is the vertical - // axis because Columns are vertical (the cross axis would be - // horizontal). - // - // TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint" - // action in the IDE, or press "p" in the console), to see the - // wireframe for each widget. - mainAxisAlignment: MainAxisAlignment.center, - children: [ - const Text( - 'You have pushed the button this many times:', - ), - Text( - '$_counter', - style: Theme.of(context).textTheme.headlineMedium, - ), - ], + return Consumer(builder: (context, themeProvider, child) { + return MediaQuery( + data: MediaQueryData(), + child: MaterialApp( + theme: themeProvider.theme, + debugShowCheckedModeBanner: false, + title: 'ChatGPT Client', + navigatorKey: NavigationService.instance.navigatorKey, + home: const SplashScreen(), ), - ), - floatingActionButton: FloatingActionButton( - onPressed: _incrementCounter, - tooltip: 'Increment', - child: const Icon(Icons.add), - ), // This trailing comma makes auto-formatting nicer for build methods. - ); + ); + }); } } diff --git a/lib/view/chat_screen/components/chat_bubble.dart b/lib/view/chat_screen/components/chat_bubble.dart new file mode 100644 index 0000000..6a4a571 --- /dev/null +++ b/lib/view/chat_screen/components/chat_bubble.dart @@ -0,0 +1,91 @@ +import 'package:chatgpt_flutter_case/core/models/message_model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import '../../../core/core_shelf.dart'; + +class ChatBubble extends StatelessWidget { + final MessageModel message; + + const ChatBubble({ + super.key, + required this.message, + }); + + @override + Widget build(BuildContext context) { + var size = MediaQuery.of(context).size; + return Padding( + padding: const EdgeInsets.all(8.0), + child: Container( + width: size.width * .95, + decoration: BoxDecoration( + color: message.sender == 'user' ? bgPrimary(context) : chatBubble(context), + borderRadius: BorderRadius.circular(10), + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.all(8.0), + child: Column( + children: [ + Container( + width: 40, + height: 40, + decoration: BoxDecoration( + color: message.sender == 'user' ? MainColors.mainPurple : MainColors.mainGreen, + shape: BoxShape.circle, + ), + ), + ], + ), + ), + Container( + width: size.width * .75, + margin: const EdgeInsets.all(8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: Text( + message.sender == 'user' ? "You" : "Chatbot", + style: TextStyle( + color: message.sender != 'user' ? MainColors.mainGreen : Colors.grey, + fontSize: 14, + fontWeight: FontWeight.bold, + ), + ), + ), + Text( + message.message, + style: TextStyle( + color: textPrimary(context), + fontSize: 14, + fontWeight: FontWeight.w700, + ), + ), + Align( + alignment: Alignment.centerRight, + child: InkWell( + onTap: () { + Clipboard.setData(ClipboardData(text: message.message)); + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text("Copied to clipboard"), + duration: Duration(milliseconds: 500), + ), + ); + }, + child: Icon(Icons.content_copy, color: textPrimary(context), size: 20)), + ) + ], + ), + ), + ], + ), + ), + ); + } +} diff --git a/lib/view/splash_screen.dart b/lib/view/splash_screen.dart new file mode 100644 index 0000000..cfc6435 --- /dev/null +++ b/lib/view/splash_screen.dart @@ -0,0 +1,85 @@ +import 'package:animated_text_kit/animated_text_kit.dart'; +import 'package:flutter/material.dart'; +import '../core/core_shelf.dart'; +import '../views/main_screen/main_screen.dart'; + +class SplashScreen extends StatefulWidget { + const SplashScreen({super.key}); + + @override + State createState() => _SplashScreenState(); +} + +class _SplashScreenState extends State { + bool isFinished = false; + @override + Widget build(BuildContext context) { + var size = MediaQuery.of(context).size; + return Scaffold( + body: InkWell( + onTap: () { + if (isFinished) { + GVariables.navigator.pushAndRemoveUntil(route: const MainScreen()); + } + }, + child: Center( + child: SizedBox( + width: size.width * .8, + height: 60, + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + AnimatedTextKit( + totalRepeatCount: 1, + displayFullTextOnTap: true, + onFinished: () { + setState(() { + isFinished = true; + }); + }, + animatedTexts: [ + TypewriterAnimatedText( + 'reload', + cursor: '', + speed: const Duration(milliseconds: 70), + textStyle: const TextStyle( + color: MainColors.mainGreen, + fontSize: 40, + fontWeight: FontWeight.bold, + ), + ), + ], + ), + const BlinkText( + '.', + times: 2, + style: TextStyle( + color: MainColors.mainYellow, + fontSize: 40, + fontWeight: FontWeight.bold, + ), + ), + AnimatedTextKit( + totalRepeatCount: 1, + displayFullTextOnTap: true, + animatedTexts: [ + TypewriterAnimatedText( + 'case', + cursor: '', + speed: const Duration(milliseconds: 70), + textStyle: const TextStyle( + color: Colors.white, + fontSize: 40, + fontWeight: FontWeight.bold, + ), + ), + ], + ), + ], + ), + ), + ), + ), + ); + } +} diff --git a/lib/view_models.dart/chat_screen_view_model.dart b/lib/view_models.dart/chat_screen_view_model.dart new file mode 100644 index 0000000..e61f6d5 --- /dev/null +++ b/lib/view_models.dart/chat_screen_view_model.dart @@ -0,0 +1,29 @@ +import 'package:chatgpt_flutter_case/core/core_shelf.dart'; +import 'package:chatgpt_flutter_case/core/models/message_model.dart'; +import 'package:chatgpt_flutter_case/core/providers/chat_provider.dart'; +import 'package:flutter/material.dart'; + +class ChatScreenViewModel { + var messageController = TextEditingController(); + + Future onSubmitted({required ChatProvider chatProvider}) async { + chatProvider.insertMessage(MessageModel(message: messageController.text, sender: 'user', time: DateTime.now())); + messageController.clear(); + chatProvider.setAwaitingResponse(true); + + try { + final response = await GVariables.openAIService.completeChat(chatProvider.conversationModel.messages!); + chatProvider.insertMessage(MessageModel(message: response, sender: 'assistant', time: DateTime.now())); + chatProvider.setAwaitingResponse(false); + } catch (e) { + ScaffoldMessenger.of(GVariables.context).showSnackBar( + const SnackBar(content: Text('An error occurred. Please try again.')), + ); + chatProvider.setAwaitingResponse(false); + } + } + + Future saveMessages({required ChatProvider chatProvider}) async { + await GVariables.secureStorage.saveMessage(chatProvider.conversationModel); + } +} diff --git a/lib/views/chat_history_screen/chat_history.dart b/lib/views/chat_history_screen/chat_history.dart new file mode 100644 index 0000000..7325ab0 --- /dev/null +++ b/lib/views/chat_history_screen/chat_history.dart @@ -0,0 +1,37 @@ +import 'package:chatgpt_flutter_case/core/constants/constants_shelf.dart'; +import 'package:flutter/material.dart'; + +import '../../core/widgets/custom_appbar.dart'; + +class ChatHistory extends StatelessWidget { + const ChatHistory({super.key}); + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: CustomAppbar(appBar: AppBar()), + body: FutureBuilder( + future: GVariables.secureStorage.getMessages(), + builder: (context, snapshot) { + if (!snapshot.hasData) { + return const Center( + child: CircularProgressIndicator(), + ); + } else if (snapshot.hasError) { + return const Center( + child: Text('Error', style: TextStyle(color: Colors.red)), + ); + } + + return ListView.builder( + itemCount: snapshot.data!.length, + itemBuilder: (context, index) { + return ListTile( + title: + Text(snapshot.data![index].messages!.last.message, style: const TextStyle(color: Colors.white)), + ); + }, + ); + })); + } +} diff --git a/lib/views/chat_screen/chat_screen.dart b/lib/views/chat_screen/chat_screen.dart new file mode 100644 index 0000000..48e2649 --- /dev/null +++ b/lib/views/chat_screen/chat_screen.dart @@ -0,0 +1,82 @@ +import 'package:chatgpt_flutter_case/core/core_shelf.dart'; +import 'package:chatgpt_flutter_case/core/providers/chat_provider.dart'; +import 'package:chatgpt_flutter_case/core/widgets/custom_appbar.dart'; +import 'package:chatgpt_flutter_case/view_models.dart/chat_screen_view_model.dart'; +import 'package:chatgpt_flutter_case/views/chat_screen/components/chat_bubble.dart'; +import 'package:chatgpt_flutter_case/views/chat_screen/components/custom_text_field.dart'; +import 'package:flutter/material.dart'; +import 'package:progress_indicators/progress_indicators.dart'; +import 'package:provider/provider.dart'; + +class ChatScreen extends StatefulWidget { + ChatScreenViewModel viewModel; + ChatScreen({super.key, required this.viewModel}); + + @override + State createState() => _ChatScreenState(); +} + +class _ChatScreenState extends State { + @override + Widget build(BuildContext context) { + var size = MediaQuery.of(context).size; + return Consumer(builder: (context, ChatProvider chatProvider, child) { + return Scaffold( + appBar: CustomAppbar( + appBar: AppBar(), + // TODO: Save messages to local storage + // actions: [ + // IconButton( + // onPressed: () { + // // GVariables.secureStorage.clearMessages(); + // widget.viewModel.saveMessages(chatProvider: chatProvider); + // }, + // icon: const Icon( + // Icons.save, + // ), + // ), + // ], + ), + body: SizedBox( + height: size.height, + width: size.width, + child: SingleChildScrollView( + child: Column( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + SizedBox( + height: size.height * .84, + child: ListView( + reverse: true, + children: [ + if (chatProvider.awaitingResponse) + JumpingDotsProgressIndicator( + fontSize: 35, + color: textPrimary(context), + ), + ...List.generate( + chatProvider.conversationModel.messages!.length, + (index) => ChatBubble( + message: chatProvider.conversationModel.messages![index], + isLast: index == 0, + chatProvider: chatProvider, + ), + ), + ], + ), + ), + Padding( + padding: const EdgeInsets.all(8.0), + child: CustomTextField( + onPressed: () => widget.viewModel.onSubmitted(chatProvider: chatProvider), + controller: widget.viewModel.messageController, + ), + ), + ], + ), + ), + ), + ); + }); + } +} diff --git a/lib/views/chat_screen/components/chat_bubble.dart b/lib/views/chat_screen/components/chat_bubble.dart new file mode 100644 index 0000000..b37370c --- /dev/null +++ b/lib/views/chat_screen/components/chat_bubble.dart @@ -0,0 +1,112 @@ +import 'package:animated_text_kit/animated_text_kit.dart'; +import 'package:chatgpt_flutter_case/core/models/message_model.dart'; +import 'package:chatgpt_flutter_case/core/providers/chat_provider.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import '../../../core/core_shelf.dart'; + +class ChatBubble extends StatelessWidget { + final MessageModel message; + final bool isLast; + final ChatProvider chatProvider; + const ChatBubble({ + super.key, + required this.message, + required this.isLast, + required this.chatProvider, + }); + + @override + Widget build(BuildContext context) { + var size = MediaQuery.of(context).size; + return Padding( + padding: const EdgeInsets.all(8.0), + child: Container( + width: size.width * .95, + decoration: BoxDecoration( + color: message.sender == 'user' ? bgPrimary(context) : chatBubble(context), + borderRadius: BorderRadius.circular(10), + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.all(8.0), + child: Column( + children: [ + Container( + width: 40, + height: 40, + decoration: BoxDecoration( + color: message.sender == 'user' ? MainColors.mainPurple : MainColors.mainGreen, + shape: BoxShape.circle, + ), + ), + ], + ), + ), + Container( + width: size.width * .75, + margin: const EdgeInsets.all(8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: Text( + message.sender == 'user' ? "You" : "Chatbot", + style: TextStyle( + color: message.sender != 'user' ? MainColors.mainGreen : Colors.grey, + fontSize: 14, + fontWeight: FontWeight.bold, + ), + ), + ), + (isLast && message.sender == 'assistant' && chatProvider.shouldAnimate) + ? AnimatedTextKit( + isRepeatingAnimation: false, + repeatForever: false, + displayFullTextOnTap: true, + totalRepeatCount: 1, + animatedTexts: [ + TyperAnimatedText( + message.message.trim(), + textStyle: TextStyle( + color: textPrimary(context), + fontSize: 14, + fontWeight: FontWeight.w700, + ), + ), + ]) + : Text( + message.message, + style: TextStyle( + color: textPrimary(context), + fontSize: 14, + fontWeight: FontWeight.w700, + ), + ), + Align( + alignment: Alignment.centerRight, + child: InkWell( + onTap: () { + Clipboard.setData(ClipboardData(text: message.message)); + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text("Copied to clipboard"), + duration: Duration(milliseconds: 500), + ), + ); + }, + child: Icon(Icons.content_copy, color: textPrimary(context), size: 20)), + ) + ], + ), + ), + ], + ), + ), + ); + } +} diff --git a/lib/views/chat_screen/components/custom_text_field.dart b/lib/views/chat_screen/components/custom_text_field.dart new file mode 100644 index 0000000..595ad5c --- /dev/null +++ b/lib/views/chat_screen/components/custom_text_field.dart @@ -0,0 +1,54 @@ +import 'package:chatgpt_flutter_case/core/theme/theme_shelf.dart'; +import 'package:flutter/material.dart'; + +class CustomTextField extends StatelessWidget { + final TextEditingController controller; + Function()? onPressed; + CustomTextField({super.key, required this.controller, required this.onPressed}); + @override + Widget build(BuildContext context) { + var size = MediaQuery.of(context).size; + return SizedBox( + width: size.width * .9, + child: TextField( + controller: controller, + style: TextStyle(color: textPrimary(context)), + decoration: InputDecoration( + suffixIcon: Padding( + padding: const EdgeInsets.only(right: 8), + child: CircleAvatar( + backgroundColor: textPrimary(context), + child: IconButton( + onPressed: onPressed, + icon: Icon( + Icons.send, + color: bgPrimary(context), + )), + ), + ), + border: const OutlineInputBorder( + borderSide: BorderSide.none, + borderRadius: BorderRadius.all( + Radius.circular(30), + ), + ), + focusedBorder: const OutlineInputBorder( + borderSide: BorderSide(color: MainColors.mainGreen, width: 1), + borderRadius: BorderRadius.all( + Radius.circular(30), + ), + ), + enabledBorder: const OutlineInputBorder( + borderSide: BorderSide.none, + borderRadius: BorderRadius.all( + Radius.circular(30), + ), + ), + filled: true, + hintStyle: TextStyle(color: Colors.grey[700]), + hintText: "Message", + fillColor: const Color(0xff262626)), + ), + ); + } +} diff --git a/lib/views/main_screen/components/cont_button.dart b/lib/views/main_screen/components/cont_button.dart new file mode 100644 index 0000000..197283e --- /dev/null +++ b/lib/views/main_screen/components/cont_button.dart @@ -0,0 +1,31 @@ +import 'package:flutter/material.dart'; + +class MainScreenButton extends StatelessWidget { + const MainScreenButton({super.key, required this.onTap}); + final Function() onTap; + + @override + Widget build(BuildContext context) { + var size = MediaQuery.of(context).size; + return InkWell( + onTap: onTap, + child: Container( + width: size.width * .8, + height: 60, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(22), + ), + child: const Center( + child: Text( + 'Continue', + style: TextStyle( + fontSize: 15, + fontWeight: FontWeight.w600, + ), + ), + ), + ), + ); + } +} diff --git a/lib/views/main_screen/components/header.dart b/lib/views/main_screen/components/header.dart new file mode 100644 index 0000000..77c9dd2 --- /dev/null +++ b/lib/views/main_screen/components/header.dart @@ -0,0 +1,40 @@ +import 'package:chatgpt_flutter_case/core/theme/colors.dart'; +import 'package:flutter/material.dart'; + +class Header extends StatelessWidget { + const Header({super.key}); + + @override + Widget build(BuildContext context) { + var size = MediaQuery.of(context).size; + return SizedBox( + width: size.width * .8, + height: 60, + child: Center( + child: RichText( + text: const TextSpan( + text: 'reload', + style: TextStyle( + color: MainColors.mainGreen, + fontSize: 25, + fontWeight: FontWeight.bold, + ), + children: [ + TextSpan( + text: '.', + style: TextStyle( + color: Colors.white, + )), + TextSpan( + text: 'case', + style: TextStyle( + color: MainColors.mainYellow, + ), + ), + ], + ), + ), + ), + ); + } +} diff --git a/lib/views/main_screen/components/info_text.dart b/lib/views/main_screen/components/info_text.dart new file mode 100644 index 0000000..f6ef086 --- /dev/null +++ b/lib/views/main_screen/components/info_text.dart @@ -0,0 +1,19 @@ +import 'package:chatgpt_flutter_case/core/theme/colors.dart'; +import 'package:flutter/material.dart'; + +class InfoText extends StatelessWidget { + const InfoText({super.key}); + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.all(16.0), + child: Text('We’ve trained a model called ChatGPT which interacts in a conversational way.', + textAlign: TextAlign.center, + style: TextStyle( + fontSize: 15, + color: textPrimary(context), + )), + ); + } +} diff --git a/lib/views/main_screen/components/m_components_shelf.dart b/lib/views/main_screen/components/m_components_shelf.dart new file mode 100644 index 0000000..4e6cab3 --- /dev/null +++ b/lib/views/main_screen/components/m_components_shelf.dart @@ -0,0 +1,4 @@ +export 'cont_button.dart'; +export 'header.dart'; +export 'info_text.dart'; +export 'name_text.dart'; diff --git a/lib/views/main_screen/components/name_text.dart b/lib/views/main_screen/components/name_text.dart new file mode 100644 index 0000000..d3a9f7e --- /dev/null +++ b/lib/views/main_screen/components/name_text.dart @@ -0,0 +1,31 @@ +import 'package:flutter/material.dart'; +import '../../../core/theme/colors.dart'; + +class NameText extends StatelessWidget { + const NameText({super.key}); + + @override + Widget build(BuildContext context) { + return RichText( + textAlign: TextAlign.center, + text: const TextSpan( + text: 'AI', + style: TextStyle( + color: MainColors.mainGreen, + fontSize: 52, + fontWeight: FontWeight.bold, + ), + children: [ + TextSpan( + text: ' Chatbot', + style: TextStyle( + color: MainColors.mainYellow, + fontSize: 52, + fontWeight: FontWeight.bold, + ), + ), + ], + ), + ); + } +} diff --git a/lib/views/main_screen/main_screen.dart b/lib/views/main_screen/main_screen.dart new file mode 100644 index 0000000..e106b4a --- /dev/null +++ b/lib/views/main_screen/main_screen.dart @@ -0,0 +1,71 @@ +import 'package:chatgpt_flutter_case/core/constants/constants_shelf.dart'; +import 'package:chatgpt_flutter_case/core/widgets/custom_appbar.dart'; +import 'package:chatgpt_flutter_case/view_models.dart/chat_screen_view_model.dart'; +import 'package:chatgpt_flutter_case/views/chat_screen/chat_screen.dart'; +import 'package:flutter/material.dart'; +import 'components/m_components_shelf.dart'; + +class MainScreen extends StatefulWidget { + const MainScreen({super.key}); + + @override + State createState() => _MainScreenState(); +} + +class _MainScreenState extends State { + final viewModel = ChatScreenViewModel(); + @override + Widget build(BuildContext context) { + var size = MediaQuery.of(context).size; + return Scaffold( + appBar: CustomAppbar(appBar: AppBar()), + body: Stack( + children: [ + Center( + child: Padding( + padding: const EdgeInsets.all(8.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + // const Header(), + SizedBox( + height: size.height * .25, + ), + const NameText(), + const InfoText(), + const Spacer(), + MainScreenButton( + onTap: () { + GVariables.navigator.pushAndRemoveUntil( + route: ChatScreen( + viewModel: viewModel, + )); + }, + ), + SizedBox( + height: size.height * .02, + ) + ], + ), + ), + ), + // Positioned( + // right: 8, + // top: 30, + // child: InkWell( + // onTap: () { + // GVariables.dialogService.showBottomSheet( + // context, + // ); + // }, + // child: Icon( + // FontAwesome5.user_circle, + // color: textPrimary(context), + // ), + // ), + // ), + ], + ), + ); + } +} diff --git a/lib/views/splash_screen.dart b/lib/views/splash_screen.dart new file mode 100644 index 0000000..144f606 --- /dev/null +++ b/lib/views/splash_screen.dart @@ -0,0 +1,87 @@ +import 'package:animated_text_kit/animated_text_kit.dart'; +import 'package:flutter/material.dart'; +import '../core/core_shelf.dart'; +import 'main_screen/main_screen.dart'; + +class SplashScreen extends StatefulWidget { + const SplashScreen({super.key}); + + @override + State createState() => _SplashScreenState(); +} + +class _SplashScreenState extends State { + bool isFinished = false; + + @override + void initState() { + super.initState(); + Future.delayed(const Duration(milliseconds: 2400), () { + GVariables.navigator.pushAndRemoveUntil(route: const MainScreen()); + }); + } + + @override + Widget build(BuildContext context) { + var size = MediaQuery.of(context).size; + return Scaffold( + body: Center( + child: SizedBox( + width: size.width * .8, + height: 60, + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + AnimatedTextKit( + totalRepeatCount: 1, + displayFullTextOnTap: true, + onFinished: () { + setState(() { + isFinished = true; + }); + }, + animatedTexts: [ + TypewriterAnimatedText( + 'reload', + cursor: '', + speed: const Duration(milliseconds: 70), + textStyle: const TextStyle( + color: MainColors.mainGreen, + fontSize: 40, + fontWeight: FontWeight.bold, + ), + ), + ], + ), + const BlinkText( + '.', + times: 2, + style: TextStyle( + color: MainColors.mainYellow, + fontSize: 40, + fontWeight: FontWeight.bold, + ), + ), + AnimatedTextKit( + totalRepeatCount: 1, + displayFullTextOnTap: true, + animatedTexts: [ + TypewriterAnimatedText( + 'case', + cursor: '', + speed: const Duration(milliseconds: 70), + textStyle: const TextStyle( + color: Colors.white, + fontSize: 40, + fontWeight: FontWeight.bold, + ), + ), + ], + ), + ], + ), + ), + ), + ); + } +} diff --git a/linux/flutter/generated_plugin_registrant.cc b/linux/flutter/generated_plugin_registrant.cc index e71a16d..d0e7f79 100644 --- a/linux/flutter/generated_plugin_registrant.cc +++ b/linux/flutter/generated_plugin_registrant.cc @@ -6,6 +6,10 @@ #include "generated_plugin_registrant.h" +#include void fl_register_plugins(FlPluginRegistry* registry) { + g_autoptr(FlPluginRegistrar) flutter_secure_storage_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "FlutterSecureStorageLinuxPlugin"); + flutter_secure_storage_linux_plugin_register_with_registrar(flutter_secure_storage_linux_registrar); } diff --git a/linux/flutter/generated_plugins.cmake b/linux/flutter/generated_plugins.cmake index 2e1de87..b29e9ba 100644 --- a/linux/flutter/generated_plugins.cmake +++ b/linux/flutter/generated_plugins.cmake @@ -3,6 +3,7 @@ # list(APPEND FLUTTER_PLUGIN_LIST + flutter_secure_storage_linux ) list(APPEND FLUTTER_FFI_PLUGIN_LIST diff --git a/macos/Flutter/GeneratedPluginRegistrant.swift b/macos/Flutter/GeneratedPluginRegistrant.swift index cccf817..37af1fe 100644 --- a/macos/Flutter/GeneratedPluginRegistrant.swift +++ b/macos/Flutter/GeneratedPluginRegistrant.swift @@ -5,6 +5,12 @@ import FlutterMacOS import Foundation +import flutter_secure_storage_macos +import path_provider_foundation +import shared_preferences_foundation func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { + FlutterSecureStoragePlugin.register(with: registry.registrar(forPlugin: "FlutterSecureStoragePlugin")) + PathProviderPlugin.register(with: registry.registrar(forPlugin: "PathProviderPlugin")) + SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin")) } diff --git a/pubspec.yaml b/pubspec.yaml index e7fa760..5d16b11 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -19,7 +19,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev version: 1.0.0+1 environment: - sdk: '>=3.0.0-322.0.dev <4.0.0' + sdk: '>=2.19.0 <3.0.0' # Dependencies specify other packages that your package needs in order to work. # To automatically upgrade your package dependencies to the latest versions @@ -35,6 +35,16 @@ dependencies: # The following adds the Cupertino Icons font to your application. # Use with the CupertinoIcons class for iOS style icons. cupertino_icons: ^1.0.2 + animated_text_kit: ^4.2.2 + provider: ^6.0.5 + shared_preferences: ^2.1.0 + get_it: ^7.2.0 + fluttericon: ^2.0.0 + google_fonts: ^4.0.3 + dart_openai: ^1.9.1 + progress_indicators: ^1.0.0 + flutter_secure_storage: ^8.0.0 + envied: ^0.3.0 dev_dependencies: flutter_test: @@ -46,6 +56,8 @@ dev_dependencies: # package. See that file for information about deactivating specific lint # rules and activating additional ones. flutter_lints: ^2.0.0 + envied_generator: ^0.3.0 + build_runner: ^2.3.3 # For information on the generic Dart part of this file, see the # following page: https://dart.dev/tools/pub/pubspec diff --git a/test/widget_test.dart b/test/widget_test.dart index 42dc1b8..9322cd7 100644 --- a/test/widget_test.dart +++ b/test/widget_test.dart @@ -8,12 +8,10 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:chatgpt_flutter_case/main.dart'; - void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. - await tester.pumpWidget(const MyApp()); + // await tester.pumpWidget(const MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); diff --git a/windows/flutter/generated_plugin_registrant.cc b/windows/flutter/generated_plugin_registrant.cc index 8b6d468..0c50753 100644 --- a/windows/flutter/generated_plugin_registrant.cc +++ b/windows/flutter/generated_plugin_registrant.cc @@ -6,6 +6,9 @@ #include "generated_plugin_registrant.h" +#include void RegisterPlugins(flutter::PluginRegistry* registry) { + FlutterSecureStorageWindowsPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FlutterSecureStorageWindowsPlugin")); } diff --git a/windows/flutter/generated_plugins.cmake b/windows/flutter/generated_plugins.cmake index b93c4c3..4fc759c 100644 --- a/windows/flutter/generated_plugins.cmake +++ b/windows/flutter/generated_plugins.cmake @@ -3,6 +3,7 @@ # list(APPEND FLUTTER_PLUGIN_LIST + flutter_secure_storage_windows ) list(APPEND FLUTTER_FFI_PLUGIN_LIST