如何在flutter中使用共享首选项? [英] how to use shared preferences in flutter?

查看:106
本文介绍了如何在flutter中使用共享首选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的flutter应用程序中添加共享的首选项,以使用户即使关闭该应用程序也可以登录.有人可以帮助我提供代码吗?我已经添加了共享首选项,因为必须添加它们,但是我不确定如何在其中保存电话号码.有人可以编辑代码以正确使用它,或告诉正确的执行方法.

I wanted to add shared preferences in my flutter app to make the user logged in even if he closes the app. can someone help me with the code ? I have added the shared preference as they have to be added but i am not sure how to save the phone number there. Can someone edit the code to use it properly or tell the proper way it should be done.

登录页面.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

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()));
}

推荐答案

您只需在所有未命名函数之外获取一次实例:

You only have to acquire an instance once, outside of any unnamed functions:

  SharedPreferences prefs = await SharedPreferences.getInstance();

由于这是异步api,因此最好在加载"界面中完成此操作.或飞溅"屏幕或任何替换.您的main()不应是异步的.异步获取实例后,可以同步获取其值.

Since this is an async api, this is better done in a "loading" or "splash" screen or any replacement. Your main() should not be async. After you asynchroniously got the instance, you can get it's values synchroniously.

SharedPrefs是一个键值存储,因此您需要一个键:

SharedPrefs is a key-value storage, so you need a key:

const String key = "key";

此后,您可以设置以下任何值:

After this you can set any values like this:

prefs.setString(key, "value");

或创建一个服务类,通过以下功能为您完成此任务:

or create a service class that does this for you with functions like these:

  String get(final String key) =>
      prefs.getString(key);

  Future<void> set(final String key, final String value) => 
      prefs.setString(key, value);

请注意,您获得的实例将不会立即收到更新.您的值应单独存储在内存中,并且应该从偏好中获取一次,例如在应用启动时

Note that the instance you got will not immediately receive updates. your value should be stored separately in memory, and should be fetched from prefernces once, for example when the app is starting

这篇关于如何在flutter中使用共享首选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