initial commit 2

This commit is contained in:
David
2026-05-22 18:58:35 -06:00
parent 1334540303
commit abfbb255fe
157 changed files with 8071 additions and 1 deletions

48
.gitignore vendored
View File

@@ -1,3 +1,4 @@
<<<<<<< HEAD
# ---> Flutter
# Miscellaneous
*.class
@@ -153,3 +154,50 @@ google-services.json
# Android Profiling
*.hprof
=======
# Miscellaneous
*.class
*.log
*.pyc
*.swp
.DS_Store
.atom/
.build/
.buildlog/
.history
.svn/
.swiftpm/
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-dependencies
.pub-cache/
.pub/
/build/
/coverage/
# 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
>>>>>>> 8e51b9c (initial commit 2)

45
.metadata Normal file
View File

@@ -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: "559ffa3f75e7402d65a8def9c28389a9b2e6fe42"
channel: "stable"
project_type: app
# Tracks metadata for the flutter migrate command
migration:
platforms:
- platform: root
create_revision: 559ffa3f75e7402d65a8def9c28389a9b2e6fe42
base_revision: 559ffa3f75e7402d65a8def9c28389a9b2e6fe42
- platform: android
create_revision: 559ffa3f75e7402d65a8def9c28389a9b2e6fe42
base_revision: 559ffa3f75e7402d65a8def9c28389a9b2e6fe42
- platform: ios
create_revision: 559ffa3f75e7402d65a8def9c28389a9b2e6fe42
base_revision: 559ffa3f75e7402d65a8def9c28389a9b2e6fe42
- platform: linux
create_revision: 559ffa3f75e7402d65a8def9c28389a9b2e6fe42
base_revision: 559ffa3f75e7402d65a8def9c28389a9b2e6fe42
- platform: macos
create_revision: 559ffa3f75e7402d65a8def9c28389a9b2e6fe42
base_revision: 559ffa3f75e7402d65a8def9c28389a9b2e6fe42
- platform: web
create_revision: 559ffa3f75e7402d65a8def9c28389a9b2e6fe42
base_revision: 559ffa3f75e7402d65a8def9c28389a9b2e6fe42
- platform: windows
create_revision: 559ffa3f75e7402d65a8def9c28389a9b2e6fe42
base_revision: 559ffa3f75e7402d65a8def9c28389a9b2e6fe42
# 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'

View File

@@ -1,3 +1,23 @@
<<<<<<< HEAD
# ProxyTrash
Una aplicacion para saber si el camion mas sercano es Organico o inorganico junto con su distancia y otras funciones mas.
Una aplicacion para saber si el camion mas sercano es Organico o inorganico junto con su distancia y otras funciones mas.
=======
# flutter_application_1
A new Flutter project.
## Getting Started
This project is a starting point for a Flutter application.
A few resources to get you started if this is your first Flutter project:
- [Learn Flutter](https://docs.flutter.dev/get-started/learn-flutter)
- [Write your first Flutter app](https://docs.flutter.dev/get-started/codelab)
- [Flutter learning resources](https://docs.flutter.dev/reference/learning-resources)
For help getting started with Flutter development, view the
[online documentation](https://docs.flutter.dev/), which offers tutorials,
samples, guidance on mobile development, and a full API reference.
>>>>>>> 8e51b9c (initial commit 2)

28
analysis_options.yaml Normal file
View File

@@ -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

14
android/.gitignore vendored Normal file
View File

@@ -0,0 +1,14 @@
gradle-wrapper.jar
/.gradle
/captures/
/gradlew
/gradlew.bat
/local.properties
GeneratedPluginRegistrant.java
.cxx/
# Remember to never publicly share your keystore.
# See https://flutter.dev/to/reference-keystore
key.properties
**/*.keystore
**/*.jks

View File

@@ -0,0 +1,45 @@
plugins {
id("com.android.application")
// The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins.
id("dev.flutter.flutter-gradle-plugin")
}
android {
namespace = "com.example.flutter_application_1"
compileSdk = flutter.compileSdkVersion
ndkVersion = flutter.ndkVersion
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId = "com.example.flutter_application_1"
// You can update the following values to match your application needs.
// For more information, see: https://flutter.dev/to/review-gradle-config.
minSdk = flutter.minSdkVersion
targetSdk = flutter.targetSdkVersion
versionCode = flutter.versionCode
versionName = flutter.versionName
}
buildTypes {
release {
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so `flutter run --release` works.
signingConfig = signingConfigs.getByName("debug")
}
}
}
kotlin {
compilerOptions {
jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17
}
}
flutter {
source = "../.."
}

View File

@@ -0,0 +1,7 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- The INTERNET permission is required for development. Specifically,
the Flutter tool needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>

View File

@@ -0,0 +1,45 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application
android:label="flutter_application_1"
android:name="${applicationName}"
android:icon="@mipmap/ic_launcher">
<activity
android:name=".MainActivity"
android:exported="true"
android:launchMode="singleTop"
android:taskAffinity=""
android:theme="@style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<!-- Specifies an Android theme to apply to this Activity as soon as
the Android process has started. This theme is visible to the user
while the Flutter UI initializes. After that, this theme continues
to determine the Window background behind the Flutter UI. -->
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="@style/NormalTheme"
/>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
android:name="flutterEmbedding"
android:value="2" />
</application>
<!-- Required to query activities that can process text, see:
https://developer.android.com/training/package-visibility and
https://developer.android.com/reference/android/content/Intent#ACTION_PROCESS_TEXT.
In particular, this is used by the Flutter engine in io.flutter.plugin.text.ProcessTextPlugin. -->
<queries>
<intent>
<action android:name="android.intent.action.PROCESS_TEXT"/>
<data android:mimeType="text/plain"/>
</intent>
</queries>
</manifest>

View File

@@ -0,0 +1,5 @@
package com.example.flutter_application_1
import io.flutter.embedding.android.FlutterActivity
class MainActivity : FlutterActivity()

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Modify this file to customize your launch splash screen -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="?android:colorBackground" />
<!-- You can insert your own image assets here -->
<!-- <item>
<bitmap
android:gravity="center"
android:src="@mipmap/launch_image" />
</item> -->
</layer-list>

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Modify this file to customize your launch splash screen -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@android:color/white" />
<!-- You can insert your own image assets here -->
<!-- <item>
<bitmap
android:gravity="center"
android:src="@mipmap/launch_image" />
</item> -->
</layer-list>

Binary file not shown.

After

Width:  |  Height:  |  Size: 544 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 442 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 721 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

View File

@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is on -->
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
<!-- Show a splash screen on the activity. Automatically removed when
the Flutter engine draws its first frame -->
<item name="android:windowBackground">@drawable/launch_background</item>
</style>
<!-- Theme applied to the Android Window as soon as the process has started.
This theme determines the color of the Android Window while your
Flutter UI initializes, as well as behind your Flutter UI while its
running.
This Theme is only used starting with V2 of Flutter's Android embedding. -->
<style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar">
<item name="android:windowBackground">?android:colorBackground</item>
</style>
</resources>

View File

@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is off -->
<style name="LaunchTheme" parent="@android:style/Theme.Light.NoTitleBar">
<!-- Show a splash screen on the activity. Automatically removed when
the Flutter engine draws its first frame -->
<item name="android:windowBackground">@drawable/launch_background</item>
</style>
<!-- Theme applied to the Android Window as soon as the process has started.
This theme determines the color of the Android Window while your
Flutter UI initializes, as well as behind your Flutter UI while its
running.
This Theme is only used starting with V2 of Flutter's Android embedding. -->
<style name="NormalTheme" parent="@android:style/Theme.Light.NoTitleBar">
<item name="android:windowBackground">?android:colorBackground</item>
</style>
</resources>

View File

@@ -0,0 +1,7 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- The INTERNET permission is required for development. Specifically,
the Flutter tool needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>

24
android/build.gradle.kts Normal file
View File

@@ -0,0 +1,24 @@
allprojects {
repositories {
google()
mavenCentral()
}
}
val newBuildDir: Directory =
rootProject.layout.buildDirectory
.dir("../../build")
.get()
rootProject.layout.buildDirectory.value(newBuildDir)
subprojects {
val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name)
project.layout.buildDirectory.value(newSubprojectBuildDir)
}
subprojects {
project.evaluationDependsOn(":app")
}
tasks.register<Delete>("clean") {
delete(rootProject.layout.buildDirectory)
}

View File

@@ -0,0 +1,6 @@
org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError
android.useAndroidX=true
# This newDsl flag was added by the Flutter template
android.newDsl=false
# This builtInKotlin flag was added by the Flutter template
android.builtInKotlin=false

View File

@@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.1.0-all.zip

View File

@@ -0,0 +1,26 @@
pluginManagement {
val flutterSdkPath =
run {
val properties = java.util.Properties()
file("local.properties").inputStream().use { properties.load(it) }
val flutterSdkPath = properties.getProperty("flutter.sdk")
require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" }
flutterSdkPath
}
includeBuild("$flutterSdkPath/packages/flutter_tools/gradle")
repositories {
google()
mavenCentral()
gradlePluginPortal()
}
}
plugins {
id("dev.flutter.flutter-plugin-loader") version "1.0.0"
id("com.android.application") version "9.0.1" apply false
id("org.jetbrains.kotlin.android") version "2.3.20" apply false
}
include(":app")

4
backend/.env Normal file
View File

@@ -0,0 +1,4 @@
DATABASE_URL=postgresql+psycopg://postgres:password@127.0.0.1:5432/hackaton
SECRET_KEY=change-this-in-production
ACCESS_TOKEN_EXPIRE_MINUTES=10080
CORS_ORIGINS=http://localhost:3000,http://10.0.2.2:3000

View File

@@ -0,0 +1,5 @@
# Copia este contenido a backend/.env y reemplaza los valores entre < >
DATABASE_URL=postgresql+psycopg://<usuario>:<contraseña>@<IP_DE_TU_POSTGRESQL>:5432/<nombre_base_datos>
SECRET_KEY=<cadena_larga_secreta>
ACCESS_TOKEN_EXPIRE_MINUTES=10080
CORS_ORIGINS=http://localhost:3000,http://10.0.2.2:3000,http://<IP_DE_TU_FLUTTER>:8000

4
backend/.env.example Normal file
View File

@@ -0,0 +1,4 @@
DATABASE_URL=postgresql+psycopg://postgres:TU_PASSWORD@10.77.234.29:5432/hackaton
SECRET_KEY=pon-una-clave-larga-y-segura-aqui
ACCESS_TOKEN_EXPIRE_MINUTES=10080
CORS_ORIGINS=http://localhost:3000,http://10.0.2.2:3000,http://10.77.234.6:8000

128
backend/README.md Normal file
View File

@@ -0,0 +1,128 @@
# Backend Python para Flutter
Backend en Python con FastAPI para autenticar usuarios y guardar direcciones en PostgreSQL. No usa HTTPS; expone HTTP en el puerto 8000 por defecto.
## Qué debes cambiar
### 1. Configuración del backend
Crea el archivo `backend/.env` copiando `backend/.env.example` y reemplaza estos valores:
```env
DATABASE_URL=postgresql+psycopg://postgres:TU_PASSWORD@10.77.234.29:5432/hackaton
SECRET_KEY=pon-una-clave-larga-y-segura-aqui
ACCESS_TOKEN_EXPIRE_MINUTES=10080
CORS_ORIGINS=http://localhost:3000,http://10.0.2.2:3000,http://10.77.234.6:8000
```
### 2. Configuración de Flutter
En Flutter, la URL base del backend está en [lib/app_config.dart](../lib/app_config.dart). Debe apuntar al backend HTTP, por ejemplo:
```dart
static const String apiBaseUrl = String.fromEnvironment(
'API_BASE_URL',
defaultValue: 'http://10.77.234.6:8000',
);
```
No pongas la cadena `postgresql://...` en Flutter. Esa cadena solo va en el backend.
## Variables que usa el backend
- `DATABASE_URL`: conexión a PostgreSQL.
- `SECRET_KEY`: clave para firmar el token JWT.
- `ACCESS_TOKEN_EXPIRE_MINUTES`: tiempo de vida del token.
- `CORS_ORIGINS`: orígenes permitidos para la app Flutter o pruebas web.
## Estructura de PostgreSQL
El backend crea las tablas automáticamente al arrancar con `Base.metadata.create_all(...)`, pero si quieres crearlas manualmente, este es el esquema esperado.
### Tabla `users`
```sql
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
name VARCHAR(120) NOT NULL,
email VARCHAR(255) NOT NULL UNIQUE,
password_hash VARCHAR(255) NOT NULL,
last_login_at TIMESTAMPTZ NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
```
### Tabla `addresses`
```sql
CREATE TABLE IF NOT EXISTS addresses (
id SERIAL PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
house_number VARCHAR(50) NOT NULL,
colonia VARCHAR(120) NOT NULL,
street VARCHAR(160) NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
```
## Datos que se envían desde Flutter
### Registro
Se envía al endpoint `POST /auth/register`:
```json
{
"name": "Juan Perez",
"email": "juan@mail.com",
"password": "123456"
}
```
### Inicio de sesión
Se envía al endpoint `POST /auth/login`:
```json
{
"email": "juan@mail.com",
"password": "123456"
}
```
### Dirección
Se envía al endpoint `POST /addresses` con token Bearer:
```json
{
"email": "juan@mail.com",
"houseNumber": "12A",
"colonia": "Centro",
"street": "Reforma"
}
```
## Endpoints disponibles
- `POST /auth/register`
- `POST /auth/login`
- `GET /me`
- `POST /addresses`
- `GET /health`
## Instalar y ejecutar
```bash
cd backend
python -m venv .venv
.venv\Scripts\activate
pip install -r requirements.txt
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
```
## Cómo funciona la conexión
1. Flutter llama a `http://IP_DEL_BACKEND:8000`.
2. El backend recibe login/registro y crea el token JWT.
3. El backend conecta a PostgreSQL usando `DATABASE_URL`.
4. Al guardar la dirección, el backend asocia la dirección al usuario autenticado.
## Nota importante
Si pruebas desde un celular físico, `10.0.2.2` no sirve para la API. Debes usar la IP real de la computadora donde corre el backend.

0
backend/app/__init__.py Normal file
View File

22
backend/app/auth.py Normal file
View File

@@ -0,0 +1,22 @@
from datetime import datetime, timedelta, timezone
from jose import jwt
from passlib.context import CryptContext
from .core.config import settings
pwd_context = CryptContext(schemes=['bcrypt'], deprecated='auto')
def hash_password(password: str) -> str:
return pwd_context.hash(password)
def verify_password(plain_password: str, hashed_password: str) -> bool:
return pwd_context.verify(plain_password, hashed_password)
def create_access_token(*, user_id: int, email: str) -> str:
expire = datetime.now(timezone.utc) + timedelta(minutes=settings.access_token_expire_minutes)
payload = {'sub': str(user_id), 'email': email, 'exp': expire}
return jwt.encode(payload, settings.secret_key, algorithm=settings.algorithm)

View File

View File

@@ -0,0 +1,25 @@
from functools import lru_cache
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_file='.env', env_file_encoding='utf-8', extra='ignore')
database_url: str = 'postgresql+psycopg://postgres:password@127.0.0.1:5432/hackaton'
secret_key: str = 'change-this-in-production'
algorithm: str = 'HS256'
access_token_expire_minutes: int = 60 * 24 * 7
cors_origins: str = 'http://localhost:3000,http://10.0.2.2:3000'
@property
def cors_origin_list(self) -> list[str]:
return [origin.strip() for origin in self.cors_origins.split(',') if origin.strip()]
@lru_cache
def get_settings() -> Settings:
return Settings()
settings = get_settings()

56
backend/app/crud.py Normal file
View File

@@ -0,0 +1,56 @@
from datetime import datetime, timezone
from sqlalchemy import select
from sqlalchemy.orm import Session
from .auth import hash_password, verify_password
from .models import Address, User
from .schemas import AddressCreate, UserCreate
def get_user_by_id(db: Session, user_id: int) -> User | None:
return db.get(User, user_id)
def get_user_by_email(db: Session, email: str) -> User | None:
statement = select(User).where(User.email == email)
return db.scalar(statement)
def create_user(db: Session, user_in: UserCreate) -> User:
user = User(
name=user_in.name,
email=user_in.email,
password_hash=hash_password(user_in.password),
)
db.add(user)
db.commit()
db.refresh(user)
return user
def authenticate_user(db: Session, email: str, password: str) -> User | None:
user = get_user_by_email(db, email)
if user is None:
return None
if not verify_password(password, user.password_hash):
return None
user.last_login_at = datetime.now(timezone.utc)
db.add(user)
db.commit()
db.refresh(user)
return user
def create_address(db: Session, user: User, address_in: AddressCreate) -> Address:
address = Address(
user_id=user.id,
house_number=address_in.house_number,
colonia=address_in.colonia,
street=address_in.street,
)
db.add(address)
db.commit()
db.refresh(address)
return address

View File

22
backend/app/db/session.py Normal file
View File

@@ -0,0 +1,22 @@
from collections.abc import Generator
from sqlalchemy import create_engine
from sqlalchemy.orm import DeclarativeBase, Session, sessionmaker
from ..core.config import settings
class Base(DeclarativeBase):
pass
engine = create_engine(settings.database_url, pool_pre_ping=True)
SessionLocal = sessionmaker(bind=engine, autocommit=False, autoflush=False)
def get_db() -> Generator[Session, None, None]:
db = SessionLocal()
try:
yield db
finally:
db.close()

View File

@@ -0,0 +1,31 @@
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt
from sqlalchemy.orm import Session
from .core.config import settings
from .crud import get_user_by_id
from .db.session import get_db
from .models import User
oauth2_scheme = OAuth2PasswordBearer(tokenUrl='/auth/login')
def get_current_user(token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)) -> User:
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail='Token inválido o expirado',
headers={'WWW-Authenticate': 'Bearer'},
)
try:
payload = jwt.decode(token, settings.secret_key, algorithms=[settings.algorithm])
user_id = payload.get('sub')
if user_id is None:
raise credentials_exception
except JWTError as exc:
raise credentials_exception from exc
user = get_user_by_id(db, int(user_id))
if user is None:
raise credentials_exception
return user

