Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Add files via upload
  • Loading branch information
I-am-the-coder-Tusharbola authored Oct 29, 2023
commit ad8659280c4a0589990e1f4f86a85a9b2a26ae0e
28 changes: 28 additions & 0 deletions sustainable-living-guide-app/analysis_options.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# This file configures the analyzer, which statically analyzes Dart code to
# check for errors, warnings, and lints.
#
# The issues identified by the analyzer are surfaced in the UI of Dart-enabled
# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be
# invoked from the command line by running `flutter analyze`.

# The following line activates a set of recommended lints for Flutter apps,
# packages, and plugins designed to encourage good coding practices.
include: package:flutter_lints/flutter.yaml

linter:
# The lint rules applied to this project can be customized in the
# section below to disable rules from the `package:flutter_lints/flutter.yaml`
# included above or to enable additional rules. A list of all available lints
# and their documentation is published at https://dart.dev/lints.
#
# Instead of disabling a lint rule for the entire project in the
# section below, it can also be suppressed for a single line of code
# or a specific dart file by using the `// ignore: name_of_lint` and
# `// ignore_for_file: name_of_lint` syntax on the line or in the file
# producing the lint.
rules:
# avoid_print: false # Uncomment to disable the `avoid_print` rule
# prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule

# Additional information about this file can be found at
# https://dart.dev/guides/language/analysis-options
115 changes: 115 additions & 0 deletions sustainable-living-guide-app/lib/AI_support.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
// Importing necessary packages
import 'package:flutter/material.dart';
import 'package:dart_openai/dart_openai.dart';

// Defining a stateful widget for the AI chat screen
class AIChatScreen extends StatefulWidget {
const AIChatScreen({Key? key}) : super(key: key);

@override
_AIChatScreenState createState() => _AIChatScreenState();
}

// Defining the state for the AI chat screen
class _AIChatScreenState extends State<AIChatScreen> {
// Initializing a text editing controller for the input field
final TextEditingController _controller = TextEditingController();

// Initializing a list to store the messages
final List<Message> _messages = <Message>[];

// Function to handle the submission of a query
Future<void> _submitQuery(String text) async {
// Setting the API key for OpenAI
OpenAI.apiKey = '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';

// Creating a completion with the OpenAI API
final completion = await OpenAI.instance.completion.create(
model: "text-davinci-003",
prompt: text,
maxTokens: 200,
stop: '/n',
);

// Updating the state with the new messages
setState(() {
_messages.insert(
0, Message(text: 'AI: ${completion.choices[0].text}', type: 'ai'));
_messages.insert(0, Message(text: 'User: $text', type: 'user'));
});

// Clearing the input field
_controller.clear();
}

@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: const Text('AI Support'),
centerTitle: true,
),
body: Column(
children: <Widget>[
Flexible(
child: ListView.builder(
padding: const EdgeInsets.all(8.0),
reverse: false,
itemBuilder: (_, int index) => _messages[index],
itemCount: _messages.length,
),
),
const Divider(height: 1.0),
Container(
decoration: BoxDecoration(color: Theme.of(context).cardColor),
child: IconTheme(
data:
IconThemeData(color: Theme.of(context).colorScheme.secondary),
child: Container(
margin: const EdgeInsets.symmetric(horizontal: 8.0),
child: Row(
children: <Widget>[
Flexible(
child: TextField(
controller: _controller,
onSubmitted: _submitQuery,
decoration: const InputDecoration.collapsed(
hintText: "Send a message"),
),
),
Container(
margin: const EdgeInsets.symmetric(horizontal: 4.0),
child: IconButton(
icon: const Icon(Icons.send),
onPressed: () => _submitQuery(_controller.text)),
),
],
),
),
),
),
],
),
);
}
}

// Defining a stateless widget for a message
class Message extends StatelessWidget {
const Message({this.text, this.type});

final String? text;
final String? type;

@override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.symmetric(vertical: 10.0, horizontal: 10.0),
child: type == 'ai'
? Text(text!,
style: const TextStyle(color: Colors.blue, fontSize: 14))
: Text(text!, style: const TextStyle(fontSize: 14)),
);
}
}
170 changes: 170 additions & 0 deletions sustainable-living-guide-app/lib/community_forum_screen.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
// Importing necessary packages
import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:supabase/supabase.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

// Defining a stateful widget for the community forum screen
class CommunityForumScreen extends StatefulWidget {
@override
_CommunityForumScreenState createState() => _CommunityForumScreenState();
}

