-
Notifications
You must be signed in to change notification settings - Fork 13
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: add Flutter example #36
Open
Saffron-codes
wants to merge
2
commits into
neondatabase:main
Choose a base branch
from
Saffron-codes:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
# Postgres URL retrieved here: https://console.neon.tech | ||
POSTGRES_URL="postgresql://neondb_owner:[email protected]/neondb?sslmode=require" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
# Miscellaneous | ||
*.class | ||
*.log | ||
*.pyc | ||
*.swp | ||
.DS_Store | ||
.atom/ | ||
.buildlog/ | ||
.history | ||
.svn/ | ||
migrate_working_dir/ | ||
|
||
# IntelliJ related | ||
*.iml | ||
*.ipr | ||
*.iws | ||
.idea/ | ||
|
||
# The .vscode folder contains launch configuration and tasks you configure in | ||
# VS Code which you may wish to be included in version control, so this line | ||
# is commented out by default. | ||
#.vscode/ | ||
|
||
# Flutter/Dart/Pub related | ||
**/doc/api/ | ||
**/ios/Flutter/.last_build_id | ||
.dart_tool/ | ||
.flutter-plugins | ||
.flutter-plugins-dependencies | ||
.pub-cache/ | ||
.pub/ | ||
/build/ | ||
|
||
# Symbolication related | ||
app.*.symbols | ||
|
||
# Obfuscation related | ||
app.*.map.json | ||
|
||
# Android Studio will place build artifacts here | ||
/android/app/debug | ||
/android/app/profile | ||
/android/app/release | ||
|
||
|
||
android/ | ||
ios/ | ||
web/ | ||
|
||
|
||
# Ignore .env and .env.local files | ||
.env | ||
.env.local | ||
|
||
# Allow .env.example to be tracked | ||
!.env.example |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
# This file tracks properties of this Flutter project. | ||
# Used by Flutter tool to assess capabilities and perform upgrades etc. | ||
# | ||
# This file should be version controlled and should not be manually edited. | ||
|
||
version: | ||
revision: "2663184aa79047d0a33a14a3b607954f8fdd8730" | ||
channel: "stable" | ||
|
||
project_type: app | ||
|
||
# Tracks metadata for the flutter migrate command | ||
migration: | ||
platforms: | ||
- platform: root | ||
create_revision: 2663184aa79047d0a33a14a3b607954f8fdd8730 | ||
base_revision: 2663184aa79047d0a33a14a3b607954f8fdd8730 | ||
- platform: android | ||
create_revision: 2663184aa79047d0a33a14a3b607954f8fdd8730 | ||
base_revision: 2663184aa79047d0a33a14a3b607954f8fdd8730 | ||
- platform: ios | ||
create_revision: 2663184aa79047d0a33a14a3b607954f8fdd8730 | ||
base_revision: 2663184aa79047d0a33a14a3b607954f8fdd8730 | ||
- platform: linux | ||
create_revision: 2663184aa79047d0a33a14a3b607954f8fdd8730 | ||
base_revision: 2663184aa79047d0a33a14a3b607954f8fdd8730 | ||
- platform: macos | ||
create_revision: 2663184aa79047d0a33a14a3b607954f8fdd8730 | ||
base_revision: 2663184aa79047d0a33a14a3b607954f8fdd8730 | ||
- platform: web | ||
create_revision: 2663184aa79047d0a33a14a3b607954f8fdd8730 | ||
base_revision: 2663184aa79047d0a33a14a3b607954f8fdd8730 | ||
- platform: windows | ||
create_revision: 2663184aa79047d0a33a14a3b607954f8fdd8730 | ||
base_revision: 2663184aa79047d0a33a14a3b607954f8fdd8730 | ||
|
||
# User provided section | ||
|
||
# List of Local paths (relative to this file) that should be | ||
# ignored by the migrate tool. | ||
# | ||
# Files that are not part of the templates will be ignored by default. | ||
unmanaged_files: | ||
- 'lib/main.dart' | ||
- 'ios/Runner.xcodeproj/project.pbxproj' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
<img width="250px" src="https://raw.githubusercontent.com/neondatabase/website/a898a3ff9c2786a3fd4691d083eb8f3c751e008b/src/images/logo-white.svg" /> | ||
|
||
# Getting started with Neon and Flutter | ||
|
||
## Clone the repository | ||
|
||
```bash | ||
npx degit neondatabase/examples/with-flutter ./with-flutter | ||
``` | ||
|
||
Run the command below to copy the `.env.example` file: | ||
|
||
``` | ||
cp .env.example .env | ||
``` | ||
|
||
## Store your Neon credentials | ||
|
||
Store your Neon credentials in your `.env` file. | ||
|
||
``` | ||
DATABASE_URL="postgresql://neondb_owner:[email protected]/neondb?sslmode=require" | ||
``` | ||
|
||
- `user` is the database user. | ||
- `password` is the database user’s password. | ||
- `endpoint_hostname` is the host with neon.tech as the [TLD](https://www.cloudflare.com/en-gb/learning/dns/top-level-domain/). | ||
- `dbname` is the name of the database. “neondb” is the default database created with each Neon project. | ||
- `?sslmode=require` an optional query parameter that enforces the [SSL](https://www.cloudflare.com/en-gb/learning/ssl/what-is-ssl/) mode while connecting to the Postgres instance for better security. | ||
|
||
**Important**: To ensure the security of your data, never expose your Neon credentials to the browser. | ||
|
||
Run the command below to install project dependencies: | ||
|
||
``` | ||
flutter pub get | ||
``` | ||
|
||
Run the Express application using the following command: | ||
|
||
``` | ||
flutter run | ||
``` | ||
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
import 'package:flutter/material.dart'; | ||
import 'package:flutter_dotenv/flutter_dotenv.dart'; | ||
import 'package:postgres/postgres.dart'; | ||
import 'package:with_flutter/todos_page.dart'; | ||
|
||
void main() async { | ||
WidgetsFlutterBinding.ensureInitialized(); | ||
await dotenv.load(fileName: ".env"); | ||
final url = Uri.parse(dotenv.get("DATABASE_URL")); | ||
|
||
final conn = await Connection.open(Endpoint( | ||
host: url.host, | ||
database: url.path.replaceAll("/", ""), | ||
username: url.userInfo.split(':')[0], | ||
password: url.userInfo.split(':')[1], | ||
)); | ||
|
||
runApp(MyApp(db: conn)); | ||
} | ||
|
||
class MyApp extends StatelessWidget { | ||
const MyApp({super.key, required this.db}); | ||
|
||
final Connection db; | ||
|
||
@override | ||
Widget build(BuildContext context) { | ||
return MaterialApp( | ||
title: 'Flutter + Neon 🚀', | ||
theme: ThemeData( | ||
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), | ||
useMaterial3: true, | ||
), | ||
home: TodosPage( | ||
db: db, | ||
), | ||
); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,171 @@ | ||
import 'package:flutter/material.dart'; | ||
import 'package:postgres/postgres.dart'; | ||
|
||
class TodosPage extends StatefulWidget { | ||
const TodosPage({super.key, required this.db}); | ||
|
||
final Connection db; | ||
|
||
@override | ||
State<TodosPage> createState() => _TodosPageState(); | ||
} | ||
|
||
class _TodosPageState extends State<TodosPage> { | ||
List<Map<String, dynamic>> todos = []; | ||
bool isLoading = true; | ||
String error = ""; | ||
final TextEditingController todoController = TextEditingController(); | ||
|
||
@override | ||
void initState() { | ||
super.initState(); | ||
getTodos(); | ||
} | ||
|
||
void showError(BuildContext context) { | ||
ScaffoldMessenger.of(context).showSnackBar( | ||
const SnackBar( | ||
content: Text("Some error occurred"), | ||
backgroundColor: Colors.red, | ||
), | ||
); | ||
} | ||
|
||
void getTodos() async { | ||
try { | ||
final res = await widget.db.execute("select * from todos order by done"); | ||
|
||
todos = res | ||
.map((item) => {"id": item[0], "text": item[1], "done": item[2]}) | ||
.toList(); | ||
isLoading = false; | ||
setState(() {}); | ||
} on Exception catch (e) { | ||
isLoading = false; | ||
error = e.toString(); | ||
setState(() {}); | ||
} | ||
} | ||
|
||
void addTodo() async { | ||
try { | ||
final String todo = todoController.text.trim(); | ||
|
||
if (todo.isNotEmpty) { | ||
await widget.db.execute( | ||
r"insert into todos(text) values($1)", | ||
parameters: [todoController.text], | ||
); | ||
todoController.clear(); | ||
|
||
getTodos(); | ||
} | ||
} on Exception catch (e) { | ||
showError(context); | ||
} | ||
} | ||
|
||
void updateTodo(int id, bool val) async { | ||
try { | ||
await widget.db.execute( | ||
r"update todos set done = $1 where id=$2", | ||
parameters: [val, id], | ||
); | ||
getTodos(); | ||
} on Exception catch (e) { | ||
showError(context); | ||
} | ||
} | ||
|
||
void deleteTodo(int id) async { | ||
try { | ||
await widget.db.execute( | ||
r"delete from todos where id=$1", | ||
parameters: [id], | ||
); | ||
getTodos(); | ||
} on Exception catch (e) { | ||
showError(context); | ||
} | ||
} | ||
|
||
@override | ||
Widget build(BuildContext context) { | ||
return Scaffold( | ||
appBar: AppBar( | ||
title: const Text("Flutter + Neon 🚀"), | ||
), | ||
body: buildBody(), | ||
); | ||
} | ||
|
||
Widget buildBody() { | ||
if (isLoading) { | ||
return const Center( | ||
child: CircularProgressIndicator(), | ||
); | ||
} else { | ||
return Column( | ||
children: [ | ||
todos.isNotEmpty | ||
? buildTodoList() | ||
: const Expanded( | ||
child: Center( | ||
child: Text("No Todos"), | ||
), | ||
), | ||
buildAddTodoForm(), | ||
], | ||
); | ||
} | ||
} | ||
|
||
Widget buildTodoList() { | ||
return Expanded( | ||
child: ListView.builder( | ||
shrinkWrap: true, | ||
itemCount: todos.length, | ||
itemBuilder: (_, i) { | ||
return ListTile( | ||
title: Text(todos[i]["text"]), | ||
leading: Checkbox( | ||
value: todos[i]["done"], | ||
onChanged: (val) { | ||
updateTodo(todos[i]['id'], val!); | ||
}, | ||
), | ||
trailing: IconButton( | ||
onPressed: () => deleteTodo(todos[i]["id"]), | ||
icon: const Icon(Icons.delete), | ||
), | ||
); | ||
}, | ||
), | ||
); | ||
} | ||
|
||
Widget buildAddTodoForm() { | ||
return Card( | ||
child: Row( | ||
children: [ | ||
// Input Field | ||
Expanded( | ||
child: TextField( | ||
controller: todoController, | ||
decoration: const InputDecoration( | ||
hintText: 'Enter a task...', | ||
border: OutlineInputBorder(), | ||
), | ||
), | ||
), | ||
const SizedBox(width: 8), | ||
// Add Button | ||
ElevatedButton( | ||
onPressed: addTodo, | ||
child: const Text('Add'), | ||
), | ||
], | ||
), | ||
); | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
How can I install the Flutter CLI?
Also, how to run this in a Mac? I tried this but it keeps saying no wireless device connected.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Checkout the flutter docs for the platforms you want to test in a Mac:
android
iOS
make sure you have the android or iOS virtual devices running before executing
flutter run
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@Saffron-codes can you help me with what's to be done to set up android or ios virtual devices?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sure!. Let's go with the easy one, Android.
flutter run