79
backend/app/main.py Normal file
View File

@@ -0,0 +1,79 @@
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy.orm import Session
from .auth import create_access_token
from .core.config import settings
from .crud import authenticate_user, create_address, create_user, get_user_by_email
from .db.session import Base, engine, get_db
from .dependencies import get_current_user
from .models import Address, User
from .schemas import AddressCreate, AddressRead, TokenResponse, UserCreate, UserLogin, UserRead
app = FastAPI(title='Flutter Auth API', version='1.0.0')
app.add_middleware(
CORSMiddleware,
allow_origins=settings.cors_origin_list,
allow_credentials=True,
allow_methods=['*'],
allow_headers=['*'],
)
@app.on_event('startup')
def on_startup() -> None:
Base.metadata.create_all(bind=engine)
@app.get('/health')
def health_check() -> dict[str, str]:
return {'status': 'ok'}
@app.post('/auth/register', response_model=TokenResponse, status_code=status.HTTP_201_CREATED)
def register(payload: UserCreate, db: Session = Depends(get_db)) -> TokenResponse:
existing_user = get_user_by_email(db, payload.email)
if existing_user is not None:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='Ya existe un usuario con ese correo')
user = create_user(db, payload)
token = create_access_token(user_id=user.id, email=user.email)
return TokenResponse(token=token, user=UserRead.model_validate(user))
@app.post('/auth/login', response_model=TokenResponse)
def login(payload: UserLogin, db: Session = Depends(get_db)) -> TokenResponse:
user = authenticate_user(db, payload.email, payload.password)
if user is None:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail='Correo o contraseña inválidos')
token = create_access_token(user_id=user.id, email=user.email)
return TokenResponse(token=token, user=UserRead.model_validate(user))
@app.get('/me', response_model=UserRead)
def read_me(current_user: User = Depends(get_current_user)) -> UserRead:
return UserRead.model_validate(current_user)
@app.post('/addresses', response_model=AddressRead, status_code=status.HTTP_201_CREATED)
def save_address(
payload: AddressCreate,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
) -> AddressRead:
if payload.email is not None and payload.email != current_user.email:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='El correo no coincide con el usuario autenticado')
address = create_address(db, current_user, payload)
return AddressRead.model_validate(address)
@app.get('/addresses/me', response_model=list[AddressRead])
def read_my_addresses(
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
) -> list[AddressRead]:
addresses = sorted(current_user.addresses, key=lambda address: address.created_at, reverse=True)
return [AddressRead.model_validate(address) for address in addresses]

32
backend/app/models.py Normal file
View File

@@ -0,0 +1,32 @@
from datetime import datetime
from sqlalchemy import DateTime, ForeignKey, Integer, String, func
from sqlalchemy.orm import Mapped, mapped_column, relationship
from .db.session import Base
class User(Base):
__tablename__ = 'users'
id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
name: Mapped[str] = mapped_column(String(120), nullable=False)
email: Mapped[str] = mapped_column(String(255), unique=True, index=True, nullable=False)
password_hash: Mapped[str] = mapped_column(String(255), nullable=False)
last_login_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), nullable=False)
addresses: Mapped[list['Address']] = relationship(back_populates='user', cascade='all, delete-orphan')
class Address(Base):
__tablename__ = 'addresses'
id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
user_id: Mapped[int] = mapped_column(ForeignKey('users.id', ondelete='CASCADE'), index=True, nullable=False)
house_number: Mapped[str] = mapped_column(String(50), nullable=False)
colonia: Mapped[str] = mapped_column(String(120), nullable=False)
street: Mapped[str] = mapped_column(String(160), nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), nullable=False)
user: Mapped['User'] = relationship(back_populates='addresses')

50
backend/app/schemas.py Normal file
View File

