I have a simple app, it has named route in an appbar to a stateful widget. Currently, whenever I navigate away from the stateful widget and back again, the stateful widget loses its state (in this case my counter goes back to 0). I'd like the stateful widget to keep its state, but I'm not sure what I'm doing wrong. Do I need to explicitly keep state around? How? Should I be using didUpdateWidget
to transfer state? Or something else?
This is my main.dart:
import 'dart:async';
import 'package:flutter/material.dart';
import './pages/home_page.dart';
import './pages/counter_page.dart';
void main()
{
CounterPage counterPage = new CounterPage();
return runApp(new MaterialApp(
home: new HomePage(),
theme: new ThemeData.dark(),
routes: <String, WidgetBuilder> {
"main": (BuildContext context) => new HomePage(),
'counter_page': (BuildContext context) {
return counterPage;
}
},
));
}
This is the counter_page.dart
import 'dart:async';
import 'package:flutter/material.dart';
class CounterPage extends StatefulWidget {
static String route = "counter_page";
CounterPage();
@override
_CounterPageState createState() => _CounterPageState();
}
class _CounterPageState extends State<CounterPage> {
int _counter;
@override
void initState() {
super.initState();
_counter = 0;
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("Count"),
),
body: new Text("$_counter"),
floatingActionButton: new FloatingActionButton(
onPressed: () => setState(() {_counter += 1;}),
tooltip: 'Count',
child: new Icon(Icons.refresh),
),
);
}
}