Как очистить всю форму при нажатии кнопки очистки во флаттере - PullRequest
0 голосов
/ 19 сентября 2019

Как очистить всю форму, когда пользователь нажимает кнопку очистки.Я пытался, но когда я нажимаю кнопку очистки, он не снимает флажок Условия и условия и выпадающий список.

Поэтому я хочу, чтобы, когда пользователь нажимает кнопку очистки, он очищал всю форму.

Вот код, который я пробовал.Надеюсь, вы понимаете вопрос.Ваша помощь будет оценена.

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:image/mobile_register_scree.dart';
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:geocoder/geocoder.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:image/page2.dart';
import 'package:pin_code_fields/pin_code_fields.dart';
import 'package:pin_entry_text_field/pin_entry_text_field.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:async';

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';

import 'package:shared_preferences/shared_preferences.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: SignupScreen(),
    );
  }
}

class SignupScreen extends StatefulWidget {
  @override
  _SignupScreenState createState() => new _SignupScreenState();
}

class _SignupScreenState extends State<SignupScreen> {
  final formKey = new GlobalKey<FormState>();
  bool _validate = false;
  List<Country> _countries = [];
  bool _obscureText = true;
  Person person = new Person();

  String passcode;
  final _emailFocusNode = new FocusNode();
  final _passwordFocusNode = new FocusNode();
  final _fnameFocuNode = new FocusNode();
  final _lnameFocusNode = new FocusNode();

  final TextEditingController _email = new TextEditingController();
  final TextEditingController _add = new TextEditingController();
  final TextEditingController _fn = new TextEditingController();
  final TextEditingController _ln = new TextEditingController();
  final TextEditingController _pho = new TextEditingController();
  final TextEditingController _pass = new TextEditingController();
  TextEditingController phoneController = new TextEditingController();
  static List<CountryModel> _dropdownItems = new List();
  String otpWaitTimeLabel = "";
  CountryModel _dropdownValue;
  TextEditingController otpcontroller = TextEditingController();
  String thisText = "";
  int pinLength = 6;
  bool hasError = false;
  bool showAlertBox = false;
  String errorMessage;
  SharedPreferences prefs;
  DateTime target;
  bool hasTimerStopped = false;

  final changeNotifier = StreamController<Functions>.broadcast();
  ValueChanged _onChanged = (val) => print(val);

  bool _submit() {
    final form = formKey.currentState;
    if (form.validate()) {
      form.save();
      return true;
    } else {
      return false;
    }
  }

  Widget _buildEmailField() {
    return TextFormField(
      controller: _email,
      focusNode: _emailFocusNode,
      decoration: new InputDecoration(
        prefixIcon: Icon(
          Icons.email,
        ),
        labelText: "Email",
        border: UnderlineInputBorder(),
        filled: false,
        hintText: 'Your email address',
      ),
      keyboardType: TextInputType.emailAddress,
      onSaved: (String value) {
        print('person');
        print(person);
        person.email = value.trim();
      },
    );
  }

  Widget _buildCountry(List<Country> countries) {
    if (countries.length > 0 && _dropdownItems.length != countries.length - 1) {
      print("countries list");
      print(countries[0].name);
      for (int i = 0; i < countries.length; i++) {
        if (countries[i].name.toLowerCase() != 'world') {
          _dropdownItems.add(
            CountryModel(
                country: countries[i].name, countryCode: countries[i].isdCode),
          );
        }
      }
    }
    return FormBuilder(
      autovalidate: true,
      initialValue: {},
      child: FormBuilderCustomField(
        attribute: "Country",
        validators: [
          FormBuilderValidators.required(),
        ],
        formField: FormField(
          builder: (FormFieldState<dynamic> field) {
            return DropdownButtonHideUnderline(
              child: new Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: <Widget>[
                  new InputDecorator(
                    decoration: InputDecoration(
                      filled: false,
                      hintText: 'Choose Country',
                      prefixIcon: Icon(Icons.location_on),
                      labelText: _dropdownValue == null
                          ? 'Where are you from'
                          : 'From',
                      errorText: field.errorText,
                    ),
                    isEmpty: _dropdownValue == null,
                    child: new DropdownButton<CountryModel>(
                      value: _dropdownValue,
                      isDense: true,
                      onChanged: (CountryModel newValue) {
                        print('value change');
                        print(newValue);
                        person.country = newValue.country;
                        person.countryCode = newValue.countryCode;
                        setState(() {
                          _dropdownValue = newValue;
                          phoneController.text = _dropdownValue.countryCode;
                          field.didChange(newValue);
                        });
                      },
                      items: _dropdownItems.map(
                        (CountryModel value) {
                          return DropdownMenuItem<CountryModel>(
                            value: value,
                            child: Text(value.country),
                          );
                        },
                      ).toList(),
                    ),
                  ),
                ],
              ),
            );
          },
        ),
      ),
    );
  }

  Widget _buildTermsAndContionsCheck() {
    return FormBuilderCheckbox(
      attribute: 'accept_terms',
      initialValue: false,
      onChanged: _onChanged,
      leadingInput: true,
      label: RichText(
        text: TextSpan(
          children: [
            TextSpan(
              text: 'I have read and agree to the ',
              style: TextStyle(color: Colors.black),
            ),
            TextSpan(
                text: 'Terms and Conditions',
                style: TextStyle(color: Colors.blue),
                recognizer: TapGestureRecognizer()
                  // ..onTap = () {
                  //   print("launch url");
                  // },
                  ..onTap = () => _launchURL()),
          ],
        ),
      ),
      validators: [
        FormBuilderValidators.requiredTrue(
          errorText: "You must accept terms and conditions to continue",
        ),
      ],
    );
  }

  Widget _buildSignupButton(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: <Widget>[
        new FlatButton.icon(
          icon: Icon(Icons.close),
          label: Text('Clear'),
          textColor: Colors.black,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(7),
          ),
          onPressed: () {
            _email.clear();
            _fn.clear();
            _ln.clear();
            _pho.clear();
            _add.clear();
            _pass.clear();
            mobilecontroller.clear();
          },
        ),
        new FlatButton.icon(
            icon: Icon(Icons.accessibility_new),
            label: Text('TUDO Sign Up'),
            color: Colors.amber,
            textColor: Colors.white,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(7),
            ),
            onPressed: () {
              if (formKey.currentState.validate()) {
                person.email = _email.text;
                person.phoneNumber = mobilecontroller.text;
                person.firstname = _fn.text;
                person.lastname = _ln.text;
                person.password = _pass.text;

                // _onAlertotp(signupVm);
                // } else {
                // print('Error: while sign up the user');
                // print(signupVm.error);
                // }
              }
            }),
        // _buildSignupButton(context, signupVm),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: AppBar(
        title: Text("Signup"),
        // leading: Icon(Icons.arrow_back_ios),
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios),
          onPressed: () {},
        ),
        centerTitle: true,
      ),
      body: Container(
        height: double.infinity,
        width: double.infinity,
        child: SafeArea(
          top: false,
          bottom: false,
          child: Form(
            key: formKey,
            autovalidate: _validate,
            child: Stack(
              children: <Widget>[
                // Background(),
                SingleChildScrollView(
                  dragStartBehavior: DragStartBehavior.down,
                  padding: const EdgeInsets.symmetric(horizontal: 16.0),
                  child: new Container(
                    margin: EdgeInsets.fromLTRB(30, 0, 30, 10),
                    child: new Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        _buildEmailField(),
                        _buildCountry(countries),
                        _buildTermsAndContionsCheck(),
                        _buildSignupButton(context),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

const List<Color> signInGradients = [
  Color(0xFF0EDED2),
  Color(0xFF03A0FE),
];

const List<Color> signUpGradients = [
  Color(0xFFFF9945),
  Color(0xFFFc6076),
];

class Person {
  String email = '';
  String country = '';
  String countryCode = '';
  String phoneNumber = '';
  String firstname = '';
  String lastname = '';
  String password = '';
  bool termsAndCondition = false;
}

class CountryModel {
  String country = '';
  String countryCode = '';

  CountryModel({
    this.country,
    this.countryCode,
  });
}

Ответы [ 3 ]

0 голосов
/ 19 сентября 2019

Если вы используете формы флаттера, вы можете просто сбросить всю форму.

Сделайте это в onPressed событии вашей кнопки clear

formKey.currentState.reset();

Это сбросит всю вашу форму, включая все видимые поля формы.

Надеюсь, это поможет.

0 голосов
/ 23 сентября 2019

Пожалуйста, замените _email.clear ();with _email.text = "";

Дайте мне знать, если какие-либо проблемы и не решили вашу проблему.

0 голосов
/ 19 сентября 2019
    On click on Clear button put all thing inside setstate() like below.  
    Widget _buildTermsAndContionsCheck(bool isSelected) {
        return FormBuilderCheckbox(
          attribute: 'accept_terms',
          initialValue: isSelected,

      }

      class _SignupScreenState extends State<SignupScreen> {
      bool isSelected=false;
      }
                     onPressed: () {
                          setState(() {
                          _email.clear();
                            _fn.clear();
                            _ln.clear();
                            _pho.clear();
                            _add.clear();
                            _pass.clear();
                             bool isSelected=false;
                            mobilecontroller.clear();        
                              });

                          }
...