@@ -0,0 +1,50 @@
from datetime import datetime
from pydantic import BaseModel, ConfigDict, EmailStr, Field
class UserBase(BaseModel):
name: str
email: EmailStr
class UserCreate(UserBase):
password: str
class UserLogin(BaseModel):
email: EmailStr
password: str
class UserRead(UserBase):
model_config = ConfigDict(from_attributes=True)
id: int
last_login_at: datetime | None = None
created_at: datetime
class TokenResponse(BaseModel):
token: str
user: UserRead
class AddressCreate(BaseModel):
model_config = ConfigDict(populate_by_name=True)
house_number: str = Field(alias='houseNumber')
colonia: str
street: str
email: EmailStr | None = None
class AddressRead(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: int
house_number: str
colonia: str
street: str
user_id: int
created_at: datetime

9
backend/requirements.txt Normal file
View File

@@ -0,0 +1,9 @@
fastapi==0.115.0
uvicorn[standard]==0.32.0
SQLAlchemy==2.0.36
psycopg[binary]==3.2.3
pydantic-settings==2.6.0
python-jose[cryptography]==3.3.0
passlib[bcrypt]==1.7.4
python-multipart==0.0.12
email-validator==2.2.0

34
ios/.gitignore vendored Normal file
View File

@@ -0,0 +1,34 @@
**/dgph
*.mode1v3
*.mode2v3
*.moved-aside
*.pbxuser
*.perspectivev3
**/*sync/
.sconsign.dblite
.tags*
**/.vagrant/
**/DerivedData/
Icon?
**/Pods/
**/.symlinks/
profile
xcuserdata
**/.generated/
Flutter/App.framework
Flutter/Flutter.framework
Flutter/Flutter.podspec
Flutter/Generated.xcconfig
Flutter/ephemeral/
Flutter/app.flx
Flutter/app.zip
Flutter/flutter_assets/
Flutter/flutter_export_environment.sh
ServiceDefinitions.json
Runner/GeneratedPluginRegistrant.*
# Exceptions to above rules.
!default.mode1v3
!default.mode2v3
!default.pbxuser
!default.perspectivev3

View File

@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>App</string>
<key>CFBundleIdentifier</key>
<string>io.flutter.flutter.app</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>App</string>
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1.0</string>
</dict>
</plist>

View File

@@ -0,0 +1 @@
#include "Generated.xcconfig"

View File

@@ -0,0 +1 @@
#include "Generated.xcconfig"

View File

@@ -0,0 +1,644 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 54;
objects = {
/* Begin PBXBuildFile section */
1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; };
331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C807B294A618700263BE5 /* RunnerTests.swift */; };
3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; };
74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; };
7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */; };
78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; };
97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; };
97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; };
97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
331C8085294A63A400263BE5 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 97C146E61CF9000F007C117D /* Project object */;
proxyType = 1;
remoteGlobalIDString = 97C146ED1CF9000F007C117D;
remoteInfo = Runner;
};
/* End PBXContainerItemProxy section */
/* Begin PBXCopyFilesBuildPhase section */
9705A1C41CF9048500538489 /* Embed Frameworks */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 2147483647;
dstPath = "";
dstSubfolderSpec = 10;
files = (
);
name = "Embed Frameworks";
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = "<group>"; };
1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = "<group>"; };
331C807B294A618700263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = "<group>"; };
331C8081294A63A400263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = "<group>"; };
74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = "<group>"; };
74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = "<group>"; };
78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; sourceTree = "<group>"; };
7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = "<group>"; };
9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = "<group>"; };
9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = "<group>"; };
97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; };
97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = "<group>"; };
97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
97C146EB1CF9000F007C117D /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
331C8082294A63A400263BE5 /* RunnerTests */ = {
isa = PBXGroup;
children = (
331C807B294A618700263BE5 /* RunnerTests.swift */,
);
path = RunnerTests;
sourceTree = "<group>";
};
9740EEB11CF90186004384FC /* Flutter */ = {
isa = PBXGroup;
children = (
78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */,
3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */,
9740EEB21CF90195004384FC /* Debug.xcconfig */,
7AFA3C8E1D35360C0083082E /* Release.xcconfig */,
9740EEB31CF90195004384FC /* Generated.xcconfig */,
);
name = Flutter;
sourceTree = "<group>";
};
97C146E51CF9000F007C117D = {
isa = PBXGroup;
children = (
9740EEB11CF90186004384FC /* Flutter */,
97C146F01CF9000F007C117D /* Runner */,
97C146EF1CF9000F007C117D /* Products */,
331C8082294A63A400263BE5 /* RunnerTests */,
);
sourceTree = "<group>";
};
97C146EF1CF9000F007C117D /* Products */ = {
isa = PBXGroup;
children = (
97C146EE1CF9000F007C117D /* Runner.app */,
331C8081294A63A400263BE5 /* RunnerTests.xctest */,
);
name = Products;
sourceTree = "<group>";
};
97C146F01CF9000F007C117D /* Runner */ = {
isa = PBXGroup;
children = (
97C146FA1CF9000F007C117D /* Main.storyboard */,
97C146FD1CF9000F007C117D /* Assets.xcassets */,
97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */,
97C147021CF9000F007C117D /* Info.plist */,
1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */,
1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */,
74858FAE1ED2DC5600515810 /* AppDelegate.swift */,
7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */,
74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */,
);
path = Runner;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
331C8080294A63A400263BE5 /* RunnerTests */ = {
isa = PBXNativeTarget;
buildConfigurationList = 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */;
buildPhases = (
331C807D294A63A400263BE5 /* Sources */,
331C807F294A63A400263BE5 /* Resources */,
);
buildRules = (
);
dependencies = (
331C8086294A63A400263BE5 /* PBXTargetDependency */,
);
name = RunnerTests;
productName = RunnerTests;
productReference = 331C8081294A63A400263BE5 /* RunnerTests.xctest */;
productType = "com.apple.product-type.bundle.unit-test";
};
97C146ED1CF9000F007C117D /* Runner */ = {
isa = PBXNativeTarget;
buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */;
buildPhases = (
9740EEB61CF901F6004384FC /* Run Script */,
97C146EA1CF9000F007C117D /* Sources */,
97C146EB1CF9000F007C117D /* Frameworks */,
97C146EC1CF9000F007C117D /* Resources */,
9705A1C41CF9048500538489 /* Embed Frameworks */,
3B06AD1E1E4923F5004D2608 /* Thin Binary */,
);
buildRules = (
);
dependencies = (
);
name = Runner;
packageProductDependencies = (
78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */,
);
productName = Runner;
productReference = 97C146EE1CF9000F007C117D /* Runner.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
97C146E61CF9000F007C117D /* Project object */ = {
isa = PBXProject;
attributes = {
BuildIndependentTargetsInParallel = YES;
LastUpgradeCheck = 1510;
ORGANIZATIONNAME = "";
TargetAttributes = {
331C8080294A63A400263BE5 = {
CreatedOnToolsVersion = 14.0;
TestTargetID = 97C146ED1CF9000F007C117D;
};
97C146ED1CF9000F007C117D = {
CreatedOnToolsVersion = 7.3.1;
LastSwiftMigration = 1100;
};
};
};
buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */;
compatibilityVersion = "Xcode 9.3";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = 97C146E51CF9000F007C117D;
packageReferences = (
781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */,
);
productRefGroup = 97C146EF1CF9000F007C117D /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
97C146ED1CF9000F007C117D /* Runner */,
331C8080294A63A400263BE5 /* RunnerTests */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
331C807F294A63A400263BE5 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
97C146EC1CF9000F007C117D /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */,
3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */,
97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */,
97C146FC1CF9000F007C117D /* Main.storyboard in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
3B06AD1E1E4923F5004D2608 /* Thin Binary */ = {
isa = PBXShellScriptBuildPhase;
alwaysOutOfDate = 1;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
"${TARGET_BUILD_DIR}/${INFOPLIST_PATH}",
);
name = "Thin Binary";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin";
};
9740EEB61CF901F6004384FC /* Run Script */ = {
isa = PBXShellScriptBuildPhase;
alwaysOutOfDate = 1;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = "Run Script";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build";
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
331C807D294A63A400263BE5 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
97C146EA1CF9000F007C117D /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */,
1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */,
7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
331C8086294A63A400263BE5 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 97C146ED1CF9000F007C117D /* Runner */;
targetProxy = 331C8085294A63A400263BE5 /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin PBXVariantGroup section */
97C146FA1CF9000F007C117D /* Main.storyboard */ = {
isa = PBXVariantGroup;
children = (
97C146FB1CF9000F007C117D /* Base */,
);
name = Main.storyboard;
sourceTree = "<group>";
};
97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = {
isa = PBXVariantGroup;
children = (
97C147001CF9000F007C117D /* Base */,
);
name = LaunchScreen.storyboard;
sourceTree = "<group>";
};
/* End PBXVariantGroup section */
/* Begin XCBuildConfiguration section */
249021D3217E4FDB00AE95B9 /* Profile */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
CLANG_ANALYZER_NONNULL = YES;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_USER_SCRIPT_SANDBOXING = NO;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 13.0;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
SUPPORTED_PLATFORMS = iphoneos;
TARGETED_DEVICE_FAMILY = "1,2";
VALIDATE_PRODUCT = YES;
};
name = Profile;
};
249021D4217E4FDB00AE95B9 /* Profile */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
ENABLE_BITCODE = NO;
INFOPLIST_FILE = Runner/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = com.example.flutterApplication1;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
SWIFT_VERSION = 5.0;
VERSIONING_SYSTEM = "apple-generic";
};
name = Profile;
};
331C8088294A63A400263BE5 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.example.flutterApplication1.RunnerTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 5.0;
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner";
};
name = Debug;
};
331C8089294A63A400263BE5 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.example.flutterApplication1.RunnerTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner";
};
name = Release;
};
331C808A294A63A400263BE5 /* Profile */ = {
isa = XCBuildConfiguration;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.example.flutterApplication1.RunnerTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner";
};
name = Profile;
};
97C147031CF9000F007C117D /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
CLANG_ANALYZER_NONNULL = YES;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
ENABLE_USER_SCRIPT_SANDBOXING = NO;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 13.0;
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Debug;
};
97C147041CF9000F007C117D /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
CLANG_ANALYZER_NONNULL = YES;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_USER_SCRIPT_SANDBOXING = NO;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 13.0;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
SUPPORTED_PLATFORMS = iphoneos;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_OPTIMIZATION_LEVEL = "-O";
TARGETED_DEVICE_FAMILY = "1,2";
VALIDATE_PRODUCT = YES;
};
name = Release;
};
97C147061CF9000F007C117D /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
ENABLE_BITCODE = NO;
INFOPLIST_FILE = Runner/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = com.example.flutterApplication1;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 5.0;
VERSIONING_SYSTEM = "apple-generic";
};
name = Debug;
};
97C147071CF9000F007C117D /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
ENABLE_BITCODE = NO;
INFOPLIST_FILE = Runner/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = com.example.flutterApplication1;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
SWIFT_VERSION = 5.0;
VERSIONING_SYSTEM = "apple-generic";
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = {
isa = XCConfigurationList;
buildConfigurations = (
331C8088294A63A400263BE5 /* Debug */,
331C8089294A63A400263BE5 /* Release */,
331C808A294A63A400263BE5 /* Profile */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = {
isa = XCConfigurationList;
buildConfigurations = (
97C147031CF9000F007C117D /* Debug */,
97C147041CF9000F007C117D /* Release */,
249021D3217E4FDB00AE95B9 /* Profile */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = {
isa = XCConfigurationList;
buildConfigurations = (
97C147061CF9000F007C117D /* Debug */,
97C147071CF9000F007C117D /* Release */,
249021D4217E4FDB00AE95B9 /* Profile */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
/* Begin XCLocalSwiftPackageReference section */
781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */ = {
isa = XCLocalSwiftPackageReference;
relativePath = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage;
};
/* End XCLocalSwiftPackageReference section */
/* Begin XCSwiftPackageProductDependency section */
78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */ = {
isa = XCSwiftPackageProductDependency;
productName = FlutterGeneratedPluginSwiftPackage;
};
/* End XCSwiftPackageProductDependency section */
};
rootObject = 97C146E61CF9000F007C117D /* Project object */;
}

View File

@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:">
</FileRef>
</Workspace>

View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>

View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>PreviewsEnabled</key>
<false/>
</dict>
</plist>

View File

@@ -0,0 +1,119 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1510"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<PreActions>
<ExecutionAction
ActionType = "Xcode.IDEStandardExecutionActionsCore.ExecutionActionType.ShellScriptAction">
<ActionContent
title = "Run Prepare Flutter Framework Script"
scriptText = "/bin/sh &quot;$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh&quot; prepare&#10;">
<EnvironmentBuildable>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "97C146ED1CF9000F007C117D"
BuildableName = "Runner.app"
BlueprintName = "Runner"
ReferencedContainer = "container:Runner.xcodeproj">
</BuildableReference>
</EnvironmentBuildable>
</ActionContent>
</ExecutionAction>
</PreActions>
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "97C146ED1CF9000F007C117D"
BuildableName = "Runner.app"
BlueprintName = "Runner"
ReferencedContainer = "container:Runner.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
customLLDBInitFile = "$(SRCROOT)/Flutter/ephemeral/flutter_lldbinit"
shouldUseLaunchSchemeArgsEnv = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "97C146ED1CF9000F007C117D"
BuildableName = "Runner.app"
BlueprintName = "Runner"
ReferencedContainer = "container:Runner.xcodeproj">
</BuildableReference>
</MacroExpansion>
<Testables>
<TestableReference
skipped = "NO"
parallelizable = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "331C8080294A63A400263BE5"
BuildableName = "RunnerTests.xctest"
BlueprintName = "RunnerTests"
ReferencedContainer = "container:Runner.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
customLLDBInitFile = "$(SRCROOT)/Flutter/ephemeral/flutter_lldbinit"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
enableGPUValidationMode = "1"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "97C146ED1CF9000F007C117D"
BuildableName = "Runner.app"
BlueprintName = "Runner"
ReferencedContainer = "container:Runner.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</LaunchAction>
<ProfileAction
buildConfiguration = "Profile"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "97C146ED1CF9000F007C117D"
BuildableName = "Runner.app"
BlueprintName = "Runner"
ReferencedContainer = "container:Runner.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>

View File

@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "group:Runner.xcodeproj">
</FileRef>
</Workspace>

View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>

View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>PreviewsEnabled</key>
<false/>
</dict>
</plist>

View File

@@ -0,0 +1,16 @@
import Flutter
import UIKit
@main
@objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) {
GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry)
}
}

View File

@@ -0,0 +1,122 @@
{
"images" : [
{
"size" : "20x20",
"idiom" : "iphone",
"filename" : "Icon-App-20x20@2x.png",
"scale" : "2x"
},
{
"size" : "20x20",
"idiom" : "iphone",
"filename" : "Icon-App-20x20@3x.png",
"scale" : "3x"
},
{
"size" : "29x29",
"idiom" : "iphone",
"filename" : "Icon-App-29x29@1x.png",
"scale" : "1x"
},
{
"size" : "29x29",
"idiom" : "iphone",
"filename" : "Icon-App-29x29@2x.png",
"scale" : "2x"
},
{
"size" : "29x29",
"idiom" : "iphone",
"filename" : "Icon-App-29x29@3x.png",
"scale" : "3x"
},
{
"size" : "40x40",
"idiom" : "iphone",
"filename" : "Icon-App-40x40@2x.png",
"scale" : "2x"
},
{
"size" : "40x40",
"idiom" : "iphone",
"filename" : "Icon-App-40x40@3x.png",
"scale" : "3x"
},
{
"size" : "60x60",
"idiom" : "iphone",
"filename" : "Icon-App-60x60@2x.png",
"scale" : "2x"
},
{
"size" : "60x60",
"idiom" : "iphone",
"filename" : "Icon-App-60x60@3x.png",
"scale" : "3x"
},
{
"size" : "20x20",
"idiom" : "ipad",
"filename" : "Icon-App-20x20@1x.png",
"scale" : "1x"
},
{
"size" : "20x20",
"idiom" : "ipad",
"filename" : "Icon-App-20x20@2x.png",
"scale" : "2x"
},
{
"size" : "29x29",
"idiom" : "ipad",
"filename" : "Icon-App-29x29@1x.png",
"scale" : "1x"
},
{
"size" : "29x29",
"idiom" : "ipad",
"filename" : "Icon-App-29x29@2x.png",
"scale" : "2x"
},
{
"size" : "40x40",
"idiom" : "ipad",
"filename" : "Icon-App-40x40@1x.png",
"scale" : "1x"
},
{
"size" : "40x40",
"idiom" : "ipad",
"filename" : "Icon-App-40x40@2x.png",
"scale" : "2x"
},
{
"size" : "76x76",
"idiom" : "ipad",
"filename" : "Icon-App-76x76@1x.png",
"scale" : "1x"
},
{
"size" : "76x76",
"idiom" : "ipad",
"filename" : "Icon-App-76x76@2x.png",
"scale" : "2x"
},
{
"size" : "83.5x83.5",
"idiom" : "ipad",
"filename" : "Icon-App-83.5x83.5@2x.png",
"scale" : "2x"
},
{
"size" : "1024x1024",
"idiom" : "ios-marketing",
"filename" : "Icon-App-1024x1024@1x.png",
"scale" : "1x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 295 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 406 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 450 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 282 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 462 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 704 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 406 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 586 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 862 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 862 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 762 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

View File

@@ -0,0 +1,23 @@
{
"images" : [
{
"idiom" : "universal",
"filename" : "LaunchImage.png",
"scale" : "1x"
},
{
"idiom" : "universal",
"filename" : "LaunchImage@2x.png",
"scale" : "2x"
},
{
"idiom" : "universal",
"filename" : "LaunchImage@3x.png",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 B

View File

@@ -0,0 +1,5 @@
# Launch Screen Assets
You can customize the launch screen with your own desired assets by replacing the image files in this directory.
You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images.

View File

@@ -0,0 +1,37 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="12121" systemVersion="16G29" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="12089"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="EHf-IW-A2E">
<objects>
<viewController id="01J-lp-oVM" sceneMemberID="viewController">
<layoutGuides>
<viewControllerLayoutGuide type="top" id="Ydg-fD-yQy"/>
<viewControllerLayoutGuide type="bottom" id="xbc-2k-c8Z"/>
</layoutGuides>
<view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<imageView opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" image="LaunchImage" translatesAutoresizingMaskIntoConstraints="NO" id="YRO-k0-Ey4">
</imageView>
</subviews>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<constraints>
<constraint firstItem="YRO-k0-Ey4" firstAttribute="centerX" secondItem="Ze5-6b-2t3" secondAttribute="centerX" id="1a2-6s-vTC"/>
<constraint firstItem="YRO-k0-Ey4" firstAttribute="centerY" secondItem="Ze5-6b-2t3" secondAttribute="centerY" id="4X2-HB-R7a"/>
</constraints>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="53" y="375"/>
</scene>
</scenes>
<resources>
<image name="LaunchImage" width="168" height="185"/>
</resources>
</document>

View File

@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="10117" systemVersion="15F34" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" initialViewController="BYZ-38-t0r">
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="10085"/>
</dependencies>
<scenes>
<!--Flutter View Controller-->
<scene sceneID="tne-QT-ifu">
<objects>
<viewController id="BYZ-38-t0r" customClass="FlutterViewController" sceneMemberID="viewController">
<layoutGuides>
<viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/>
<viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/>
</layoutGuides>
<view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
<rect key="frame" x="0.0" y="0.0" width="600" height="600"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
</objects>
</scene>
</scenes>
</document>

70
ios/Runner/Info.plist Normal file
View File

@@ -0,0 +1,70 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CADisableMinimumFrameDurationOnPhone</key>
<true/>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleDisplayName</key>
<string>Flutter Application 1</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>flutter_application_1</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>$(FLUTTER_BUILD_NAME)</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>$(FLUTTER_BUILD_NUMBER)</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UIApplicationSceneManifest</key>
<dict>
<key>UIApplicationSupportsMultipleScenes</key>
<false/>
<key>UISceneConfigurations</key>
<dict>
<key>UIWindowSceneSessionRoleApplication</key>
<array>
<dict>
<key>UISceneClassName</key>
<string>UIWindowScene</string>
<key>UISceneConfigurationName</key>
<string>flutter</string>
<key>UISceneDelegateClassName</key>
<string>$(PRODUCT_MODULE_NAME).SceneDelegate</string>
<key>UISceneStoryboardFile</key>
<string>Main</string>
</dict>
</array>
</dict>
</dict>
<key>UIApplicationSupportsIndirectInputEvents</key>
<true/>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIMainStoryboardFile</key>
<string>Main</string>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
</dict>
</plist>

View File

@@ -0,0 +1 @@
#import "GeneratedPluginRegistrant.h"

View File

@@ -0,0 +1,6 @@
import Flutter
import UIKit
class SceneDelegate: FlutterSceneDelegate {
}

View File

@@ -0,0 +1,12 @@
import Flutter
import UIKit
import XCTest
class RunnerTests: XCTestCase {
func testExample() {
// If you add code to the Runner application, consider adding tests here.
// See https://developer.apple.com/documentation/xctest for more information about using XCTest.
}
}

106
lib/app.dart Normal file
View File

@@ -0,0 +1,106 @@
import 'package:flutter/material.dart';
import 'models/auth_session.dart';
import 'screens/auth_screen.dart';
import 'screens/dashboard_screen.dart';
import 'services/address_repository.dart';
import 'services/auth_repository.dart';
class MyApp extends StatelessWidget {
const MyApp({
super.key,
AuthRepository? authRepository,
AddressRepository? addressRepository,
this.enableLiveFeatures = true,
}) : _authRepository = authRepository ?? const HttpAuthRepository(),
_addressRepository = addressRepository ?? const HttpAddressRepository();
final AuthRepository _authRepository;
final AddressRepository _addressRepository;
final bool enableLiveFeatures;
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Acceso',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: const Color(0xFF0F766E)),
useMaterial3: true,
),
home: AuthBootstrap(
authRepository: _authRepository,
addressRepository: _addressRepository,
enableLiveFeatures: enableLiveFeatures,
),
);
}
}
class AuthBootstrap extends StatefulWidget {
const AuthBootstrap({
super.key,
required this.authRepository,
required this.addressRepository,
this.enableLiveFeatures = true,
});
final AuthRepository authRepository;
final AddressRepository addressRepository;
final bool enableLiveFeatures;
@override
State<AuthBootstrap> createState() => _AuthBootstrapState();
}
class _AuthBootstrapState extends State<AuthBootstrap> {
late final Future<AuthSession?> _sessionFuture;
@override
void initState() {
super.initState();
_sessionFuture = widget.authRepository.restoreSession();
}
@override
Widget build(BuildContext context) {
return FutureBuilder<AuthSession?>(
future: _sessionFuture,
builder: (context, snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return const _LoadingView();
}
final session = snapshot.data;
if (session != null) {
return DashboardScreen(
authRepository: widget.authRepository,
addressRepository: widget.addressRepository,
session: session,
savedAddress: null,
enableLiveFeatures: widget.enableLiveFeatures,
);
}
return AuthScreen(
authRepository: widget.authRepository,
addressRepository: widget.addressRepository,
enableLiveFeatures: widget.enableLiveFeatures,
);
},
);
}
}
class _LoadingView extends StatelessWidget {
const _LoadingView();
@override
Widget build(BuildContext context) {
return const Scaffold(
body: Center(
child: CircularProgressIndicator(),
),
);
}
}

6
lib/app_config.dart Normal file
View File

@@ -0,0 +1,6 @@
class AppConfig {
static const String apiBaseUrl = String.fromEnvironment(
'API_BASE_URL',
defaultValue: 'http://10.77.234.29:3000',
);
}

9
lib/main.dart Normal file
View File

@@ -0,0 +1,9 @@
export 'app.dart';
import 'package:flutter/material.dart';
import 'app.dart';
void main() {
runApp(const MyApp());
}

View File

@@ -0,0 +1,19 @@
class AddressEntry {
const AddressEntry({
required this.houseNumber,
required this.colonia,
required this.street,
});
final String houseNumber;
final String colonia;
final String street;
Map<String, dynamic> toJson() {
return <String, dynamic>{
'houseNumber': houseNumber,
'colonia': colonia,
'street': street,
};
}
}

View File

@@ -0,0 +1,22 @@
class AddressRecord {
const AddressRecord({
required this.id,
required this.houseNumber,
required this.colonia,
required this.street,
});
final int id;
final String houseNumber;
final String colonia;
final String street;
factory AddressRecord.fromJson(Map<String, dynamic> json) {
return AddressRecord(
id: (json['id'] as num).toInt(),
houseNumber: json['house_number']?.toString() ?? json['houseNumber']?.toString() ?? '',
colonia: json['colonia']?.toString() ?? '',
street: json['street']?.toString() ?? '',
);
}
}

View File

@@ -0,0 +1,11 @@
class AuthSession {
const AuthSession({
required this.token,
required this.email,
required this.displayName,
});
final String token;
final String email;
final String displayName;
}

View File

@@ -0,0 +1,255 @@
import 'package:flutter/material.dart';
import '../app_config.dart';
import '../models/address_entry.dart';
import '../models/auth_session.dart';
import '../services/auth_repository.dart';
import '../services/address_repository.dart';
import 'dashboard_screen.dart';
class AddressScreen extends StatefulWidget {
const AddressScreen({
super.key,
required this.authRepository,
required this.addressRepository,
required this.session,
this.enableLiveFeatures = true,
});
final AuthRepository authRepository;
final AddressRepository addressRepository;
final AuthSession session;
final bool enableLiveFeatures;
@override
State<AddressScreen> createState() => _AddressScreenState();
}
class _AddressScreenState extends State<AddressScreen> {
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
final TextEditingController _houseNumberController = TextEditingController();
final TextEditingController _coloniaController = TextEditingController();
final TextEditingController _streetController = TextEditingController();
bool _isSaving = false;
String? _errorMessage;
@override
void dispose() {
_houseNumberController.dispose();
_coloniaController.dispose();
_streetController.dispose();
super.dispose();
}
Future<void> _saveAddress() async {
if (!(_formKey.currentState?.validate() ?? false)) {
return;
}
setState(() {
_isSaving = true;
_errorMessage = null;
});
try {
await widget.addressRepository.saveAddress(
session: widget.session,
address: AddressEntry(
houseNumber: _houseNumberController.text.trim(),
colonia: _coloniaController.text.trim(),
street: _streetController.text.trim(),
),
);
if (!mounted) {
return;
}
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(
builder: (_) => DashboardScreen(
authRepository: widget.authRepository,
addressRepository: widget.addressRepository,
session: widget.session,
savedAddress: AddressEntry(
houseNumber: _houseNumberController.text.trim(),
colonia: _coloniaController.text.trim(),
street: _streetController.text.trim(),
),
enableLiveFeatures: widget.enableLiveFeatures,
),
),
(route) => false,
);
} on AddressException catch (error) {
if (!mounted) {
return;
}
setState(() {
_errorMessage = error.message;
});
} catch (_) {
if (!mounted) {
return;
}
setState(() {
_errorMessage = 'No se pudo guardar la dirección. Revisa el backend.';
});
} finally {
if (mounted) {
setState(() {
_isSaving = false;
});
}
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: [Color(0xFFF8FAFC), Color(0xFFE2E8F0), Color(0xFFCCFBF1)],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
),
child: SafeArea(
child: Center(
child: SingleChildScrollView(
padding: const EdgeInsets.all(20),
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 520),
child: Card(
elevation: 12,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(28)),
child: SingleChildScrollView(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Text(
'Dirección',
style: TextStyle(fontSize: 30, fontWeight: FontWeight.w800),
),
const SizedBox(height: 8),
Text(
'Ingresa la dirección de tu casa y se enviará al backend para guardarla en PostgreSQL.',
style: TextStyle(color: Colors.grey.shade700, height: 1.4),
),
const SizedBox(height: 20),
if (_errorMessage != null) ...[
_AddressStatusBanner(message: _errorMessage!),
const SizedBox(height: 16),
],
Form(
key: _formKey,
child: Column(
children: [
TextFormField(
controller: _houseNumberController,
keyboardType: TextInputType.text,
decoration: const InputDecoration(
labelText: 'Número de casa',
prefixIcon: Icon(Icons.home_outlined),
border: OutlineInputBorder(),
),
validator: (value) {
if (value == null || value.trim().isEmpty) {
return 'Ingresa el número de casa';
}
return null;
},
),
const SizedBox(height: 16),
TextFormField(
controller: _coloniaController,
decoration: const InputDecoration(
labelText: 'Colonia',
prefixIcon: Icon(Icons.location_city_outlined),
border: OutlineInputBorder(),
),
validator: (value) {
if (value == null || value.trim().isEmpty) {
return 'Ingresa la colonia';
}
return null;
},
),
const SizedBox(height: 16),
TextFormField(
controller: _streetController,
decoration: const InputDecoration(
labelText: 'Calle',
prefixIcon: Icon(Icons.signpost_outlined),
border: OutlineInputBorder(),
),
validator: (value) {
if (value == null || value.trim().isEmpty) {
return 'Ingresa la calle';
}
return null;
},
),
const SizedBox(height: 20),
SizedBox(
width: double.infinity,
height: 52,
child: FilledButton(
onPressed: _isSaving ? null : _saveAddress,
child: _isSaving
? const SizedBox(
width: 22,
height: 22,
child: CircularProgressIndicator(strokeWidth: 2.2, color: Colors.white),
)
: const Text('Guardar dirección'),
),
),
const SizedBox(height: 12),
Text(
'Base URL configurada: ${AppConfig.apiBaseUrl}',
style: TextStyle(fontSize: 12, color: Colors.grey.shade600),
textAlign: TextAlign.center,
),
],
),
),
],
),
),
),
),
),
),
),
),
);
}
}
class _AddressStatusBanner extends StatelessWidget {
const _AddressStatusBanner({required this.message});
final String message;
@override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
padding: const EdgeInsets.all(14),
decoration: BoxDecoration(
color: const Color(0xFFFEE2E2),
borderRadius: BorderRadius.circular(16),
border: Border.all(color: const Color(0xFFFCA5A5)),
),
child: Text(
message,
style: const TextStyle(color: Color(0xFF991B1B), height: 1.35),
),
);
}
}

