Created
April 17, 2018 20:32
-
-
Save slightfoot/df8acd03858ff9d3750c7f3af25c3433 to your computer and use it in GitHub Desktop.
Flutter PageStorage Example. Counter displayed will always be the same as the page index. Note: PageStorageKey parameter must be unique within the Route.
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 'package:flutter/material.dart'; | |
import 'package:meta/meta.dart'; | |
void main() => runApp(new MyApp()); | |
class MyApp extends StatelessWidget { | |
Widget build(BuildContext context) { | |
return new MaterialApp( | |
title: 'Page Test', | |
home: new Scaffold( | |
appBar: AppBar(title: Text("Home")), | |
body: new PageView.builder( | |
itemBuilder: (BuildContext context, int index) => | |
new TestPage(index: index, key: new PageStorageKey<String>('page-$index')), | |
itemCount: 3, | |
)), | |
); | |
} | |
} | |
class TestPage extends StatefulWidget { | |
final int index; | |
TestPage({Key key, @required this.index}) : super(key: key); | |
@override | |
TestPageState createState() => new TestPageState(); | |
} | |
int _globalCounter = 0; | |
class TestPageState extends State<TestPage> { | |
int _counter; | |
@override | |
void didChangeDependencies() { | |
super.didChangeDependencies(); | |
int value = PageStorage.of(context).readState(context); | |
if (value == null) { | |
_counter = _globalCounter++; | |
PageStorage.of(context).writeState(context, _counter); | |
} else { | |
_counter = value; | |
} | |
} | |
@override | |
Widget build(BuildContext context) { | |
return new Center(child: new Text("Page #${widget.index}\nCounter #$_counter")); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I don't see where the
PageStorage
widget (withPageStorageBucket
) initialized.