如何在flutter中使用共享首选项?

时间:2020-10-13 12:15:49

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

1 个答案:

答案 0 :(得分:1)

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

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

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