View File

@@ -0,0 +1,461 @@
import 'package:flutter/material.dart';
import '../app_config.dart';
import '../models/auth_session.dart';
import '../services/address_repository.dart';
import '../services/auth_repository.dart';
import 'address_screen.dart';
class AuthScreen extends StatefulWidget {
const AuthScreen({
super.key,
required this.authRepository,
required this.addressRepository,
this.enableLiveFeatures = true,
});
final AuthRepository authRepository;
final AddressRepository addressRepository;
final bool enableLiveFeatures;
@override
State<AuthScreen> createState() => _AuthScreenState();
}
class _AuthScreenState extends State<AuthScreen> {
final GlobalKey<FormState> _loginFormKey = GlobalKey<FormState>();
final GlobalKey<FormState> _registerFormKey = GlobalKey<FormState>();
final TextEditingController _loginEmailController = TextEditingController();
final TextEditingController _loginPasswordController = TextEditingController();
final TextEditingController _registerNameController = TextEditingController();
final TextEditingController _registerEmailController = TextEditingController();
final TextEditingController _registerPasswordController = TextEditingController();
final TextEditingController _registerConfirmPasswordController = TextEditingController();
bool _isLoading = false;
String? _errorMessage;
@override
void dispose() {
_loginEmailController.dispose();
_loginPasswordController.dispose();
_registerNameController.dispose();
_registerEmailController.dispose();
_registerPasswordController.dispose();
_registerConfirmPasswordController.dispose();
super.dispose();
}
Future<void> _signIn() async {
if (!(_loginFormKey.currentState?.validate() ?? false)) {
return;
}
await _submit(() {
return widget.authRepository.signIn(
email: _loginEmailController.text.trim(),
password: _loginPasswordController.text,
);
});
}
Future<void> _signUp() async {
if (!(_registerFormKey.currentState?.validate() ?? false)) {
return;
}
await _submit(() {
return widget.authRepository.signUp(
name: _registerNameController.text.trim(),
email: _registerEmailController.text.trim(),
password: _registerPasswordController.text,
);
});
}
Future<void> _submit(Future<AuthSession> Function() action) async {
setState(() {
_isLoading = true;
_errorMessage = null;
});
try {
final session = await action();
if (!mounted) {
return;
}
Navigator.of(context).pushReplacement(
MaterialPageRoute(
builder: (_) => AddressScreen(
authRepository: widget.authRepository,
addressRepository: widget.addressRepository,
session: session,
enableLiveFeatures: widget.enableLiveFeatures,
),
),
);
} on AuthException catch (error) {
if (!mounted) {
return;
}
setState(() {
_errorMessage = error.message;
});
} catch (_) {
if (!mounted) {
return;
}
setState(() {
_errorMessage = 'No se pudo completar la operación. Verifica el backend y vuelve a intentar.';
});
} finally {
if (mounted) {
setState(() {
_isLoading = false;
});
}
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: [Color(0xFF06141B), Color(0xFF0F766E), Color(0xFFE2E8F0)],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
),
child: SafeArea(
child: Center(
child: SingleChildScrollView(
padding: const EdgeInsets.all(20),
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 440),
child: Card(
elevation: 18,
color: Colors.white.withValues(alpha: 0.94),
shadowColor: Colors.black26,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(28)),
child: SingleChildScrollView(
padding: const EdgeInsets.all(24),
child: DefaultTabController(
length: 2,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: 72,
height: 72,
decoration: BoxDecoration(
color: const Color(0xFF0F766E).withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(20),
),
child: const Icon(Icons.lock_outline, size: 36, color: Color(0xFF0F766E)),
),
const SizedBox(height: 20),
const Text(
'Bienvenido',
style: TextStyle(fontSize: 30, fontWeight: FontWeight.w800),
),
const SizedBox(height: 8),
Text(
'Inicia sesión o crea una cuenta para continuar. Luego irás a la pantalla Dirección.',
style: TextStyle(color: Colors.grey.shade700, height: 1.4),
),
const SizedBox(height: 20),
Container(
decoration: BoxDecoration(
color: const Color(0xFFF1F5F9),
borderRadius: BorderRadius.circular(16),
),
child: TabBar(
onTap: (_) {
setState(() {
_errorMessage = null;
});
},
indicatorSize: TabBarIndicatorSize.tab,
dividerColor: Colors.transparent,
indicator: BoxDecoration(
color: const Color(0xFF0F766E),
borderRadius: BorderRadius.circular(16),
),
labelColor: Colors.white,
unselectedLabelColor: Colors.grey.shade700,
tabs: const [
Tab(text: 'Entrar'),
Tab(text: 'Crear cuenta'),
],
),
),
const SizedBox(height: 20),
if (_errorMessage != null) ...[
_AuthStatusBanner(message: _errorMessage!),
const SizedBox(height: 16),
],
SizedBox(
height: 200,
child: TabBarView(
children: [
_LoginForm(
formKey: _loginFormKey,
emailController: _loginEmailController,
passwordController: _loginPasswordController,
onSubmit: _signIn,
isLoading: _isLoading,
),
_RegisterForm(
formKey: _registerFormKey,
nameController: _registerNameController,
emailController: _registerEmailController,
passwordController: _registerPasswordController,
confirmPasswordController: _registerConfirmPasswordController,
onSubmit: _signUp,
isLoading: _isLoading,
),
],
),
),
const SizedBox(height: 12),
Text(
'Base URL configurada: ${AppConfig.apiBaseUrl}',
style: TextStyle(fontSize: 12, color: Colors.grey.shade600),
textAlign: TextAlign.center,
),
],
),
),
),
),
),
),
),
),
),
);
}
}
class _LoginForm extends StatelessWidget {
const _LoginForm({
required this.formKey,
required this.emailController,
required this.passwordController,
required this.onSubmit,
required this.isLoading,
});
final GlobalKey<FormState> formKey;
final TextEditingController emailController;
final TextEditingController passwordController;
final Future<void> Function() onSubmit;
final bool isLoading;
@override
Widget build(BuildContext context) {
return Form(
key: formKey,
child: Column(
children: [
TextFormField(
controller: emailController,
keyboardType: TextInputType.emailAddress,
decoration: const InputDecoration(
labelText: 'Correo electrónico',
prefixIcon: Icon(Icons.email_outlined),
border: OutlineInputBorder(),
),
validator: (value) {
if (value == null || value.trim().isEmpty) {
return 'Ingresa tu correo';
}
if (!value.contains('@')) {
return 'Ingresa un correo válido';
}
return null;
},
),
const SizedBox(height: 16),
TextFormField(
controller: passwordController,
obscureText: true,
decoration: const InputDecoration(
labelText: 'Contraseña',
prefixIcon: Icon(Icons.lock_outline),
border: OutlineInputBorder(),
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Ingresa tu contraseña';
}
if (value.length < 6) {
return 'Usa al menos 6 caracteres';
}
return null;
},
),
const SizedBox(height: 20),
SizedBox(
width: double.infinity,
height: 52,
child: FilledButton(
onPressed: isLoading ? null : onSubmit,
child: isLoading
? const SizedBox(
width: 22,
height: 22,
child: CircularProgressIndicator(strokeWidth: 2.2, color: Colors.white),
)
: const Text('Ingresar'),
),
),
],
),
);
}
}
class _RegisterForm extends StatelessWidget {
const _RegisterForm({
required this.formKey,
required this.nameController,
required this.emailController,
required this.passwordController,
required this.confirmPasswordController,
required this.onSubmit,
required this.isLoading,
});
final GlobalKey<FormState> formKey;
final TextEditingController nameController;
final TextEditingController emailController;
final TextEditingController passwordController;
final TextEditingController confirmPasswordController;
final Future<void> Function() onSubmit;
final bool isLoading;
@override
Widget build(BuildContext context) {
return Form(
key: formKey,
child: ListView(
children: [
TextFormField(
controller: nameController,
textCapitalization: TextCapitalization.words,
decoration: const InputDecoration(
labelText: 'Nombre',
prefixIcon: Icon(Icons.person_outline),
border: OutlineInputBorder(),
),
validator: (value) {
if (value == null || value.trim().isEmpty) {
return 'Ingresa tu nombre';
}
return null;
},
),
const SizedBox(height: 16),
TextFormField(
controller: emailController,
keyboardType: TextInputType.emailAddress,
decoration: const InputDecoration(
labelText: 'Correo electrónico',
prefixIcon: Icon(Icons.email_outlined),
border: OutlineInputBorder(),
),
validator: (value) {
if (value == null || value.trim().isEmpty) {
return 'Ingresa tu correo';
}
if (!value.contains('@')) {
return 'Ingresa un correo válido';
}
return null;
},
),
const SizedBox(height: 16),
TextFormField(
controller: passwordController,
obscureText: true,
decoration: const InputDecoration(
labelText: 'Contraseña',
prefixIcon: Icon(Icons.lock_outline),
border: OutlineInputBorder(),
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Ingresa una contraseña';
}
if (value.length < 6) {
return 'Usa al menos 6 caracteres';
}
return null;
},
),
const SizedBox(height: 16),
TextFormField(
controller: confirmPasswordController,
obscureText: true,
decoration: const InputDecoration(
labelText: 'Confirmar contraseña',
prefixIcon: Icon(Icons.lock_reset_outlined),
border: OutlineInputBorder(),
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Confirma tu contraseña';
}
if (value != passwordController.text) {
return 'Las contraseñas no coinciden';
}
return null;
},
),
const SizedBox(height: 20),
SizedBox(
width: double.infinity,
height: 52,
child: FilledButton(
onPressed: isLoading ? null : onSubmit,
child: isLoading
? const SizedBox(
width: 22,
height: 22,
child: CircularProgressIndicator(strokeWidth: 2.2, color: Colors.white),
)
: const Text('Registrarme'),
),
),
],
),
);
}
}
class _AuthStatusBanner extends StatelessWidget {
const _AuthStatusBanner({required this.message});
final String message;
@override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
padding: const EdgeInsets.all(14),
decoration: BoxDecoration(
color: const Color(0xFFFEE2E2),
borderRadius: BorderRadius.circular(16),
border: Border.all(color: const Color(0xFFFCA5A5)),
),
child: Text(
message,
style: const TextStyle(color: Color(0xFF991B1B), height: 1.35),
),
);
}
}

View File

@@ -0,0 +1,943 @@
import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:geolocator/geolocator.dart';
import 'package:latlong2/latlong.dart';
import 'package:table_calendar/table_calendar.dart';
import '../models/address_entry.dart';
import '../models/address_record.dart';
import '../models/auth_session.dart';
import '../services/address_repository.dart';
import '../services/auth_repository.dart';
import 'auth_screen.dart';
class DashboardScreen extends StatefulWidget {
const DashboardScreen({
super.key,
required this.authRepository,
required this.addressRepository,
required this.session,
this.savedAddress,
this.enableLiveFeatures = true,
});
final AuthRepository authRepository;
final AddressRepository addressRepository;
final AuthSession session;
final AddressEntry? savedAddress;
final bool enableLiveFeatures;
@override
State<DashboardScreen> createState() => _DashboardScreenState();
}
class _DashboardScreenState extends State<DashboardScreen> {
final MapController _mapController = MapController();
final TextEditingController _calendarNoteController = TextEditingController();
final TextEditingController _newHouseNumberController = TextEditingController();
final TextEditingController _newColoniaController = TextEditingController();
final TextEditingController _newStreetController = TextEditingController();
final List<_AppNotification> _notifications = <_AppNotification>[];
final Map<DateTime, String> _calendarNotes = <DateTime, String>{};
final Random _random = Random();
int _selectedIndex = 0;
LatLng _center = const LatLng(19.4326, -99.1332);
bool _isLoadingLocation = true;
bool _showLiveFeatures = true;
String? _locationError;
Timer? _truckTimer;
LatLng? _truckPosition;
bool _truckVisible = false;
bool _loadingAddresses = true;
String? _addressesError;
List<AddressRecord> _addresses = <AddressRecord>[];
DateTime _focusedDay = DateTime.now();
DateTime? _selectedDay;
CalendarFormat _calendarFormat = CalendarFormat.month;
@override
void initState() {
super.initState();
_showLiveFeatures = widget.enableLiveFeatures;
if (!_showLiveFeatures) {
_isLoadingLocation = false;
_loadingAddresses = false;
_seedTruckSimulation();
return;
}
unawaited(_loadLocation());
unawaited(_loadAddresses());
_startTruckSimulation();
}
@override
void dispose() {
_truckTimer?.cancel();
_calendarNoteController.dispose();
_newHouseNumberController.dispose();
_newColoniaController.dispose();
_newStreetController.dispose();
super.dispose();
}
DateTime _normalizeDay(DateTime day) => DateTime(day.year, day.month, day.day);
void _addNotification(String message) {
if (!mounted) {
return;
}
setState(() {
_notifications.insert(0, _AppNotification(message: message, timestamp: DateTime.now()));
});
}
void _seedTruckSimulation() {
final visible = _random.nextBool();
_truckVisible = visible;
_truckPosition = _truckOffsetFromCenter(_random.nextDouble() * 20.0);
_notifications.add(
_AppNotification(
message: visible ? 'El camión de basura apareció cerca de tu ubicación.' : 'El camión de basura está fuera de rango.',
timestamp: DateTime.now(),
),
);
}
Future<void> _loadLocation() async {
try {
final permission = await Geolocator.checkPermission();
var currentPermission = permission;
if (currentPermission == LocationPermission.denied) {
currentPermission = await Geolocator.requestPermission();
}
if (currentPermission == LocationPermission.denied || currentPermission == LocationPermission.deniedForever) {
if (!mounted) {
return;
}
setState(() {
_locationError = 'Permiso de ubicación no concedido. Mostrando mapa por defecto.';
_isLoadingLocation = false;
});
return;
}
final position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
final newCenter = LatLng(position.latitude, position.longitude);
if (!mounted) {
return;
}
setState(() {
_center = newCenter;
_isLoadingLocation = false;
_locationError = null;
});
_mapController.move(newCenter, 15);
} catch (_) {
if (!mounted) {
return;
}
setState(() {
_locationError = 'No se pudo obtener la ubicación actual. Se usó una referencia por defecto.';
_isLoadingLocation = false;
});
}
}
Future<void> _loadAddresses() async {
try {
final addresses = await widget.addressRepository.getMyAddresses(session: widget.session);
if (!mounted) {
return;
}
setState(() {
_addresses = addresses;
_loadingAddresses = false;
_addressesError = null;
});
} catch (error) {
if (!mounted) {
return;
}
setState(() {
_addressesError = error.toString();
_loadingAddresses = false;
});
}
}
void _startTruckSimulation() {
_truckTimer?.cancel();
_truckTimer = Timer.periodic(const Duration(seconds: 4), (_) {
final distanceMeters = _random.nextDouble() * 40.0;
final newTruckPosition = _truckOffsetFromCenter(distanceMeters);
final wasVisible = _truckVisible;
final isVisible = distanceMeters <= 20.0;
if (!mounted) {
return;
}
setState(() {
_truckPosition = newTruckPosition;
_truckVisible = isVisible;
});
if (isVisible != wasVisible) {
_addNotification(
isVisible
? 'El camión de basura apareció a ${distanceMeters.toStringAsFixed(1)} m.'
: 'El camión de basura salió del rango visible.',
);
}
});
}
LatLng _truckOffsetFromCenter(double distanceMeters) {
final angle = _random.nextDouble() * 2 * pi;
final metersPerDegreeLat = 111320.0;
final metersPerDegreeLng = 111320.0 * cos(_center.latitude * pi / 180.0).abs().clamp(0.2, 1.0);
final deltaLat = (distanceMeters * cos(angle)) / metersPerDegreeLat;
final deltaLng = (distanceMeters * sin(angle)) / metersPerDegreeLng;
return LatLng(_center.latitude + deltaLat, _center.longitude + deltaLng);
}
Future<void> _logOut(BuildContext context) async {
await widget.authRepository.signOut();
if (!context.mounted) {
return;
}
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(
builder: (_) => AuthScreen(
authRepository: widget.authRepository,
addressRepository: widget.addressRepository,
),
),
(route) => false,
);
}
Future<void> _saveCalendarNote() async {
final note = _calendarNoteController.text.trim();
if (note.isEmpty || _selectedDay == null) {
return;
}
final normalizedDay = _normalizeDay(_selectedDay!);
setState(() {
_calendarNotes[normalizedDay] = note;
});
_calendarNoteController.clear();
_addNotification('Se guardó texto en el calendario para ${_selectedDay!.day}/${_selectedDay!.month}.');
}
Future<void> _saveNewAddress() async {
if (_newHouseNumberController.text.trim().isEmpty ||
_newColoniaController.text.trim().isEmpty ||
_newStreetController.text.trim().isEmpty) {
_addNotification('Completa la nueva dirección antes de guardarla.');
return;
}
final newAddress = AddressEntry(
houseNumber: _newHouseNumberController.text.trim(),
colonia: _newColoniaController.text.trim(),
street: _newStreetController.text.trim(),
);
try {
await widget.addressRepository.saveAddress(session: widget.session, address: newAddress);
if (!mounted) {
return;
}
setState(() {
_addresses = <AddressRecord>[
AddressRecord(
id: DateTime.now().millisecondsSinceEpoch,
houseNumber: newAddress.houseNumber,
colonia: newAddress.colonia,
street: newAddress.street,
),
..._addresses,
];
});
_newHouseNumberController.clear();
_newColoniaController.clear();
_newStreetController.clear();
_addNotification('Se agregó una nueva dirección a tu perfil.');
} catch (error) {
_addNotification('No se pudo guardar la nueva dirección: $error');
}
}
@override
Widget build(BuildContext context) {
final pages = <Widget>[
_MapSection(
center: _center,
truckPosition: _truckPosition,
truckVisible: _truckVisible,
isLoadingLocation: _isLoadingLocation,
locationError: _locationError,
mapController: _mapController,
showTiles: _showLiveFeatures,
address: widget.savedAddress,
),
_CalendarSection(
focusedDay: _focusedDay,
selectedDay: _selectedDay,
calendarFormat: _calendarFormat,
notes: _calendarNotes,
noteController: _calendarNoteController,
onSelectedDay: (day, focusedDay) {
setState(() {
_selectedDay = day;
_focusedDay = focusedDay;
});
},
onFormatChanged: (format) {
setState(() {
_calendarFormat = format;
});
},
onPageChanged: (focusedDay) {
_focusedDay = focusedDay;
},
onSaveNote: _saveCalendarNote,
),
_NotificationsSection(notifications: _notifications),
_DataSection(
session: widget.session,
loadingAddresses: _loadingAddresses,
addressesError: _addressesError,
addresses: _addresses,
houseNumberController: _newHouseNumberController,
coloniaController: _newColoniaController,
streetController: _newStreetController,
onSaveAddress: _saveNewAddress,
),
];
return Scaffold(
body: SafeArea(
child: Column(
children: [
_UserHeader(
session: widget.session,
onLogout: () => _logOut(context),
),
Expanded(
child: IndexedStack(
index: _selectedIndex,
children: pages,
),
),
],
),
),
bottomNavigationBar: NavigationBar(
selectedIndex: _selectedIndex,
onDestinationSelected: (index) {
setState(() {
_selectedIndex = index;
});
},
destinations: const [
NavigationDestination(icon: Icon(Icons.my_location_outlined), selectedIcon: Icon(Icons.my_location), label: 'Mapa'),
NavigationDestination(icon: Icon(Icons.calendar_month_outlined), selectedIcon: Icon(Icons.calendar_month), label: 'Calendario'),
NavigationDestination(icon: Icon(Icons.notifications_outlined), selectedIcon: Icon(Icons.notifications), label: 'Avisos'),
NavigationDestination(icon: Icon(Icons.input_outlined), selectedIcon: Icon(Icons.input), label: 'Datos'),
],
),
);
}
}
class _UserHeader extends StatelessWidget {
const _UserHeader({required this.session, required this.onLogout});
final AuthSession session;
final VoidCallback onLogout;
@override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [Colors.teal.shade900, Colors.teal.shade700],
),
),
child: Row(
children: [
CircleAvatar(
radius: 24,
backgroundColor: Colors.white.withValues(alpha: 0.18),
child: Text(
session.displayName.isNotEmpty ? session.displayName[0].toUpperCase() : 'U',
style: const TextStyle(color: Colors.white, fontWeight: FontWeight.w800),
),
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(session.displayName, style: const TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.w700)),
Text(session.email, style: TextStyle(color: Colors.white.withValues(alpha: 0.85))),
],
),
),
IconButton(
onPressed: onLogout,
icon: const Icon(Icons.logout, color: Colors.white),
tooltip: 'Cerrar sesión',
),
],
),
);
}
}
class _MapSection extends StatelessWidget {
const _MapSection({
required this.center,
required this.truckPosition,
required this.truckVisible,
required this.isLoadingLocation,
required this.locationError,
required this.mapController,
required this.showTiles,
required this.address,
});
final LatLng center;
final LatLng? truckPosition;
final bool truckVisible;
final bool isLoadingLocation;
final String? locationError;
final MapController mapController;
final bool showTiles;
final AddressEntry? address;
@override
Widget build(BuildContext context) {
final markers = <Marker>[
Marker(
width: 60,
height: 60,
point: center,
child: const Icon(Icons.person_pin_circle, size: 56, color: Colors.blue),
),
if (truckVisible && truckPosition != null)
Marker(
width: 60,
height: 60,
point: truckPosition!,
child: const Icon(Icons.local_shipping, size: 50, color: Colors.red),
),
];
return Container(
color: const Color(0xFFF8FAFC),
child: Column(
children: [
if (locationError != null)
Padding(
padding: const EdgeInsets.all(12),
child: _NoticeBanner(message: locationError!),
),
Expanded(
child: Center(
child: Padding(
padding: const EdgeInsets.all(16),
child: ClipRRect(
borderRadius: BorderRadius.circular(24),
child: Stack(
children: [
if (showTiles)
FlutterMap(
mapController: mapController,
options: MapOptions(
initialCenter: center,
initialZoom: 15,
interactionOptions: const InteractionOptions(flags: InteractiveFlag.all),
),
children: [
TileLayer(
urlTemplate: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
userAgentPackageName: 'flutter_application_1',
),
MarkerLayer(markers: markers),
],
)
else
_MapPlaceholder(
center: center,
truckVisible: truckVisible,
truckPosition: truckPosition,
),
Positioned(
top: 16,
left: 16,
right: 16,
child: Card(
elevation: 8,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
child: Padding(
padding: const EdgeInsets.all(14),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text('Mapa y camión', style: Theme.of(context).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.w800)),
const SizedBox(height: 4),
Text(
address == null
? 'No hay una dirección guardada todavía.'
: 'Dirección: ${address!.houseNumber}, ${address!.colonia}, ${address!.street}',
style: TextStyle(color: Colors.grey.shade700),
),
const SizedBox(height: 4),
Text(
truckVisible ? 'El camión está dentro de 20 m.' : 'El camión está fuera de rango.',
style: const TextStyle(fontWeight: FontWeight.w700),
),
],
),
),
),
),
if (isLoadingLocation)
const Center(
child: CircularProgressIndicator(),
),
],
),
),
),
),
),
],
),
);
}
}
class _MapPlaceholder extends StatelessWidget {
const _MapPlaceholder({
required this.center,
required this.truckVisible,
required this.truckPosition,
});
final LatLng center;
final bool truckVisible;
final LatLng? truckPosition;
@override
Widget build(BuildContext context) {
return Container(
color: const Color(0xFFE2E8F0),
alignment: Alignment.center,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.map_outlined, size: 72, color: Colors.teal),
const SizedBox(height: 12),
const Text('Mapa centrado en tu ubicación', style: TextStyle(fontWeight: FontWeight.w700)),
const SizedBox(height: 4),
Text('Lat: ${center.latitude.toStringAsFixed(5)}, Lng: ${center.longitude.toStringAsFixed(5)}'),
const SizedBox(height: 12),
Text(
truckVisible && truckPosition != null
? 'Camión visible cerca de ti'
: 'Camión fuera del rango de 20 m',
style: const TextStyle(fontWeight: FontWeight.w700),
),
],
),
);
}
}
class _CalendarSection extends StatelessWidget {
const _CalendarSection({
required this.focusedDay,
required this.selectedDay,
required this.calendarFormat,
required this.notes,
required this.noteController,
required this.onSelectedDay,
required this.onFormatChanged,
required this.onPageChanged,
required this.onSaveNote,
});
final DateTime focusedDay;
final DateTime? selectedDay;
final CalendarFormat calendarFormat;
final Map<DateTime, String> notes;
final TextEditingController noteController;
final void Function(DateTime day, DateTime focusedDay) onSelectedDay;
final void Function(CalendarFormat format) onFormatChanged;
final void Function(DateTime focusedDay) onPageChanged;
final Future<void> Function() onSaveNote;
DateTime _normalizeDay(DateTime day) => DateTime(day.year, day.month, day.day);
@override
Widget build(BuildContext context) {
final selectedNormalized = selectedDay == null ? null : _normalizeDay(selectedDay!);
return Container(
color: const Color(0xFFF8FAFC),
padding: const EdgeInsets.all(16),
child: Column(
children: [
Card(
elevation: 8,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(24)),
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
children: [
TableCalendar<String>(
firstDay: DateTime.utc(2020, 1, 1),
lastDay: DateTime.utc(2035, 12, 31),
focusedDay: focusedDay,
calendarFormat: calendarFormat,
selectedDayPredicate: (day) => isSameDay(selectedDay, day),
eventLoader: (day) => notes.containsKey(_normalizeDay(day)) ? <String>[notes[_normalizeDay(day)]!] : <String>[],
onDaySelected: onSelectedDay,
onFormatChanged: onFormatChanged,
onPageChanged: onPageChanged,
calendarBuilders: CalendarBuilders(
defaultBuilder: (context, day, focusedDay) {
final note = notes[_normalizeDay(day)];
if (note == null) {
return null;
}
return _CalendarDayCell(day: day, note: note, selected: false);
},
selectedBuilder: (context, day, focusedDay) {
final note = notes[_normalizeDay(day)];
return _CalendarDayCell(day: day, note: note, selected: true);
},
todayBuilder: (context, day, focusedDay) {
final note = notes[_normalizeDay(day)];
return _CalendarDayCell(day: day, note: note, selected: false, today: true);
},
),
),
const SizedBox(height: 12),
TextField(
controller: noteController,
maxLines: 2,
decoration: const InputDecoration(
labelText: 'Texto del día',
border: OutlineInputBorder(),
),
),
const SizedBox(height: 12),
SizedBox(
width: double.infinity,
child: FilledButton(
onPressed: onSaveNote,
child: const Text('Guardar texto y resaltar casilla'),
),
),
const SizedBox(height: 12),
Text(
selectedNormalized == null
? 'Selecciona un día para escribir.'
: 'Día seleccionado: ${selectedNormalized.day}/${selectedNormalized.month}/${selectedNormalized.year}',
style: TextStyle(color: Colors.grey.shade700),
),
],
),
),
),
],
),
);
}
}
class _CalendarDayCell extends StatelessWidget {
const _CalendarDayCell({
required this.day,
required this.note,
required this.selected,
this.today = false,
});
final DateTime day;
final String? note;
final bool selected;
final bool today;
@override
Widget build(BuildContext context) {
final backgroundColor = selected
? Colors.teal.shade700
: today
? Colors.teal.shade100
: Colors.white;
return Container(
margin: const EdgeInsets.all(4),
padding: const EdgeInsets.all(6),
decoration: BoxDecoration(
color: backgroundColor,
borderRadius: BorderRadius.circular(14),
border: Border.all(color: note == null ? Colors.grey.shade300 : Colors.teal),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'${day.day}',
style: TextStyle(
color: selected ? Colors.white : Colors.black,
fontWeight: FontWeight.w800,
),
),
if (note != null) ...[
const SizedBox(height: 4),
Text(
note!,
maxLines: 2,
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 10,
color: selected ? Colors.white : Colors.teal.shade900,
fontWeight: FontWeight.w700,
),
),
],
],
),
);
}
}
class _NotificationsSection extends StatelessWidget {
const _NotificationsSection({required this.notifications});
final List<_AppNotification> notifications;
@override
Widget build(BuildContext context) {
return Container(
color: const Color(0xFFF8FAFC),
child: ListView.builder(
padding: const EdgeInsets.all(16),
itemCount: notifications.isEmpty ? 1 : notifications.length,
itemBuilder: (context, index) {
if (notifications.isEmpty) {
return const Center(
child: Padding(
padding: EdgeInsets.only(top: 48),
child: Text('Aquí aparecerán las notificaciones.'),
),
);
}
final notification = notifications[index];
return Card(
margin: const EdgeInsets.only(bottom: 12),
child: ListTile(
leading: const Icon(Icons.notifications_active, color: Colors.teal),
title: Text(notification.message),
subtitle: Text(
'${notification.timestamp.hour.toString().padLeft(2, '0')}:${notification.timestamp.minute.toString().padLeft(2, '0')}',
),
),
);
},
),
);
}
}
class _DataSection extends StatelessWidget {
const _DataSection({
required this.session,
required this.loadingAddresses,
required this.addressesError,
required this.addresses,
required this.houseNumberController,
required this.coloniaController,
required this.streetController,
required this.onSaveAddress,
});
final AuthSession session;
final bool loadingAddresses;
final String? addressesError;
final List<AddressRecord> addresses;
final TextEditingController houseNumberController;
final TextEditingController coloniaController;
final TextEditingController streetController;
final Future<void> Function() onSaveAddress;
@override
Widget build(BuildContext context) {
return Container(
color: const Color(0xFFF8FAFC),
padding: const EdgeInsets.all(16),
child: ListView(
children: [
Card(
elevation: 8,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(24)),
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Datos de la cuenta', style: Theme.of(context).textTheme.titleLarge?.copyWith(fontWeight: FontWeight.w800)),
const SizedBox(height: 12),
_ProfileRow(label: 'Nombre', value: session.displayName),
_ProfileRow(label: 'Correo', value: session.email),
],
),
),
),
const SizedBox(height: 16),
Card(
elevation: 8,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(24)),
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Agregar otra dirección', style: Theme.of(context).textTheme.titleLarge?.copyWith(fontWeight: FontWeight.w800)),
const SizedBox(height: 12),
TextField(
controller: houseNumberController,
decoration: const InputDecoration(labelText: 'Número de casa', border: OutlineInputBorder()),
),
const SizedBox(height: 12),
TextField(
controller: coloniaController,
decoration: const InputDecoration(labelText: 'Colonia', border: OutlineInputBorder()),
),
const SizedBox(height: 12),
TextField(
controller: streetController,
decoration: const InputDecoration(labelText: 'Calle', border: OutlineInputBorder()),
),
const SizedBox(height: 12),
SizedBox(
width: double.infinity,
child: FilledButton.icon(
onPressed: onSaveAddress,
icon: const Icon(Icons.add_location_alt_outlined),
label: const Text('Guardar nueva dirección'),
),
),
],
),
),
),
const SizedBox(height: 16),
Card(
elevation: 8,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(24)),
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Direcciones registradas', style: Theme.of(context).textTheme.titleLarge?.copyWith(fontWeight: FontWeight.w800)),
const SizedBox(height: 12),
if (loadingAddresses) const Center(child: CircularProgressIndicator()),
if (addressesError != null) Text(addressesError!, style: const TextStyle(color: Colors.red)),
if (!loadingAddresses && addresses.isEmpty)
const Text('Todavía no hay direcciones registradas.'),
if (addresses.isNotEmpty)
...addresses.map(
(address) => Card(
margin: const EdgeInsets.only(bottom: 12),
child: ListTile(
leading: const Icon(Icons.home_work_outlined, color: Colors.teal),
title: Text('Casa ${address.houseNumber}'),
subtitle: Text('${address.colonia}, ${address.street}'),
),
),
),
],
),
),
),
],
),
);
}
}
class _ProfileRow extends StatelessWidget {
const _ProfileRow({required this.label, required this.value});
final String label;
final String value;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(width: 90, child: Text(label, style: const TextStyle(fontWeight: FontWeight.w700))),
Expanded(child: Text(value)),
],
),
);
}
}
class _AppNotification {
_AppNotification({required this.message, required this.timestamp});
final String message;
final DateTime timestamp;
}
class _NoticeBanner extends StatelessWidget {
const _NoticeBanner({required this.message});
final String message;
@override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
padding: const EdgeInsets.all(14),
decoration: BoxDecoration(
color: const Color(0xFFE0F2FE),
borderRadius: BorderRadius.circular(16),
border: Border.all(color: const Color(0xFF7DD3FC)),
),
child: Text(message, style: const TextStyle(color: Color(0xFF075985))),
);
}
}

