首页 > 解决方案 > RangeError(开始):无效值:只有有效值是 0:-16 - FLUTTER

问题描述

我正在尝试在本地加密密码,它是在用户希望时创建或更改的。但是当我尝试从用户界面更改它时,我收到此错误:

Unhandled Exception: RangeError (start): Invalid value: Only valid value is 0: -16.

虽然该应用程序仍然有效。这是类代码:

 class SettingsPage extends  StatefulWidget {
  @override
  _State createState() => _State();
  static String routeName = '/settings';
  static bool switched = false;
  static String inputPassword = '0000';
}

class _State extends State<SettingsPage> {

  static final key = encrypt.Key.fromLength(32);
  static final  iv = encrypt.IV.fromLength(1);
  static final encrypter = encrypt.Encrypter(encrypt.AES(key));

  static encryptAES(text) {
    final encrypted = encrypter.encrypt(text, iv: iv);

    print(encrypted.bytes);
    print(encrypted.base16);
    print(encrypted.base64);
    return encrypted;
  }

  static decryptAES(text) {
    return encrypter.decrypt(text, iv: iv);
  }

  TextEditingController tec = TextEditingController();
  var encryptedText, plainText;

  Future<void> localAuth(BuildContext context) async {
    final localAuth = LocalAuthentication();
    final didAuthenticate = await localAuth.authenticateWithBiometrics(
        localizedReason: 'Please authenticate');
    if (didAuthenticate) {
      Navigator.pop(context);
    }
  }

  Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
  late SharedPreferences prefs;

  getSwitchValues() async {
    SettingsPage.switched = await getSwitchState();
    setState(() {});
  }

  getPassValues() async{
    prefs = await _prefs;
    setState(() {
      prefs.containsKey('savedPass')? prefs.getString('savedPass'): "";
      setState(() {
      });
    });
  }

  @override
  void initState() {
    super.initState();
    getSwitchValues();
    getPassValues();
  }

  Future<bool> getSwitchState() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    SettingsPage.switched = prefs.getBool("switched")!;
    print(SettingsPage.switched);

    return SettingsPage.switched;
  }

  Future<bool> saveSwitchState(bool value) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setBool("switched", value);
    print('Switch Value saved $value');
    return prefs.setBool("switched", value);
  }



  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(paddingSizeLarge),
      child:
      Column(
        children: [
         Text('SETTINGS',
          style: GoogleFonts.encodeSansSemiCondensed(fontSize: 35.0, fontWeight: FontWeight.w700,color: Palette.secondaryTextColor),
          textAlign: TextAlign.center,
           ),
          VerticalSpacing(of: marginSizeDefault),
        Container(
         child:
          ListView(
            shrinkWrap: true,
            padding: EdgeInsets.all(paddingSizeDefault),
            children: [
              Row(
                children:[
              Text('Activate Biometrics : ',
                style: GoogleFonts.encodeSansSemiCondensed(fontSize: 20.0, fontWeight: FontWeight.w700,color: Palette.textColor),),
              HorizontalSpacing(of: marginSizeXXLarge),
              Switch(
                 value: SettingsPage.switched,
                  onChanged: (value) {
                  setState(() {
                    SettingsPage.switched = value;
                    saveSwitchState(SettingsPage.switched);
                  });
                  screenLock(context: context, correctString: '1234',
                    canCancel: true,
                    customizedButtonTap: () async {
                      await localAuth(context);
                    },
                    didOpened: () async {
                      await localAuth(context);
                    },);
                  },
                  activeTrackColor: Colors.blue,
                  activeColor: Colors.blue,
                  ),
                ]),
              VerticalSpacing(of: marginSizeLarge),
           /*   Row(
               children:[
              Text('Biometrics Settings : ',
                style: GoogleFonts.encodeSansSemiCondensed(fontSize: 20.0, fontWeight: FontWeight.w700,color: Palette.textColor),),
                 HorizontalSpacing(of: marginSizeXXLarge),
                 IconButton(onPressed: (){ print('bio set');} ,  icon: const Icon(FeatherIcons.arrowRight, color: Colors.black,))
               ]),
              VerticalSpacing(of:  marginSizeLarge),*/
              Row(
                  children:[
              Text('Create/Change Password : ',
                style: GoogleFonts.encodeSansSemiCondensed(fontSize: 20.0, fontWeight: FontWeight.w700,color: Palette.textColor),),

              IconButton( icon: const Icon(FeatherIcons.arrowRight, color: Colors.black,),
                  onPressed: () async {
                          final result = await
                          showOkCancelAlertDialog(
                          context: context,
                          title: 'Change or Create a new Password',
                          message:
                          'This will remove your existing Password or create a new one',
                           );

                          if (result == OkCancelResult.ok) {

                            final input = (await showTextInputDialog(
                              textFields: [DialogTextField(keyboardType: TextInputType.numberWithOptions(decimal: true),
                                            ),
                                          ],
                              context: context,
                              title: 'Change or Create a new Password',
                              message: 'enter your new password',
                            ))!.join();

                            if (input != null && input.length > 0 && input.length == 4 ) {

                              context.read<SettingsBloc>().changePassword(input);
                                SettingsPage.inputPassword = input;
                                 SettingsPage.inputPassword = tec.text;
                              setState(() {
                                encryptedText = encryptAES(SettingsPage.inputPassword);
                                 print("PROVA ENCRYPTED TEXT "+encryptedText);
                              });
                                 prefs.setString('savedPass', encryptedText);
                                 encryptedText = decryptAES(encryptedText);
                                 print("PROVA TESTO DECRIPTATO " + encryptedText);
                            }
                          }
                        },
                      ),
                   ]),
              VerticalSpacing(of:  50),
              RoundedButton(text:'Log Out',),
            ],
         ),
          decoration: new BoxDecoration(
            color: Palette.primaryLightColor,
            borderRadius: BorderRadius.circular(20),
            boxShadow: [
              BoxShadow(color: Palette.backgroundColor,
              ),
            ],
          ),
        ),
       ]
      ),
    );

  }

}

两个文本都不会使用打印功能写入提示。条件内一定有问题,另外我在更改密码时遇到错误,请如果有人知道如何帮助我,请出面谢谢。

标签: flutterdartencryptionpasswords

解决方案


推荐阅读