本文介绍了Flutter:从其他页面访问存储的Sharedpreference值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在将值存储在名为page1.dart
的页面中.我想从page2.dart
或page3.dart
访问存储的值.我该如何实现?
I'm storing a value in a page called page1.dart
. I want to access the stored value from page2.dart
or page3.dart
. How can I achieve this?
推荐答案
我已经在第一个屏幕中存储了一个字符串,然后通过以下代码从第二个屏幕中检索了存储的值
I have stored a string in 1st screen,then retrieved the stored value from the second screen by the following code
第1页:
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:trial/class2.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String _email = '';
@override
void initState() {
super.initState();
_loadCounter();
}
_loadCounter() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
_email = (prefs.getString('email') ?? '');
});
}
_incrementCounter() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
_email = "[email protected]";
});
prefs.setString('email', _email);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("title"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'$_email',
),
new RaisedButton(
child: new Text("next2"),
onPressed: () {
Navigator.push(context,
new MaterialPageRoute(builder: (context) => new Next()));
},
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
child: Icon(Icons.add),
),
);
}
}
第2页:
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
String _email='';
class Next extends StatefulWidget {
@override
_NextState createState() => _NextState();
}
class _NextState extends State<Next> {
@override
void initState() {
super.initState();
_loadCounter();
}
_loadCounter() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
_email = (prefs.getString('email')??'');
});
}
@override
Widget build(BuildContext context) {
return Container(
child: new Text("read value from sharepreference is:"+_email),
);
}
}
这篇关于Flutter:从其他页面访问存储的Sharedpreference值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!