View File

@@ -0,0 +1,155 @@
import 'package:flutter/material.dart';
import '../models/address_entry.dart';
import '../models/auth_session.dart';
import '../services/auth_repository.dart';
import '../services/address_repository.dart';
import 'auth_screen.dart';
class HomeScreen extends StatelessWidget {
const HomeScreen({
super.key,
required this.authRepository,
required this.addressRepository,
required this.session,
this.savedAddress,
});
final AuthRepository authRepository;
final AddressRepository addressRepository;
final AuthSession session;
final AddressEntry? savedAddress;
Future<void> _logOut(BuildContext context) async {
await authRepository.signOut();
if (!context.mounted) {
return;
}
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(
builder: (_) => AuthScreen(
authRepository: authRepository,
addressRepository: addressRepository,
),
),
(route) => false,
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: [Color(0xFFF8FAFC), Color(0xFFE2E8F0), Color(0xFFCCFBF1)],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
),
child: SafeArea(
child: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 520),
child: Padding(
padding: const EdgeInsets.all(20),
child: Card(
elevation: 12,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(28)),
child: SingleChildScrollView(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
CircleAvatar(
radius: 34,
backgroundColor: const Color(0xFF0F766E).withValues(alpha: 0.12),
child: Text(
session.displayName.isNotEmpty ? session.displayName[0].toUpperCase() : 'U',
style: const TextStyle(
fontSize: 28,
fontWeight: FontWeight.w800,
color: Color(0xFF0F766E),
),
),
),
const SizedBox(height: 16),
Text(
'Hola, ${session.displayName}',
style: const TextStyle(fontSize: 28, fontWeight: FontWeight.w800),
),
const SizedBox(height: 8),
Text(
session.email,
style: TextStyle(color: Colors.grey.shade700),
),
const SizedBox(height: 20),
_InfoTile(
icon: Icons.dns_outlined,
title: 'Dirección guardada',
subtitle: savedAddress == null
? 'Todavía no hay una dirección registrada para esta sesión.'
: 'Casa ${savedAddress!.houseNumber}, Colonia ${savedAddress!.colonia}, Calle ${savedAddress!.street}',
),
const SizedBox(height: 12),
_InfoTile(
icon: Icons.storage_outlined,
title: 'Persistencia en PostgreSQL',
subtitle: 'La dirección se envió al backend con el token de sesión para almacenarla en la base de datos.',
),
const SizedBox(height: 24),
FilledButton.icon(
onPressed: () => _logOut(context),
icon: const Icon(Icons.logout),
label: const Text('Cerrar sesión'),
),
],
),
),
),
),
),
),
),
),
);
}
}
class _InfoTile extends StatelessWidget {
const _InfoTile({required this.icon, required this.title, required this.subtitle});
final IconData icon;
final String title;
final String subtitle;
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: const Color(0xFFF8FAFC),
borderRadius: BorderRadius.circular(18),
border: Border.all(color: const Color(0xFFE2E8F0)),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(icon, color: const Color(0xFF0F766E)),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(title, style: const TextStyle(fontWeight: FontWeight.w700)),
const SizedBox(height: 4),
Text(subtitle, style: TextStyle(color: Colors.grey.shade700, height: 1.35)),
],
),
),
],
),
);
}
}

View File

@@ -0,0 +1,96 @@
import 'dart:convert';
import 'package:http/http.dart' as http;
import '../app_config.dart';
import '../models/address_entry.dart';
import '../models/address_record.dart';
import '../models/auth_session.dart';
abstract class AddressRepository {
Future<void> saveAddress({
required AuthSession session,
required AddressEntry address,
});
Future<List<AddressRecord>> getMyAddresses({required AuthSession session});
}
class HttpAddressRepository implements AddressRepository {
const HttpAddressRepository({http.Client? client}) : _client = client;
final http.Client? _client;
@override
Future<void> saveAddress({
required AuthSession session,
required AddressEntry address,
}) async {
final uri = Uri.parse('${AppConfig.apiBaseUrl}/addresses');
late final http.Response response;
try {
response = await (_client ?? http.Client()).post(
uri,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer ${session.token}',
},
body: jsonEncode(address.toJson()),
);
} catch (_) {
throw AddressException(
'No se pudo conectar con el backend en ${AppConfig.apiBaseUrl}.',
);
}
if (response.statusCode < 200 || response.statusCode >= 300) {
final payload = jsonDecode(response.body);
final message = payload['message']?.toString() ?? 'Error al guardar la dirección.';
throw AddressException(message);
}
}
@override
Future<List<AddressRecord>> getMyAddresses({required AuthSession session}) async {
final uri = Uri.parse('${AppConfig.apiBaseUrl}/addresses/me');
late final http.Response response;
try {
response = await (_client ?? http.Client()).get(
uri,
headers: {
'Accept': 'application/json',
'Authorization': 'Bearer ${session.token}',
},
);
} catch (_) {
throw AddressException(
'No se pudo conectar con el backend en ${AppConfig.apiBaseUrl}.',
);
}
if (response.statusCode < 200 || response.statusCode >= 300) {
final payload = jsonDecode(response.body);
final message = payload['message']?.toString() ?? 'Error al obtener las direcciones.';
throw AddressException(message);
}
final decoded = jsonDecode(response.body);
if (decoded is! List) {
return <AddressRecord>[];
}
return decoded
.whereType<Map<String, dynamic>>()
.map(AddressRecord.fromJson)
.toList(growable: false);
}
}
class AddressException implements Exception {
AddressException(this.message);
final String message;
@override
String toString() => message;
}

View File

@@ -0,0 +1,132 @@
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import '../app_config.dart';
import '../models/auth_session.dart';
abstract class AuthRepository {
Future<AuthSession?> restoreSession();
Future<AuthSession> signIn({required String email, required String password});
Future<AuthSession> signUp({required String name, required String email, required String password});
Future<void> signOut();
}
class HttpAuthRepository implements AuthRepository {
const HttpAuthRepository({http.Client? client}) : _client = client;
final http.Client? _client;
static const String _tokenKey = 'auth_token';
static const String _emailKey = 'auth_email';
static const String _nameKey = 'auth_name';
@override
Future<AuthSession?> restoreSession() async {
final prefs = await SharedPreferences.getInstance();
final token = prefs.getString(_tokenKey);
final email = prefs.getString(_emailKey);
final name = prefs.getString(_nameKey);
if (token == null || email == null) {
return null;
}
return AuthSession(token: token, email: email, displayName: name ?? email);
}
@override
Future<AuthSession> signIn({required String email, required String password}) {
return _authenticate(
endpoint: '/auth/login',
body: <String, dynamic>{'email': email, 'password': password},
);
}
@override
Future<AuthSession> signUp({required String name, required String email, required String password}) {
return _authenticate(
endpoint: '/auth/register',
body: <String, dynamic>{'name': name, 'email': email, 'password': password},
);
}
Future<AuthSession> _authenticate({required String endpoint, required Map<String, dynamic> body}) async {
final uri = Uri.parse('${AppConfig.apiBaseUrl}$endpoint');
late final http.Response response;
try {
response = await (_client ?? http.Client()).post(
uri,
headers: const <String, String>{
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: jsonEncode(body),
);
} catch (_) {
throw AuthException(
'No se pudo conectar con el backend en ${AppConfig.apiBaseUrl}. Verifica que el servicio esté activo.',
);
}
final Map<String, dynamic> payload = _decodeJson(response.body);
if (response.statusCode < 200 || response.statusCode >= 300) {
final message = payload['message']?.toString() ?? 'Credenciales inválidas o usuario no disponible.';
throw AuthException(message);
}
final token = payload['token']?.toString();
if (token == null || token.isEmpty) {
throw AuthException('El backend respondió sin token de sesión.');
}
final user = payload['user'] is Map<String, dynamic>
? payload['user'] as Map<String, dynamic>
: <String, dynamic>{};
final emailValue = (user['email'] ?? body['email'])?.toString() ?? body['email'].toString();
final displayName = (user['name'] ?? user['fullName'] ?? body['name'] ?? emailValue).toString();
final session = AuthSession(token: token, email: emailValue, displayName: displayName);
await _persistSession(session);
return session;
}
Future<void> _persistSession(AuthSession session) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_tokenKey, session.token);
await prefs.setString(_emailKey, session.email);
await prefs.setString(_nameKey, session.displayName);
}
Map<String, dynamic> _decodeJson(String responseBody) {
if (responseBody.trim().isEmpty) {
return <String, dynamic>{};
}
final decoded = jsonDecode(responseBody);
if (decoded is Map<String, dynamic>) {
return decoded;
}
return <String, dynamic>{};
}
@override
Future<void> signOut() async {
final prefs = await SharedPreferences.getInstance();
await prefs.remove(_tokenKey);
await prefs.remove(_emailKey);
await prefs.remove(_nameKey);
}
}
class AuthException implements Exception {
AuthException(this.message);
final String message;
@override
String toString() => message;
}

1
linux/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
flutter/ephemeral

128
linux/CMakeLists.txt Normal file
View File

@@ -0,0 +1,128 @@
# Project-level configuration.
cmake_minimum_required(VERSION 3.13)
project(runner LANGUAGES CXX)
# The name of the executable created for the application. Change this to change
# the on-disk name of your application.
set(BINARY_NAME "flutter_application_1")
# The unique GTK application identifier for this application. See:
# https://wiki.gnome.org/HowDoI/ChooseApplicationID
set(APPLICATION_ID "com.example.flutter_application_1")
# Explicitly opt in to modern CMake behaviors to avoid warnings with recent
# versions of CMake.
cmake_policy(SET CMP0063 NEW)
# Load bundled libraries from the lib/ directory relative to the binary.
set(CMAKE_INSTALL_RPATH "$ORIGIN/lib")
# Root filesystem for cross-building.
if(FLUTTER_TARGET_PLATFORM_SYSROOT)
set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT})
set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT})
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
endif()
# Define build configuration options.
if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
set(CMAKE_BUILD_TYPE "Debug" CACHE
STRING "Flutter build mode" FORCE)
set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS
"Debug" "Profile" "Release")
endif()
# Compilation settings that should be applied to most targets.
#
# Be cautious about adding new options here, as plugins use this function by
# default. In most cases, you should add new options to specific targets instead
# of modifying this function.
function(APPLY_STANDARD_SETTINGS TARGET)
target_compile_features(${TARGET} PUBLIC cxx_std_14)
target_compile_options(${TARGET} PRIVATE -Wall -Werror)
target_compile_options(${TARGET} PRIVATE "$<$<NOT:$<CONFIG:Debug>>:-O3>")
target_compile_definitions(${TARGET} PRIVATE "$<$<NOT:$<CONFIG:Debug>>:NDEBUG>")
endfunction()
# Flutter library and tool build rules.
set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter")
add_subdirectory(${FLUTTER_MANAGED_DIR})
# System-level dependencies.
find_package(PkgConfig REQUIRED)
pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0)
# Application build; see runner/CMakeLists.txt.
add_subdirectory("runner")
# Run the Flutter tool portions of the build. This must not be removed.
add_dependencies(${BINARY_NAME} flutter_assemble)
# Only the install-generated bundle's copy of the executable will launch
# correctly, since the resources must in the right relative locations. To avoid
# people trying to run the unbundled copy, put it in a subdirectory instead of
# the default top-level location.
set_target_properties(${BINARY_NAME}
PROPERTIES
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run"
)
# Generated plugin build rules, which manage building the plugins and adding
# them to the application.
include(flutter/generated_plugins.cmake)
# === Installation ===
# By default, "installing" just makes a relocatable bundle in the build
# directory.
set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle")
if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT)
set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE)
endif()
# Start with a clean build bundle directory every time.
install(CODE "
file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\")
" COMPONENT Runtime)
set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data")
set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib")
install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}"
COMPONENT Runtime)
install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}"
COMPONENT Runtime)
install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES})
install(FILES "${bundled_library}"
DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
endforeach(bundled_library)
# Copy the native assets provided by the build.dart from all packages.
set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/")
install(DIRECTORY "${NATIVE_ASSETS_DIR}"
DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
# Fully re-copy the assets directory on each build to avoid having stale files
# from a previous install.
set(FLUTTER_ASSET_DIR_NAME "flutter_assets")
install(CODE "
file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\")
" COMPONENT Runtime)
install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}"
DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime)
# Install the AOT library on non-Debug builds only.
if(NOT CMAKE_BUILD_TYPE MATCHES "Debug")
install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
endif()

View File

@@ -0,0 +1,88 @@
# This file controls Flutter-level build steps. It should not be edited.
cmake_minimum_required(VERSION 3.10)
set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral")
# Configuration provided via flutter tool.
include(${EPHEMERAL_DIR}/generated_config.cmake)
# TODO: Move the rest of this into files in ephemeral. See
# https://github.com/flutter/flutter/issues/57146.
# Serves the same purpose as list(TRANSFORM ... PREPEND ...),
# which isn't available in 3.10.
function(list_prepend LIST_NAME PREFIX)
set(NEW_LIST "")
foreach(element ${${LIST_NAME}})
list(APPEND NEW_LIST "${PREFIX}${element}")
endforeach(element)
set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE)
endfunction()
# === Flutter Library ===
# System-level dependencies.
find_package(PkgConfig REQUIRED)
pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0)
pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0)
pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0)
set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so")
# Published to parent scope for install step.
set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE)
set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE)
set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE)
set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE)
list(APPEND FLUTTER_LIBRARY_HEADERS
"fl_basic_message_channel.h"
"fl_binary_codec.h"
"fl_binary_messenger.h"
"fl_dart_project.h"
"fl_engine.h"
"fl_json_message_codec.h"
"fl_json_method_codec.h"
"fl_message_codec.h"
"fl_method_call.h"
"fl_method_channel.h"
"fl_method_codec.h"
"fl_method_response.h"
"fl_plugin_registrar.h"
"fl_plugin_registry.h"
"fl_standard_message_codec.h"
"fl_standard_method_codec.h"
"fl_string_codec.h"
"fl_value.h"
"fl_view.h"
"flutter_linux.h"
)
list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/")
add_library(flutter INTERFACE)
target_include_directories(flutter INTERFACE
"${EPHEMERAL_DIR}"
)
target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}")
target_link_libraries(flutter INTERFACE
PkgConfig::GTK
PkgConfig::GLIB
PkgConfig::GIO
)
add_dependencies(flutter flutter_assemble)
# === Flutter tool backend ===
# _phony_ is a non-existent file to force this command to run every time,
# since currently there's no way to get a full input/output list from the
# flutter tool.
add_custom_command(
OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS}
${CMAKE_CURRENT_BINARY_DIR}/_phony_
COMMAND ${CMAKE_COMMAND} -E env
${FLUTTER_TOOL_ENVIRONMENT}
"${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh"
${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE}
VERBATIM
)
add_custom_target(flutter_assemble DEPENDS
"${FLUTTER_LIBRARY}"
${FLUTTER_LIBRARY_HEADERS}
)

View File

@@ -0,0 +1,11 @@
//
// Generated file. Do not edit.
//
// clang-format off
#include "generated_plugin_registrant.h"
void fl_register_plugins(FlPluginRegistry* registry) {
}

View File

@@ -0,0 +1,15 @@
//
// Generated file. Do not edit.
//
// clang-format off
#ifndef GENERATED_PLUGIN_REGISTRANT_
#define GENERATED_PLUGIN_REGISTRANT_
#include <flutter_linux/flutter_linux.h>
// Registers Flutter plugins.
void fl_register_plugins(FlPluginRegistry* registry);
#endif // GENERATED_PLUGIN_REGISTRANT_

View File

@@ -0,0 +1,23 @@
#
# Generated file, do not edit.
#
list(APPEND FLUTTER_PLUGIN_LIST
)
list(APPEND FLUTTER_FFI_PLUGIN_LIST
)
set(PLUGIN_BUNDLED_LIBRARIES)
foreach(plugin ${FLUTTER_PLUGIN_LIST})
add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin})
target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin)
list(APPEND PLUGIN_BUNDLED_LIBRARIES $<TARGET_FILE:${plugin}_plugin>)
list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries})
endforeach(plugin)
foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST})
add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin})
list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries})
endforeach(ffi_plugin)

View File

@@ -0,0 +1,26 @@
cmake_minimum_required(VERSION 3.13)
project(runner LANGUAGES CXX)
# Define the application target. To change its name, change BINARY_NAME in the
# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer
# work.
#
# Any new source files that you add to the application should be added here.
add_executable(${BINARY_NAME}
"main.cc"
"my_application.cc"
"${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc"
)
# Apply the standard set of build settings. This can be removed for applications
# that need different build settings.
apply_standard_settings(${BINARY_NAME})
# Add preprocessor definitions for the application ID.
add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}")
# Add dependency libraries. Add any application-specific dependencies here.
target_link_libraries(${BINARY_NAME} PRIVATE flutter)
target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK)
target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}")

6
linux/runner/main.cc Normal file
View File

@@ -0,0 +1,6 @@
#include "my_application.h"
int main(int argc, char** argv) {
g_autoptr(MyApplication) app = my_application_new();
return g_application_run(G_APPLICATION(app), argc, argv);
}

View File

@@ -0,0 +1,148 @@
#include "my_application.h"
#include <flutter_linux/flutter_linux.h>
#ifdef GDK_WINDOWING_X11
#include <gdk/gdkx.h>
#endif
#include "flutter/generated_plugin_registrant.h"
struct _MyApplication {
GtkApplication parent_instance;
char** dart_entrypoint_arguments;
};
G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION)
// Called when first Flutter frame received.
static void first_frame_cb(MyApplication* self, FlView* view) {
gtk_widget_show(gtk_widget_get_toplevel(GTK_WIDGET(view)));
}
// Implements GApplication::activate.
static void my_application_activate(GApplication* application) {
MyApplication* self = MY_APPLICATION(application);
GtkWindow* window =
GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application)));
// Use a header bar when running in GNOME as this is the common style used
// by applications and is the setup most users will be using (e.g. Ubuntu
// desktop).
// If running on X and not using GNOME then just use a traditional title bar
// in case the window manager does more exotic layout, e.g. tiling.
// If running on Wayland assume the header bar will work (may need changing
// if future cases occur).
gboolean use_header_bar = TRUE;
#ifdef GDK_WINDOWING_X11
GdkScreen* screen = gtk_window_get_screen(window);
if (GDK_IS_X11_SCREEN(screen)) {
const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen);
if (g_strcmp0(wm_name, "GNOME Shell") != 0) {
use_header_bar = FALSE;
}
}
#endif
if (use_header_bar) {
GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new());
gtk_widget_show(GTK_WIDGET(header_bar));
gtk_header_bar_set_title(header_bar, "flutter_application_1");
gtk_header_bar_set_show_close_button(header_bar, TRUE);
gtk_window_set_titlebar(window, GTK_WIDGET(header_bar));
} else {
gtk_window_set_title(window, "flutter_application_1");
}
gtk_window_set_default_size(window, 1280, 720);
g_autoptr(FlDartProject) project = fl_dart_project_new();
fl_dart_project_set_dart_entrypoint_arguments(
project, self->dart_entrypoint_arguments);
FlView* view = fl_view_new(project);
GdkRGBA background_color;
// Background defaults to black, override it here if necessary, e.g. #00000000
// for transparent.
gdk_rgba_parse(&background_color, "#000000");
fl_view_set_background_color(view, &background_color);
gtk_widget_show(GTK_WIDGET(view));
gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view));
// Show the window when Flutter renders.
// Requires the view to be realized so we can start rendering.
g_signal_connect_swapped(view, "first-frame", G_CALLBACK(first_frame_cb),
self);
gtk_widget_realize(GTK_WIDGET(view));
fl_register_plugins(FL_PLUGIN_REGISTRY(view));
gtk_widget_grab_focus(GTK_WIDGET(view));
}
// Implements GApplication::local_command_line.
static gboolean my_application_local_command_line(GApplication* application,
gchar*** arguments,
int* exit_status) {
MyApplication* self = MY_APPLICATION(application);
// Strip out the first argument as it is the binary name.
self->dart_entrypoint_arguments = g_strdupv(*arguments + 1);
g_autoptr(GError) error = nullptr;
if (!g_application_register(application, nullptr, &error)) {
g_warning("Failed to register: %s", error->message);
*exit_status = 1;
return TRUE;
}
g_application_activate(application);
*exit_status = 0;
return TRUE;
}
// Implements GApplication::startup.
static void my_application_startup(GApplication* application) {
// MyApplication* self = MY_APPLICATION(object);
// Perform any actions required at application startup.
G_APPLICATION_CLASS(my_application_parent_class)->startup(application);
}
// Implements GApplication::shutdown.
static void my_application_shutdown(GApplication* application) {
// MyApplication* self = MY_APPLICATION(object);
// Perform any actions required at application shutdown.
G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application);
}
// Implements GObject::dispose.
static void my_application_dispose(GObject* object) {
MyApplication* self = MY_APPLICATION(object);
g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev);
G_OBJECT_CLASS(my_application_parent_class)->dispose(object);
}
static void my_application_class_init(MyApplicationClass* klass) {
G_APPLICATION_CLASS(klass)->activate = my_application_activate;
G_APPLICATION_CLASS(klass)->local_command_line =
my_application_local_command_line;
G_APPLICATION_CLASS(klass)->startup = my_application_startup;
G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown;
G_OBJECT_CLASS(klass)->dispose = my_application_dispose;
}
static void my_application_init(MyApplication* self) {}
MyApplication* my_application_new() {
// Set the program name to the application ID, which helps various systems
// like GTK and desktop environments map this running application to its
// corresponding .desktop file. This ensures better integration by allowing
// the application to be recognized beyond its binary name.
g_set_prgname(APPLICATION_ID);
return MY_APPLICATION(g_object_new(my_application_get_type(),
"application-id", APPLICATION_ID, "flags",
G_APPLICATION_NON_UNIQUE, nullptr));
}

Some files were not shown because too many files have changed in this diff Show More