Skip to content

Instantly share code, notes, and snippets.

@slightfoot
Created April 17, 2018 20:32
Show Gist options
  • Save slightfoot/df8acd03858ff9d3750c7f3af25c3433 to your computer and use it in GitHub Desktop.
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.
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"));
}
}
@bambinoua
Copy link

I don't see where the PageStorage widget (with PageStorageBucket) initialized.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment