Skip to content

Commit

Permalink
api de validação de CEP on, cadastro e exclusão de casas on
Browse files Browse the repository at this point in the history
  • Loading branch information
LeonardoMessaWagner committed Dec 9, 2023
1 parent cea94f4 commit 085d189
Show file tree
Hide file tree
Showing 9 changed files with 205 additions and 22 deletions.
3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"java.configuration.updateBuildConfiguration": "interactive"
}
5 changes: 4 additions & 1 deletion android/app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ android {
targetSdkVersion flutter.targetSdkVersion
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
multiDexEnabled true
}

buildTypes {
Expand All @@ -64,4 +65,6 @@ flutter {
source '../..'
}

dependencies {}
dependencies {
implementation 'com.android.support:multidex:2.0.1'
}
34 changes: 33 additions & 1 deletion lib/database/casas_store.dart
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:flutter_trabalho/database/db_firebase.dart';
import 'package:flutter_trabalho/http/constantes.dart';
import 'package:flutter_trabalho/servicos/auth.dart';
import 'package:http/http.dart' as http;

class CasasRepository extends ChangeNotifier {
late FirebaseFirestore db;
Expand All @@ -19,5 +21,35 @@ class CasasRepository extends ChangeNotifier {
db = DBFirestore.get();
}

saveCasa(String Rua, int numero, String CEP, bool garagem, bool piscina) {}
saveCasa(String apelido, String Rua, String numero, String CEP, bool garagem,
bool piscina) async {
try {
Uri url = Uri.parse(ApiConstants.baseurl + CEP + ApiConstants.endpoint);

http.Response response = await http.get(url);

if (response.statusCode == 200) {
int numeroint = int.parse(numero);

final docCasa =
db.collection('usuarios/${auth.usuario!.uid}/minhascasas').doc();

docCasa.set({
'id': docCasa.id,
'rua': Rua,
'numero': numeroint,
'Cep': CEP,
'garagem': garagem,
'piscina': piscina,
'apelido': apelido
});
return true;
} else {
return false;
}
} catch (e) {
print(e.toString());
return false;
}
}
}
4 changes: 4 additions & 0 deletions lib/http/constantes.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
class ApiConstants {
static String baseurl = "https://viacep.com.br/ws/";
static String endpoint = "/json";
}
2 changes: 1 addition & 1 deletion lib/paginas/appbar.dart
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ class CustomAppBar extends StatelessWidget implements PreferredSizeWidget {
@override
Widget build(BuildContext context) {
return AppBar(
title: Text(title ?? 'Ops'),
title: Center(child: Text(title ?? 'Ops')),
leading: Builder(builder: (context) {
return IconButton(
icon: const Icon(Icons.menu),
Expand Down
109 changes: 94 additions & 15 deletions lib/paginas/cad_casas.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import 'package:flutter/material.dart';
import 'package:flutter_trabalho/database/casas_store.dart';
import 'package:provider/provider.dart';

class CadCasas extends StatefulWidget {
const CadCasas({super.key});
Expand All @@ -9,11 +11,84 @@ class CadCasas extends StatefulWidget {

class _CadCasasState extends State<CadCasas> {
final _formKey = GlobalKey<FormState>();
final TextEditingController _apelidoController = TextEditingController();
final TextEditingController _ruaController = TextEditingController();
final TextEditingController _numeroController = TextEditingController();
final TextEditingController _cepController = TextEditingController();
bool? _temGaragem = false;
bool? _temPiscina = false;

Future<void> _alertaPositivo() async {
return showDialog<void>(
context: context,
barrierDismissible: false, // user must tap button!
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Tudo certo'),
content: const SingleChildScrollView(
child: ListBody(
children: <Widget>[
Text('Casa cadastrada!'),
],
),
),
actions: <Widget>[
TextButton(
child: const Text('Ok'),
onPressed: () {
Navigator.of(context).pop();
Navigator.of(context).pop();
Navigator.of(context).pop();
},
),
],
);
},
);
}

Future<void> _alertaNegativo() async {
return showDialog<void>(
context: context,
barrierDismissible: false, // user must tap button!
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Algo errado'),
content: const SingleChildScrollView(
child: ListBody(
children: <Widget>[
Text('Verifique os dados inseridos!'),
],
),
),
actions: <Widget>[
TextButton(
child: const Text('Ok'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}

salvar() async {
bool resposta = await context.read<CasasRepository>().saveCasa(
_apelidoController.text,
_ruaController.text,
_numeroController.text,
_cepController.text,
_temGaragem!,
_temPiscina!);
if (resposta == true) {
_alertaPositivo();
} else {
_alertaNegativo();
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
Expand All @@ -28,35 +103,40 @@ class _CadCasasState extends State<CadCasas> {
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
TextFormField(
controller: _ruaController,
decoration: InputDecoration(labelText: 'Rua'),
controller: _apelidoController,
decoration: const InputDecoration(labelText: 'Apelido da Casa'),
validator: (value) {
if (value!.isEmpty) {
return 'Por favor, insira a rua';
return 'Por favor, insira o apelido da casa';
}
return null;
},
),
TextFormField(
controller: _numeroController,
decoration: InputDecoration(labelText: 'Número'),
controller: _ruaController,
decoration: InputDecoration(labelText: 'Rua'),
validator: (value) {
if (value!.isEmpty) {
return 'Por favor, insira o número';
return 'Por favor, insira a rua';
}
return null;
},
),
TextFormField(
controller: _cepController,
decoration: InputDecoration(labelText: 'CEP'),
controller: _numeroController,
keyboardType: TextInputType.number,
decoration: const InputDecoration(labelText: 'Número'),
validator: (value) {
if (value!.isEmpty) {
return 'Por favor, insira o CEP';
}
return 'Por favor, insira um número valido';
} else {}
return null;
},
),
TextFormField(
controller: _cepController,
decoration: const InputDecoration(labelText: 'CEP'),
),
CheckboxListTile(
title: const Text('Tem Garagem'),
value: _temGaragem,
Expand All @@ -67,19 +147,18 @@ class _CadCasasState extends State<CadCasas> {
},
),
CheckboxListTile(
title: Text('Tem Piscina'),
title: const Text('Tem Piscina'),
value: _temPiscina,
onChanged: (bool? value) {
setState(() {
_temPiscina = value!;
});

;
},
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () {},
onPressed: () {
salvar();
},
child: Text('Cadastrar Casa'),
),
],
Expand Down
63 changes: 63 additions & 0 deletions lib/paginas/home.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter_trabalho/paginas/appbar.dart';
import 'package:flutter_trabalho/paginas/cad_casas.dart';
Expand All @@ -11,7 +13,19 @@ class Home extends StatefulWidget {
State<Home> createState() => _HomeState();
}

late AuthService auth;

class _HomeState extends State<Home> {
late AuthService authService;
late User? usuario;

@override
void initState() {
super.initState();
authService = Provider.of<AuthService>(context, listen: false);
usuario = authService.usuario;
}

@override
Widget build(BuildContext context) {
final authService = Provider.of<AuthService>(context);
Expand Down Expand Up @@ -52,6 +66,55 @@ class _HomeState extends State<Home> {
],
),
),
body: StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance
.collection('usuarios/${usuario?.uid}/minhascasas')
.snapshots(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
}

if (snapshot.hasError) {
return const Center(child: Text('Erro ao carregar os dados'));
}

// Lista de documentos
List<DocumentSnapshot> casas = snapshot.data!.docs;

return ListView.builder(
itemCount: casas.length,
itemBuilder: (context, index) {
var casa = casas[index];
return ListTile(
title: Text(casa['apelido']),
subtitle: Text('CEP: ${casa['Cep']}'),
trailing: IconButton(
icon: Icon(Icons.delete),
onPressed: () {
// Exclui o documento do Firebase Firestore
FirebaseFirestore.instance
.collection('usuarios/${usuario?.uid}/minhascasas')
.doc(casa.id)
.delete()
.then((value) {
// Ação após a exclusão (opcional)
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Casa excluída com sucesso')),
);
}).catchError((error) {
// Caso ocorra um erro na exclusão
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Erro ao excluir a casa')),
);
});
},
),
);
},
);
},
),
);
}
}
6 changes: 2 additions & 4 deletions lib/servicos/auth.dart
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,8 @@ class AuthService extends ChangeNotifier {
await _auth.signInWithEmailAndPassword(email: email, password: senha);
_getUser();
} on FirebaseAuthException catch (e) {
if (e.code == 'user-not-found') {
throw AuthException('usuario não cadastrado');
} else if (e.code == 'wrong-password') {
throw AuthException('Senha incorreta');
if (e.code == 'invalid-credential') {
throw AuthException('Credenciais invalidas');
}
}
}
Expand Down
1 change: 1 addition & 0 deletions pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ dependencies:
provider: ^6.1.1
cloud_firestore: ^4.13.5
http: ^1.1.0



dev_dependencies:
Expand Down

0 comments on commit 085d189

Please sign in to comment.