Skip to content
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
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
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
2 changes: 2 additions & 0 deletions with_flutter/.env.example
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"
56 changes: 56 additions & 0 deletions with_flutter/.gitignore
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
45 changes: 45 additions & 0 deletions with_flutter/.metadata
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'
43 changes: 43 additions & 0 deletions with_flutter/README.md
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
```
Copy link
Collaborator

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.

Copy link
Author

@Saffron-codes Saffron-codes Dec 17, 2024

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

Copy link
Collaborator

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?

Copy link
Author

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.

  1. Install Android Studio
  2. Use AVD Manager to setup emulators, choose any of the latest android SDK
  3. Open the project in Android Studio. Start the installed emulator.
  4. Now, execute flutter run

28 changes: 28 additions & 0 deletions with_flutter/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
39 changes: 39 additions & 0 deletions with_flutter/lib/main.dart
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,
),
);
}
}
171 changes: 171 additions & 0 deletions with_flutter/lib/todos_page.dart
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'),
),
],
),
);
}
}
Loading