jeudi 19 septembre 2019

How to clear whole form on clear button click in flutter

How to clean the whole form when the user clicks the clear button. i've tried but when I am pressing the clear button it will not clear the Terms and condition checkbox and Dropdown.

So I want that when the user presses the clear button it will clear whole form.

Here is Code i've tried. Hope you understand the question. you help will be appreciated.

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




Aucun commentaire:

Enregistrer un commentaire