// Defining the state for the community forum screen
class _CommunityForumScreenState extends State<CommunityForumScreen> {
// Initializing a Supabase client with the URL and API key
final client = SupabaseClient('https://poqhuqdfdnygffdamvhv.supabase.co',
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InBvcWh1cWRmZG55Z2ZmZGFtdmh2Iiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImlhdCI6MTY5ODU2MzE2OCwiZXhwIjoyMDE0MTM5MTY4fQ.mLsveckdJ7eAlWz3UTXjBLj2zr87BhbmW5sYwWDccpU');
String? userName;

@override
void initState() {
super.initState();
getUserName(); // Fetching the username when the widget is initialized
}

// Function to get the username from a local file
Future<void> getUserName() async {
final status = await Permission.storage.request();
if (status.isGranted) {
final directory = await getApplicationDocumentsDirectory();
final file = File('${directory.path}/user_name.txt');
userName = await file.readAsString(); // Reading the file here
setState(() {}); // Then updating the state here
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Community Forum'),
),
body: userName == null
? Center(
child:
CircularProgressIndicator()) // Showing a progress indicator while fetching the username
: Column(
children: [
Expanded(
child: MessagesView(client,
userName!)), // Displaying the messages view here
MessageInput(client,
userName!), // Displaying the message input field here
],
),
);
}
}

// Defining a stateful widget for the messages view
class MessagesView extends StatefulWidget {
final SupabaseClient client;
final String userName;

MessagesView(this.client, this.userName);

@override
_MessagesViewState createState() => _MessagesViewState();
}

// Defining the state for the messages view
class _MessagesViewState extends State<MessagesView> {
final messages =
<Map<String, dynamic>>[]; // Initializing a list to store the messages
Timer? _timer; // Initializing a timer to fetch messages periodically

@override
void initState() {
super.initState();
_timer = Timer.periodic(
Duration(seconds: 2),
(timer) =>
fetchMessages()); // Fetching messages every 2 seconds when the widget is initialized
}

@override
void dispose() {
_timer?.cancel(); // Canceling the timer when disposing of the widget
super.dispose();
}

// Function to fetch messages from a Supabase table named 'messages'
fetchMessages() async {
final response = await widget.client.from('messages').select().execute();
if (response.status == 200 && response.data != null) {
setState(() {
messages.clear(); // Clearing old messages here
for (var item in response.data) {
if (item is Map<String, dynamic>) {
messages.insert(0,
item); // Inserting new messages at the beginning of the list here
}
}
});
} else {
// Removed print statement. You can handle the error here by showing it in the UI.
}
}

@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: messages.length,
itemBuilder: (context, index) {
final message = messages[index];
return ListTile(
title: Text('${message['text']}'),
subtitle: Text('${message['timestamp']}'),
);
},
);
}
}

// Defining a stateful widget for message input field
class MessageInput extends StatefulWidget {
final SupabaseClient client;
final String userName;

MessageInput(this.client, this.userName);

@override
_MessageInputState createState() => _MessageInputState();
}

// Defining the state for the message input field
class _MessageInputState extends State<MessageInput> {
final controller =
TextEditingController(); // Initializing a text editing controller for the input field

@override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(8),
child: Row(
children: [
Expanded(
child: TextField(
controller: controller,
decoration: InputDecoration(hintText: 'Enter message'),
),
),
IconButton(
icon: Icon(Icons.send),
onPressed: () async {
await widget.client.from('messages').insert({
'text': '${widget.userName}: ${controller.text}',
'timestamp': DateTime.now().toIso8601String()
});
controller
.clear(); // Clearing the input field after sending a message
},
),
],
),
);
}
}
67 changes: 67 additions & 0 deletions sustainable-living-guide-app/lib/loading_screen.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
// Importing necessary packages
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show rootBundle;
import 'dart:math';
import 'welcome_screen.dart';

// Defining a stateful widget for the loading screen
class LoadingScreen extends StatefulWidget {
@override
_LoadingScreenState createState() => _LoadingScreenState();
}

// Defining the state for the loading screen
class _LoadingScreenState extends State<LoadingScreen> {
String _quote = ''; // Initializing a string to store the quote

@override
void initState() {
super.initState();
loadQuote().then((value) {
// Loading a quote when the widget is initialized
setState(() {
_quote = value; // Then updating the state with the loaded quote here
});
});
Future.delayed(Duration(seconds: 10), () {
// Navigating to the welcome screen after 10 seconds
Navigator.pushReplacement(
context, MaterialPageRoute(builder: (context) => WelcomeScreen()));
});
}

// Function to load a random quote from a text file
Future<String> loadQuote() async {
String text = await rootBundle.loadString(
'assets/quotes.txt'); // Loading the quotes from a text file here
List<String> quotes =
text.split('\n'); // Splitting the text into individual quotes here
return quotes[
Random().nextInt(quotes.length)]; // Returning a random quote here
}

@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Expanded(
child: Center(
child: Container(
height: 200.0,
child: Image.asset(
'assets/images/logo.jpeg'), // Displaying the logo here
),
),
),
Text(_quote), // Displaying the quote here

CircularProgressIndicator(), // Displaying a progress indicator here

SizedBox(height: 20.0),
],
),
);
}
}
Loading