【问题标题】:how to use shared preferences in flutter?如何在颤振中使用共享偏好?
【发布时间】:2021-01-27 18:49:17
【问题描述】:

我想在我的 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 pattern = r'(^[0-9]*$)';
    RegExp regExp = new RegExp(pattern);

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

【问题讨论】:

    标签: flutter


    【解决方案1】:

    在任何未命名的函数之外,您只需获取一次实例:

      SharedPreferences prefs = await SharedPreferences.getInstance();
    

    由于这是一个异步 API,最好在“加载”或“启动”屏幕或任何替换屏幕中完成。您的 main() 不应该是异步的。异步获取实例后,就可以同步获取它的值了。

    SharedPrefs是key-value存储,所以需要key:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-11
      • 1970-01-01
      • 2021-12-31
      • 1970-01-01
      • 2020-11-08
      • 1970-01-01
      • 1970-01-01
      • 2021-01-13
      相关资源
      最近更新 更多