Skip to content

Commit

Permalink
{beam_location}: [add] onUpdate
Browse files Browse the repository at this point in the history
	- closes #507
  • Loading branch information
slovnicki committed Jun 10, 2022
1 parent cc2c265 commit 88c8537
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 10 deletions.
25 changes: 15 additions & 10 deletions examples/books_bloc/lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,7 @@ class HomeScreen extends StatelessWidget {
),
body: Center(
child: ElevatedButton(
onPressed: () => context
..read<BooksBloc>().add(LoadBooks())
..beamToNamed('/books'),
onPressed: () => context.beamToNamed('/books'),
child: Text('See books'),
),
),
Expand All @@ -40,9 +38,7 @@ class BooksScreen extends StatelessWidget {
(book) => ListTile(
title: Text(book.title),
subtitle: Text(book.author),
onTap: () => context
..read<BooksBloc>().add(LoadBook(book.id))
..beamToNamed('/books/${book.id}'),
onTap: () => context.beamToNamed('/books/${book.id}'),
),
)
.toList(),
Expand Down Expand Up @@ -83,13 +79,22 @@ class BookDetailsScreen extends StatelessWidget {

// LOCATIONS
class BooksLocation extends BeamLocation<BeamState> {
BooksLocation() : super() {
addListener(_listener);
late BooksBloc _booksBloc;

@override
void initState() {
super.initState();
_booksBloc = BooksBloc();
}

final BooksBloc _booksBloc = BooksBloc();
@override
void disposeState() {
_booksBloc.close();
super.disposeState();
}

void _listener() {
@override
void onUpdate() {
if (state.pathPatternSegments.isEmpty) return;

final bookId = state.pathParameters.containsKey('bookId')
Expand Down
7 changes: 7 additions & 0 deletions package/lib/src/beam_location.dart
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,12 @@ abstract class BeamLocation<T extends RouteInformationSerializable>
state = createState(routeInformation);
}

/// Called after [initState] and on each [update],
/// i.e. whenever we navigate with this [BeamLocation].
///
/// Useful for delegating some tasks that depend on navigation.
void onUpdate() {}

/// How to release any resources used by [state].
///
/// Override this if
Expand Down Expand Up @@ -248,6 +254,7 @@ abstract class BeamLocation<T extends RouteInformationSerializable>
);
}
}
onUpdate();
if (rebuild) {
notifyListeners();
}
Expand Down
1 change: 1 addition & 0 deletions package/lib/src/beamer_delegate.dart
Original file line number Diff line number Diff line change
Expand Up @@ -846,6 +846,7 @@ class BeamerDelegate extends RouterDelegate<RouteInformation>

void _initBeamLocation(BeamLocation beamLocation) {
beamLocation.initState();
beamLocation.onUpdate();
beamLocation.addListener(_updateFromCurrentBeamLocation);
}

Expand Down

0 comments on commit 88c8537

Please sign in to comment.