[英]how to use shared preferences in flutter?
我想在我的 flutter 应用程序中添加共享首选项,以使用户即使关闭应用程序也能登录。 有人可以帮我写代码吗? 我添加了共享首选项,因为它们必须添加,但我不确定如何在那里保存电话号码。 有人可以编辑代码以正确使用它或告诉它应该以正确的方式完成。
登录页面.dart -
import 'package:flutter/material.dart';
import 'package:flutter_on_field/API/api.dart';
import 'package:shared_preferences/shared_preferences.dart';
final _phoneController=TextEditingController();
final _passwordController=TextEditingController();
// ignore: non_constant_identifier_names
String your_mobile_number;
String password;
class MyApp extends StatefulWidget {
MyApp({Key key}) : super(key:key);
@override
_my_appState createState(){
return _my_appState();
}
}
// ignore: camel_case_types
class _my_appState extends State<MyApp> {
@override
Widget build(BuildContext context)
{
return new MaterialApp(
debugShowCheckedModeBanner: false,
home: new LoginPage(),
theme: new ThemeData(
primarySwatch: Colors.blue
)
);
}
}
class LoginPage extends StatefulWidget {
@override
State createState() => new LoginPageState();
}
class LoginPageState extends State<LoginPage> with SingleTickerProviderStateMixin {
AnimationController _iconAnimationController;
Animation<double> _iconAnimation;
GlobalKey<FormState> _key = new GlobalKey();
bool _validate = false;
bool _obscureText = true;
bool _passwordVisible = false;
String session;
@override
void initStage() {
super.initState();
_passwordVisible = false;
_iconAnimationController = new AnimationController(
duration: new Duration(milliseconds: 500), vsync: null
);
_iconAnimation = new CurvedAnimation(
parent: _iconAnimationController,
curve: Curves.bounceInOut
);
_iconAnimation.addListener(() => this.setState(() {}));
_iconAnimationController.forward();
}
List<Color> _colors = [
Colors.black,
];
int _currentIndex = 0;
_onChanged() {
//update with a new color when the user taps button
int _colorCount = _colors.length;
setState(() {
if (_currentIndex == _colorCount - 1) {
_currentIndex = 0;
} else {
_currentIndex += 1;
}
});
}
@override
Widget build(BuildContext context) {
return new Scaffold(
backgroundColor: Colors.white,
body: new Stack(
fit: StackFit.expand,
children: <Widget>[
new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new FlutterLogo(
size: 100,
),
new Form(
child: new Theme(
data: new ThemeData(
brightness: Brightness.dark, primarySwatch: Colors.teal,
inputDecorationTheme: new InputDecorationTheme(
labelStyle: new TextStyle(
color: Colors.blue,
fontSize: 20.0
),
)
),
child: new Container(
padding: const EdgeInsets.all(40.0),
child: new Form(
key: _key,
// ignore: deprecated_member_use
autovalidate: _validate,
child: getForm(),
)
),
),
),
],
)
],
),
);
}
Widget getForm(){
return new Column(
children: [
new TextFormField(
decoration: new InputDecoration(
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
borderSide: BorderSide(
color: Colors.blue,
),
),
labelText: "Enter Phone Number",
),
controller: _phoneController,
style: TextStyle(color: _colors[_currentIndex]),
keyboardType: TextInputType.phone,
maxLength: 10,
validator: validateMobile,
onSaved: (String val) {
your_mobile_number = val;
}
),
new TextFormField(
obscureText: !_passwordVisible,
decoration: new InputDecoration(
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
borderSide: BorderSide(
color: Colors.blue,
),
),
labelText: "Enter Password",
suffixIcon: IconButton(
icon: Icon(
// Based on passwordVisible state choose the icon
_passwordVisible
? Icons.visibility
: Icons.visibility_off,
color: Theme
.of(context)
.primaryColorDark,
),
onPressed: () {
// Update the state i.e. toogle the state of passwordVisible variable
setState(() {
_passwordVisible = !_passwordVisible;
});
},
),
),
controller: _passwordController,
style: TextStyle(color: _colors[_currentIndex]),
keyboardType: TextInputType.text,
onSaved: (String pass) {
password = pass;
}
),
new Padding(
padding: const EdgeInsets.only(top: 40.0),
),
new SizedBox(height: 15.0),
new RaisedButton(
color: Colors.blue,
onPressed: () async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('phone', 'phoneNo.');
await _submit();
print('hi');
print(your_mobile_number);
print(password);
},
child: new Text('Login'),
),
],
);
}
String validateMobile(String value) {
String patttern = r'(^[0-9]*$)';
RegExp regExp = new RegExp(patttern);
if (value.length == 0) {
return "Mobile is Required";
} else if (value.length != 10) {
return "Mobile number must 10 digits";
} else if (!regExp.hasMatch(value)) {
return "Mobile Number must be digits";
}
return null;
}
_submit() {
{
if (_key.currentState.validate()) {
// No any error in validation
_key.currentState.save();
Navigator.push(context, new MaterialPageRoute(
builder: (BuildContext context) => MyAppp())
);
}
else {
// validation error
setState(() {
_validate = true;
});
}
}
}
}
main.dart
import 'package:flutter/material.dart';
import 'package:flutter_on_field/screens/HomeScreen.dart';
import 'package:flutter_on_field/screens/LoginPage.dart';
import 'package:shared_preferences/shared_preferences.dart';
// void main() => runApp(new MyApp());
// ignore: non_constant_identifier_names
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
SharedPreferences prefs = await SharedPreferences.getInstance();
var phone = prefs.getString('phone');
print(phone);
runApp(MaterialApp(home: phone == null ? LoginPage() : HomeScreen()));
}
在任何未命名函数之外,您只需获取一次实例:
SharedPreferences prefs = await SharedPreferences.getInstance();
由于这是一个异步 api,因此最好在“加载”或“启动”屏幕或任何替代品中完成。 你的 main() 不应该是异步的。 异步获取实例后,您可以同步获取它的值。
SharedPrefs 是一个键值存储,所以你需要一个键:
const String key = "key";
在此之后,您可以设置任何值,如下所示:
prefs.setString(key, "value");
或创建一个服务类,使用以下功能为您执行此操作:
String get(final String key) =>
prefs.getString(key);
Future<void> set(final String key, final String value) =>
prefs.setString(key, value);
请注意,您获得的实例不会立即收到更新。 您的值应该单独存储在内存中,并且应该从首选项中获取一次,例如在应用程序启动时
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.