我有一个简单的应用程序,它在应用程序栏中将路由命名为有状态小部件。目前,每当我离开有状态小部件并再次返回时,有状态小部件就会失去其状态(在这种情况下,我的计数器会回到 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),
),
);
}
}