diff --git a/packages/flutter/lib/src/widgets/page_view.dart b/packages/flutter/lib/src/widgets/page_view.dart index 5e3a8b34d7..b71c16bde4 100644 --- a/packages/flutter/lib/src/widgets/page_view.dart +++ b/packages/flutter/lib/src/widgets/page_view.dart @@ -76,7 +76,31 @@ class PageController extends ScrollController { final double viewportFraction; /// The current page displayed in the controlled [PageView]. + /// + /// There are circumstances that this [PageController] can't know the current + /// page. Reading [page] will throw an [AssertionError] in the following cases: + /// + /// 1. No [PageView] is currently using this [PageController]. Once a + /// [PageView] starts using this [PageController], the new [page] + /// position will be derived: + /// + /// * First, based on the attached [PageView]'s [BuildContext] and the + /// position saved at that context's [PageStorage] if [keepPage] is true. + /// * Second, from the [PageController]'s [initialPage]. + /// + /// 2. More than one [PageView] using the same [PageController]. + /// + /// The [hasClients] property can be used to check if a [PageView] is attached + /// prior to accessing [page]. double get page { + assert( + positions.isNotEmpty, + 'PageController.page cannot be accessed before a PageView is built with it.', + ); + assert( + positions.length == 1, + 'Multiple PageViews cannot be attached to the same PageController.', + ); final _PagePosition position = this.position; return position.page; } diff --git a/packages/flutter/test/widgets/page_view_test.dart b/packages/flutter/test/widgets/page_view_test.dart index 19399de2b0..84cc2f3c34 100644 --- a/packages/flutter/test/widgets/page_view_test.dart +++ b/packages/flutter/test/widgets/page_view_test.dart @@ -594,6 +594,15 @@ void main() { testWidgets('PageView can restore page', (WidgetTester tester) async { final PageController controller = new PageController(); + try { + controller.page; + fail('Accessing page before attaching should fail.'); + } on AssertionError catch (e) { + expect( + e.message, + 'PageController.page cannot be accessed before a PageView is built with it.', + ); + } final PageStorageBucket bucket = new PageStorageBucket(); await tester.pumpWidget(new Directionality( textDirection: TextDirection.ltr, @@ -620,7 +629,15 @@ void main() { child: new Container(), ), ); - expect(() => controller.page, throwsAssertionError); + try { + controller.page; + fail('Accessing page after detaching all PageViews should fail.'); + } on AssertionError catch (e) { + expect( + e.message, + 'PageController.page cannot be accessed before a PageView is built with it.', + ); + } await tester.pumpWidget(new Directionality( textDirection: TextDirection.ltr, child: new PageStorage(