这是我的代码片段:
static DateTime chosenDate = DateTime.now();
String formattedDate = DateFormat('yyyy-MM-dd – kk:mm').format(chosenDate);
DateTime picked;
Future<Null> _selectDate(BuildContext context) async {
DateTime picked = await showDatePicker(
context: context,
initialDate: chosenDate,
firstDate: DateTime(2015, 8),
lastDate: DateTime(2101));
if (picked != null && picked != chosenDate)
setState(() {
chosenDate = picked;
});
}如何确保chosenDate可以在其他地方使用,比如在上述作用域之外显示chosenDate的活动。我已经在main.dart文件中将其声明为以下DateTime chosenDate;,但是当我在另一个屏幕上使用以下语句时,该值返回为null,并显示错误消息,指出找不到getter 'year‘,因此返回null:
class _FinalPageState extends State<FinalPage> {
@override
Widget build(BuildContext context) {
return Container(
child: Text("$formattedDate"),
);
}
}其中formattedDate为String formattedDate = DateFormat('yyyy-MM-dd – kk:mm').format(chosenDate);
另外,有没有人知道如何保存这个值,这样每次重启应用程序时,它都不会丢失?
发布于 2019-10-31 18:37:24
Provider等状态管理可能会对您有所帮助。看看这个https://medium.com/flutter-community/flutter-pragmatic-state-management-using-provider-5c1129f9b5bb
您可以简单地使用Provider类中定义的get和set函数来获取或设置这些值。
class DateSelector {
BuildContext context;
final state;
DateSelector(this.context) : state = Provider.of<AppState>(context);
Future<Null> _selectDate() async {
if (...) {
//you may need to change picked as the format you like
state.setChosenDate(picked);
}
}
}
class AppState with ChangeNotifier {
String _date;
getChosenDate() => _date;
setChosenDate(d) {
_date = d;
notifyListeners();
}}
//make sure the root class should be like
void main() {
runApp(new MyApp());}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider<AppState>(
builder: (_) => AppState(),
child: MaterialApp(
home: HomePage(),
debugShowCheckedModeBanner: false));
}
}//然后只需调用get方法就可以从任何屏幕访问它,例如。
@override
Widget build(BuildContext context) {
appState = Provider.of<AppState>(context);
....
....
Text(appState.getChosenDate())https://stackoverflow.com/questions/58641338
复制相似问题