不能更改布尔值

时间:2020-10-21 01:45:38

标签: flutter dart

isValidated值始终为false,当我输入正确的密码(1234)时它变为true,但立即返回为false。如果我输入正确的密码,则该值必须为true,否则必须为false。

但是它不能正常工作。

我以这种方式创建了我的应用验证,但我愿意接受任何建议。

class Validation extends StatefulWidget {
  final bool isValidated;
  Validation({this.isValidated = false});
  @override
  _ValidationState createState() => _ValidationState();
}

class _ValidationState extends State<Validation> {
  bool _isValidated;
  @override
  void initState() {
    super.initState();
    _isValidated = widget.isValidated;
  }

  @override
  Widget build(BuildContext context) {
    Utils().init(context);
    final screens = Utils.screen;
    final _formKey = GlobalKey<FormState>();
    final _passwordController = TextEditingController();

    _validator() {
      if (_passwordController.text != '1234') {
        return Alert();
      } else {
        setState(() {
          _isValidated = !_isValidated;
        });
      }
    }

    _textField() {
      return SizedBox(
        width: screens.width * 0.2,
        height: screens.height * 0.08,
        child: TextFormField(
          controller: _passwordController,
          textAlign: TextAlign.center,
          decoration: InputDecoration(
            filled: true,
            fillColor: Colors.white,
            contentPadding: EdgeInsets.all(0),
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(10),
            ),
          ),
        ),
      );
    }

    _enterButton() {
      return FlatButton(
        color: Colors.white,
        shape: OutlineInputBorder(
          borderRadius: BorderRadius.circular(10),
        ),
        child: Text(
          'Entrar',
          style: kSmallBlackButtonTextStyle,
        ),
        onPressed: () {
          _validator();
        },
      );
    }

    _validationForm() {
      return Form(
        key: _formKey,
        autovalidate: false,
        child: Column(
          children: <Widget>[
            _textField(),
            DefaultDivider(0.03),
            _enterButton(),
          ],
        ),
      );
    }

    _blackPanel() {
      return Center(
        child: Container(
          width: screens.width * 0.35,
          height: screens.height * 0.4,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(20),
            color: kBlackColor,
          ),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(
                'Identificação para acessar Uber',
                style: k20RegularTextStyle,
              ),
              DefaultDivider(0.03),
              Text(
                'Senha',
                style: k20MediumTextStyle,
              ),
              DefaultDivider(0.02),
              _validationForm(),
            ],
          ),
        ),
      );
    }

    _notValidated() {
      return Stack(
        children: <Widget>[
          BackdropFilter(
            filter: ImageFilter.blur(sigmaX: 4, sigmaY: 4),
            child: Container(color: kValidationBG),
          ),
          _blackPanel(),
        ],
      );
    }

    _validated() {
      return Stack(children: [
        Container(
          width: screens.width * 0.001,
          height: screens.height * 0.001,
        ),
      ]);
    }

    print('$_isValidated');
    return _isValidated == false ? _notValidated() : _validated();
  }
}

1 个答案:

答案 0 :(得分:2)

您可以在下面复制粘贴运行完整代码
您需要从final _passwordController = TextEditingController();中移出build 避免在重建小部件时重置_passwordController

  final _formKey = GlobalKey<FormState>();
  final _passwordController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    _validator() {
      if (_passwordController.text != '1234') {
        return Text("Alert()");
      } else {
        setState(() {
          _isValidated = !_isValidated;
        });
      }
    }

工作演示

enter image description here

完整的测试代码

import 'package:flutter/material.dart';
import 'dart:ui';

class Validation extends StatefulWidget {
  final bool isValidated;
  Validation({this.isValidated = false});
  @override
  _ValidationState createState() => _ValidationState();
}

class _ValidationState extends State<Validation> {
  bool _isValidated;
  @override
  void initState() {
    super.initState();
    _isValidated = widget.isValidated;
  }

  final _formKey = GlobalKey<FormState>();
  final _passwordController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    _validator() {
      if (_passwordController.text != '1234') {
        return Text("Alert()");
      } else {
        setState(() {
          _isValidated = !_isValidated;
        });
      }
    }

    _textField() {
      return SizedBox(
        width: MediaQuery.of(context).size.width * 0.2,
        height: MediaQuery.of(context).size.height * 0.08,
        child: TextFormField(
          controller: _passwordController,
          textAlign: TextAlign.center,
          decoration: InputDecoration(
            filled: true,
            fillColor: Colors.white,
            contentPadding: EdgeInsets.all(0),
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(10),
            ),
          ),
        ),
      );
    }

    _enterButton() {
      return FlatButton(
        color: Colors.white,
        shape: OutlineInputBorder(
          borderRadius: BorderRadius.circular(10),
        ),
        child: Text(
          'Entrar',
          //style: kSmallBlackButtonTextStyle,
        ),
        onPressed: () {
          _validator();
        },
      );
    }

    _validationForm() {
      return Form(
        key: _formKey,
        autovalidate: false,
        child: Column(
          children: <Widget>[
            _textField(),
            Divider(),
            _enterButton(),
          ],
        ),
      );
    }

    _blackPanel() {
      return Center(
        child: Container(
          width: MediaQuery.of(context).size.width * 0.35,
          height: MediaQuery.of(context).size.height * 0.4,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(20),
            //color: kBlackColor,
          ),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(
                'Identificação para acessar Uber',
                //style: k20RegularTextStyle,
              ),
              Divider(),
              Text(
                'Senha',
                //style: k20MediumTextStyle,
              ),
              Divider(),
              _validationForm(),
            ],
          ),
        ),
      );
    }

    _notValidated() {
      return Stack(
        children: <Widget>[
          BackdropFilter(
            filter: ImageFilter.blur(sigmaX: 4, sigmaY: 4),
            child: Container(),
          ),
          _blackPanel(),
        ],
      );
    }

    _validated() {
      return Stack(children: [
        Container(
          child: Text("Validate")
        ),
      ]);
    }

    print('$_isValidated');
    return _isValidated == false ? _notValidated() : _validated();
  }
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Validation(),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}