Last active
April 23, 2022 20:47
-
-
Save franksantos/c6537fb5f022d48b1847dd590342f286 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:async'; | |
import 'dart:convert'; | |
import 'package:aplicativo_cfp2022/models/aluno.dart'; | |
import 'package:aplicativo_cfp2022/api/api_service.dart'; | |
import 'package:flutter/material.dart'; | |
import 'package:shared_preferences/shared_preferences.dart'; | |
import 'package:intl/intl.dart'; | |
import 'package:http/http.dart' as http; | |
import 'package:google_mobile_ads/google_mobile_ads.dart'; | |
class Anotacao extends StatefulWidget { | |
const Anotacao({Key? key}) : super(key: key); | |
@override | |
State<Anotacao> createState() => _AnotacaoState(); | |
} | |
class _AnotacaoState extends State<Anotacao> { | |
final _formkey = GlobalKey<FormState>(); | |
//token | |
late String _localToken; | |
//'responsible_annotation' esse dado vai ser passado na chamada HTTP | |
final _dataAnotacao = TextEditingController(); | |
final _horaAnotacao = TextEditingController(); | |
//só vai aparecer se marcar outro na transgressão, não tiver trangressão na lista | |
final _descricaoAnotacao = TextEditingController(); | |
//variável para conter a hora selecionada | |
TimeOfDay _horaInicialTimepicker = TimeOfDay.now(); | |
//variável error, se houver erro será true | |
late bool error; | |
//message recebe uma string de erro caso haja erro na API | |
late String message; | |
var data; | |
//lista de alunos | |
late Future<List<Aluno>> futureListAlunos; | |
late Aluno _alunoSelecionado; | |
late String _selected; | |
/* | |
* Código do Banner ADMOB | |
*/ | |
final BannerAd myBanner = BannerAd( | |
adUnitId: 'ca-app-pub-3940256099942544/6300978111', | |
size: AdSize.banner, | |
request: AdRequest(), | |
listener: BannerAdListener(), | |
); | |
Future<String?> getToken() async { | |
final SharedPreferences prefs = await SharedPreferences.getInstance(); | |
return prefs.getString('token'); | |
} | |
/// initialization is here: | |
@override | |
void initState() { | |
super.initState(); | |
myBanner.load(); | |
futureListAlunos = carregaListaAlunos(); | |
error = false; | |
} | |
Future<List<Aluno>> carregaListaAlunos() async { | |
_localToken = (await getToken())!; | |
var url = Uri.parse("http://cfp2022.viasistemasweb.com.br/api/lista-alunos"); | |
var headers = { | |
'Content-Type':'application/json', | |
'Authorization': 'Bearer $_localToken' | |
}; | |
//chama a API | |
var response = await http.get(url,headers: headers,); | |
final responseJson = jsonDecode(response.body.toString().replaceAll("\n", "")); | |
print("dados retornados da API ->"+responseJson); | |
if(response.statusCode == 200) { | |
return (responseJson as List) | |
.map((aluno) => Aluno.fromJson(aluno)).toList(); | |
}else{ | |
throw Exception('Falha ao carregar os alunos'); | |
} | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar(title: const Text("Anotação")), | |
body: Form( | |
key: _formkey, | |
child: Container( | |
padding: EdgeInsets.symmetric(vertical: 10), | |
child: SingleChildScrollView( | |
padding: const EdgeInsets.symmetric(horizontal: 16), | |
child: Column( | |
crossAxisAlignment: CrossAxisAlignment.stretch, | |
children: [ | |
Container( | |
padding: EdgeInsets.fromLTRB(0, 0, 0, 10), | |
height: 50, | |
width: 320, | |
child: AdWidget(ad: myBanner)), | |
const SizedBox(height: 10), | |
Image.asset( | |
'imagens/logo_foreground.png', | |
height: 120, | |
width: 120, | |
fit: BoxFit.scaleDown, | |
), | |
const Text("Cadastro de Anotação", | |
style: TextStyle(fontSize: 20), | |
textAlign: TextAlign.center), | |
const SizedBox(height: 10), | |
/** Data da Anotação */ | |
TextFormField( | |
decoration: InputDecoration( | |
labelText: "Data Anotação. (ex: 20/05/2022)", | |
filled: true, | |
fillColor: Colors.green.shade50, | |
labelStyle: TextStyle( | |
color: Colors.green[800], | |
fontStyle: FontStyle.italic, | |
fontSize: 10), | |
), | |
onTap: () async { | |
DateTime date = DateTime(1900); | |
FocusScope.of(context).requestFocus(new FocusNode()); | |
date = (await showDatePicker( | |
context: context, | |
initialDate: DateTime.now(), | |
firstDate: DateTime(2022), | |
lastDate: DateTime(2023), | |
builder: (BuildContext context, Widget? child) { | |
return Theme( | |
data: ThemeData.dark(), | |
child: child!, | |
); | |
}))!; | |
String dataFormatada = | |
DateFormat('dd/MM/yyyy').format(date); | |
_dataAnotacao.text = dataFormatada; | |
}, | |
controller: _dataAnotacao, | |
keyboardType: TextInputType.text, | |
validator: (previsaoReserva) { | |
if (previsaoReserva == null || | |
previsaoReserva.isEmpty) { | |
return 'Por favor digite dia/mês/ano da Anotação'; | |
} else if (!RegExp( | |
r"^([0-1])([0-9])\/([0-1])([0-9])\/([2][0][2-9][0-9])") | |
.hasMatch(_dataAnotacao.text)) { | |
return 'Siga o padrão dia/mês/ano. Ex: 20/05/2022'; | |
} | |
return null; | |
}, | |
), | |
const SizedBox(height: 10), | |
/** HORA da Anotação */ | |
TextFormField( | |
decoration: InputDecoration( | |
labelText: "Hora Anotação. (ex: 09:35)", | |
filled: true, | |
fillColor: Colors.green.shade50, | |
labelStyle: TextStyle( | |
color: Colors.green[800], | |
fontStyle: FontStyle.italic, | |
fontSize: 10), | |
), | |
onTap: () async { | |
TimeOfDay time = TimeOfDay.now(); | |
FocusScope.of(context).requestFocus(new FocusNode()); | |
time = (await showTimePicker( | |
context: context, | |
initialTime: _horaInicialTimepicker, | |
initialEntryMode: TimePickerEntryMode.dial, | |
))!; | |
int hora = time.hour; | |
int minuto = time.minute; | |
_horaAnotacao.text = | |
hora.toString() + ':' + minuto.toString(); | |
}, | |
controller: _horaAnotacao, | |
keyboardType: TextInputType.text, | |
validator: (horaAnotacao) { | |
if (horaAnotacao == null || horaAnotacao.isEmpty) { | |
return 'Por favor informe a hora da anotacao'; | |
} | |
return null; | |
}, | |
), | |
const SizedBox(height: 10), | |
/** Aluno Anotado */ | |
FutureBuilder<List<Aluno>>( | |
future: futureListAlunos, | |
builder: (context, snapshot) { | |
var dados = snapshot.data; | |
var teste = "tes"; | |
if(snapshot.hasData){ | |
return DropdownButton( | |
icon: Icon(Icons.arrow_drop_down), | |
iconSize: 30, | |
elevation: 16, | |
style: TextStyle(color: Colors.black), | |
value: _alunoSelecionado, | |
hint: const Text('Selecione...'), | |
isExpanded: true, | |
onChanged: (newValue) { | |
setState(() { | |
_alunoSelecionado = newValue as Aluno; | |
}); | |
}, | |
items: snapshot.data?.map<DropdownMenuItem<Aluno>>((Aluno value) { | |
return DropdownMenuItem<Aluno>( | |
value: value, | |
child: Text(value.nome_guerra) | |
); | |
}).toList(), | |
); | |
} else if (snapshot.hasError) { | |
return Text("${snapshot.error}"); | |
} | |
return CircularProgressIndicator(); | |
}, | |
), | |
/*Container( | |
child: error?Text(message):AlunosListaWidget(), | |
),*/ | |
const SizedBox(height: 10), | |
/** Botão Salvar */ | |
ElevatedButton( | |
onPressed: () async { | |
FocusScopeNode currentFocus = FocusScope.of(context); | |
if (_formkey.currentState!.validate()) { | |
bool deuCerto = await enviarDados(); | |
if (!currentFocus.hasPrimaryFocus) { | |
currentFocus.unfocus(); | |
} | |
if (deuCerto) { | |
} else { | |
ScaffoldMessenger.of(context) | |
.showSnackBar(snackBar); | |
} | |
} | |
}, | |
child: const Text("Enviar Anotação")) | |
], | |
)), | |
)), | |
); | |
} | |
_horarioAnotacaoTimepicker(BuildContext context) async { | |
final TimeOfDay? timeOfDay = await showTimePicker( | |
context: context, | |
initialTime: _horaInicialTimepicker, | |
initialEntryMode: TimePickerEntryMode.dial, | |
); | |
if (timeOfDay != _horaInicialTimepicker) { | |
setState(() { | |
_horaInicialTimepicker = timeOfDay!; | |
}); | |
} | |
} | |
void _carregando() { | |
showDialog( | |
context: context, | |
barrierDismissible: false, | |
builder: (BuildContext context) { | |
return Dialog( | |
child: Container( | |
width: 150, | |
height: 150, | |
alignment: Alignment.center, | |
child: new Column( | |
mainAxisSize: MainAxisSize.min, | |
children: [ | |
new CircularProgressIndicator(), | |
new Text("Carregando"), | |
], | |
), | |
)); | |
}, | |
); | |
} | |
final snackBar = const SnackBar( | |
// ignore: unnecessary_const | |
content: Text( | |
"Houve um erro. Tente novamente.", | |
textAlign: TextAlign.center, | |
), | |
backgroundColor: Colors.redAccent, | |
); | |
Future<bool> enviarDados() async { | |
_localToken = (await getToken())!; | |
debugPrint(''); | |
// return true; | |
if (_localToken != '') { | |
/** URL */ | |
var url = Uri.parse( | |
"http://cfp2022.viasistemasweb.com.br/api/atualiza-dados-aluno"); | |
/** URL do Heroku para testes */ | |
//var url = Uri.parse("https://cfsd2022.herokuapp.com/api/atualiza-dados-aluno"); | |
var headers = { | |
'Content-Type': 'application/json', | |
'Authorization': 'Bearer $_localToken' | |
}; | |
final body = {}; | |
var resposta = await http.post( | |
url, | |
headers: headers, | |
body: jsonEncode(body), // use jsonEncode() | |
); | |
if (resposta.statusCode == 200) { | |
print(jsonDecode(resposta.body)); | |
return true; | |
} else { | |
print(jsonDecode(resposta.body)); | |
return false; | |
} | |
} else { | |
return false; | |
} | |
} | |
} | |
//classe aluno | |
class Aluno { | |
String id, classroom_id; | |
String nome_guerra; | |
Aluno({required this.id, required this.nome_guerra, required this.classroom_id}); | |
factory Aluno.fromJson(Map<String, dynamic> json) { | |
var id = json['id']; | |
var classroom_id = json['classroom_id']; | |
var nome_guerra = json['nome_guerra']; | |
return Aluno( | |
id: id.cast<String>(), | |
classroom_id: classroom_id.cast<String>(), | |
nome_guerra: nome_guerra.cast<String>() | |
); | |
} | |
Map<String, dynamic> toJson() => { | |
'id': id, | |
'classroom_id': classroom_id, | |
'nome_guerra': nome_guerra | |
}; | |
} | |
// } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment