Не удается изменить логическое значение

#flutter #dart

#флаттер #dart

Вопрос:

Значение isValidated всегда равно false, оно становится true, когда я пишу правильный пароль (1234), но он мгновенно возвращается к 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. Если бы мне пришлось угадывать, я бы сказал, что ваш виджет воссоздается откуда-то из дерева виджетов.

Ответ №1:

Вы можете скопировать вставить запустить полный код ниже
, из которого вам нужно выйти final _passwordController = TextEditingController(); , build чтобы избежать сброса виджета rebuild _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;
        });
      }
    }
  

рабочая демонстрация

введите описание изображения здесь

полный тестовый код

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