Skip to content

Instantly share code, notes, and snippets.

@felangel
Created December 13, 2019 00:09
Show Gist options
  • Save felangel/68e2fd89d56de8866935e3f058d6e81b to your computer and use it in GitHub Desktop.
Save felangel/68e2fd89d56de8866935e3f058d6e81b to your computer and use it in GitHub Desktop.
[flutter_bloc] Location Stream Example
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:bloc/bloc.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:meta/meta.dart';
import 'package:geolocator/geolocator.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: BlocProvider<LocationBloc>(
create: (context) =>
LocationBloc(geolocator: Geolocator())..add(LocationStarted()),
child: Home(),
),
);
}
}
class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Home')),
body: BlocBuilder<LocationBloc, LocationState>(
builder: (context, state) {
if (state is LocationInitial) {
return Center(child: Text('Fetching Location'));
}
if (state is LocationLoadSuccess) {
return Center(
child: Text(
'Location: (${state.position.latitude}, ${state.position.longitude})',
),
);
}
return Center(child: CircularProgressIndicator());
},
),
);
}
}
@immutable
abstract class LocationEvent {}
class LocationStarted extends LocationEvent {}
class LocationChanged extends LocationEvent {
final Position position;
LocationChanged({@required this.position});
}
@immutable
abstract class LocationState {}
class LocationInitial extends LocationState {}
class LocationLoadInProgress extends LocationState {}
class LocationLoadSuccess extends LocationState {
final Position position;
LocationLoadSuccess({@required this.position});
}
class LocationBloc extends Bloc<LocationEvent, LocationState> {
final Geolocator _geolocator;
StreamSubscription _locationSubscription;
LocationBloc({@required Geolocator geolocator})
: assert(geolocator != null),
_geolocator = geolocator;
@override
LocationState get initialState => LocationInitial();
@override
Stream<LocationState> mapEventToState(
LocationEvent event,
) async* {
if (event is LocationStarted) {
yield LocationLoadInProgress();
_locationSubscription?.cancel();
_locationSubscription = _geolocator.getPositionStream().listen(
(Position position) => add(
LocationChanged(position: position),
),
);
} else if (event is LocationChanged) {
yield LocationLoadSuccess(position: event.position);
}
}
@override
Future<void> close() {
_locationSubscription?.cancel();
return super.close();
}
}
name: example
description: A new Flutter project.
version: 1.0.0+1
environment:
sdk: ">=2.1.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
bloc: ^2.0.0
equatable: ^1.0.0
flutter_bloc: ^2.1.0
geolocator: ^5.1.5
flutter:
uses-material-design: true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment