我有一个简单的应用程序,它在应用程序栏中将路由命名为有状态的小部件。当前,每当我离开有状态窗口小部件并再次返回时,有状态窗口小部件都会丢失其状态(在这种情况下,我的计数器会回到0)。我希望有状态的小部件保持其状态,但是我不确定自己做错了什么。我需要明确保持状态吗?怎么样?我应该使用didUpdateWidget
来转移状态吗?还是其他?
这是我的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;
}
},
));
}
这是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),
),
);
}
}