Skip to content

Instantly share code, notes, and snippets.

@guilhermecarvalhocarneiro
Created July 23, 2019 19:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guilhermecarvalhocarneiro/4c2d92c98df14e3a60cbc486a1c996db to your computer and use it in GitHub Desktop.
Save guilhermecarvalhocarneiro/4c2d92c98df14e3a60cbc486a1c996db to your computer and use it in GitHub Desktop.
BottomNavigationBar mantendo o estado dos dados carregados
import 'package:bloc_pattern/bloc_pattern.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:location/location.dart';
import 'package:minhacidade/blocs/atrativo_bloc.dart';
import 'package:minhacidade/blocs/cidade_bloc.dart';
import 'package:minhacidade/blocs/estabelecimento_bloc.dart';
import 'package:minhacidade/blocs/evento_bloc.dart';
import 'package:minhacidade/blocs/foursquare_bloc.dart';
import 'package:minhacidade/blocs/roteiro_bloc.dart';
import 'package:minhacidade/domain/cidade_domain.dart';
import 'package:minhacidade/domain/location_domina.dart';
import 'package:minhacidade/pages/atrativos_page.dart';
import 'package:minhacidade/pages/cidades_page.dart';
import 'package:minhacidade/pages/estabelecimentos_page.dart';
import 'package:minhacidade/pages/eventos_page.dart';
import 'package:minhacidade/pages/roteiros_page.dart';
import 'package:minhacidade/utils/colors.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return BlocProvider(
blocs: [
Bloc((i) => AtrativoBloc()),
Bloc((i) => EventoBloc()),
Bloc((i) => EstabelecimentoBloc()),
Bloc((i) => RoteiroBloc()),
Bloc((i) => CidadeBloc()),
Bloc((i) => FoursquareFotoBloc()),
Bloc((i) => FoursquareDicaBloc())
],
child: MaterialApp(
title: 'tôChegando',
theme: ThemeData(
primarySwatch: Colors.blue,
backgroundColor: backgroundCustomColor,
primaryColor: primaryCustomColor,
accentColor: accentCustomColor,
textTheme: TextTheme(
caption: TextStyle(color: defaultCustomColor),
title: TextStyle(color: defaultCustomColor),
subtitle: TextStyle(color: defaultCustomColor),
subhead: TextStyle(color: defaultCustomColor),
body1: TextStyle(color: defaultCustomColor),
body2: TextStyle(color: defaultCustomColor),
display1: TextStyle(
color: defaultCustomColor,
fontSize: 24,
fontWeight: FontWeight.bold,
),
display2: TextStyle(
color: defaultCustomColor,
fontSize: 22,
fontWeight: FontWeight.w300,
),
display3: TextStyle(fontSize: 38, color: defaultCustomColor),
display4: TextStyle(
fontSize: 18,
color: defaultCustomColor,
fontWeight: FontWeight.w400)),
),
home: MyHomePage(title: 'tôChegando'),
debugShowCheckedModeBanner: false,
),
);
}
}
class MyHomePage extends StatefulWidget {
String title;
MyHomePage({Key key, this.title}) : super(key: key);
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin<MyHomePage> {
// Indice para determinar o posicionamento da página na bottomnavigation
int _indexCurrentPage = 0;
// Página atual no bottomnavigation
Widget _currentPage;
// Lista de páginas para popular a bottomnavigation
List<Widget> _pages;
// Adicionando o Title
AtrativosPage atrativosPage;
EstabelecimentoPage estabelecimentoPage;
EventosPage eventosPage;
RoteirosPage roteirosPage;
// Configurações para pegar a localização do usuário
LocationData currentLocation;
Location location = Location();
bool permission;
String error;
@override
void initState() {
super.initState();
atrativosPage = AtrativosPage();
estabelecimentoPage = EstabelecimentoPage();
eventosPage = EventosPage();
roteirosPage = RoteirosPage();
// Método para verificar se o usuário já escolheu alguma cidade
_checkCidadeEscolhida(context);
// Verificando a Cidade selecionada
_getCidadeEscolhida();
// Criando um array com as páginas a serem utilizadas na navegação
_pages = [eventosPage, atrativosPage, estabelecimentoPage, roteirosPage];
// Setando como página inicial a página de eventos
_currentPage = eventosPage;
// Chamando o método para recuperar a localização atual do usuário
initPlatformState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(
widget.title,
style: Theme.of(context).textTheme.title,
textAlign: TextAlign.center,
),
actions: <Widget>[
IconButton(
icon: Icon(Icons.location_city),
color: defaultCustomColor,
tooltip: 'Cidades',
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => CidadesPage()),
);
})
],
backgroundColor: colorAppBar,
elevation: 0,
),
body: _currentPage,
bottomNavigationBar: buildBottomNavigationBar(),
);
}
Widget buildBottomNavigationBar() {
return BottomNavigationBar(
type: BottomNavigationBarType.fixed,
elevation: 0,
backgroundColor: colorAppBar,
items: [
BottomNavigationBarItem(
icon: Icon(Icons.calendar_today,
color:
_indexCurrentPage == 0 ? defaultCustomColor : Colors.black38),
title: Text('Eventos',
style: TextStyle(
color: _indexCurrentPage == 0
? defaultCustomColor
: Colors.black38)),
),
BottomNavigationBarItem(
icon: Icon(Icons.landscape,
color:
_indexCurrentPage == 1 ? defaultCustomColor : Colors.black38),
title: Text('Atrativos',
style: TextStyle(
color: _indexCurrentPage == 1
? defaultCustomColor
: Colors.black38)),
),
BottomNavigationBarItem(
icon: Icon(Icons.place,
color:
_indexCurrentPage == 2 ? defaultCustomColor : Colors.black38),
title: Text('Pontos',
style: TextStyle(
color: _indexCurrentPage == 2
? defaultCustomColor
: Colors.black38)),
),
BottomNavigationBarItem(
icon: Icon(Icons.trip_origin,
color:
_indexCurrentPage == 3 ? defaultCustomColor : Colors.black38),
title: Text('Roteiros',
style: TextStyle(
color: _indexCurrentPage == 3
? defaultCustomColor
: Colors.black38)),
),
],
onTap: navigationTapped,
currentIndex: _indexCurrentPage,
);
}
void navigationTapped(int page) {
setState(() {
_indexCurrentPage = page;
_currentPage = _pages[page];
});
}
_getCidadeEscolhida() async {
Cidade _cidade = await CidadeBloc.getCidadeEscolhida();
setState(() {
widget.title += " ${_cidade.nome}";
});
}
_checkCidadeEscolhida(BuildContext context) async {
// Caso a cidade ainda não tenha sido escolhida o usuário será
// redirecionado para a página das cidades
try {
int idCidade = await CidadeBloc.getIDCidadeEscolhida();
if (idCidade == null) {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => CidadesPage()),
);
}
} catch (error) {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => CidadesPage()),
);
}
}
initPlatformState() async {
// Recuperando a localização atual
var _location = await location.getLocation();
try {
if (_location != null) {
CurrentLocationData _currentLocationData = CurrentLocationData();
_currentLocationData.latitude = _location.latitude;
_currentLocationData.longitude = _location.longitude;
currentLocation = _location;
}
} on PlatformException catch (e) {
_location = null;
// Tratando dos erros
if (e.code == 'PERMISSION_DENIED') {
error = 'Permission denied';
} else if (e.code == 'PERMISSION_DENIED_NEVER_ASK') {
error =
'Permission denied - please ask the user to enable it from the app settings';
}
location.onLocationChanged().listen((_location) {
if (_location != null) {
CurrentLocationData _currentLocationData = CurrentLocationData();
_currentLocationData.latitude = _location.latitude;
_currentLocationData.longitude = _location.longitude;
currentLocation = _location;
}
});
}
// Verificando se há mudança de localização
location.onLocationChanged().listen((LocationData _location) {
CurrentLocationData _currentLocationData = CurrentLocationData();
_currentLocationData.latitude = _location.latitude;
_currentLocationData.longitude = _location.longitude;
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment