Preview:
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:ghalam_jadoee/component/api_service.dart';
import 'package:ghalam_jadoee/component/body3.dart';
import 'package:ghalam_jadoee/component/user_textfield.dart';
import 'package:ghalam_jadoee/pages/bottomnav.dart';
import 'package:ghalam_jadoee/pages/sign.dart';
import 'package:shared_preferences/shared_preferences.dart';

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

String PUser = "";

class Moarf extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Referral Code Page',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: ReferralCodePage(),
    );
  }
}

final TextEditingController _nameController = TextEditingController();

class ReferralCodePage extends StatefulWidget {
  @override
  _ReferralCodePageState createState() => _ReferralCodePageState();
}

class _ReferralCodePageState extends State<ReferralCodePage> {
  final _formKey = GlobalKey<FormState>();
  final TextEditingController _referralCodeController = TextEditingController();
  String _message = '';
  bool _isButtonActive = false;

  @override
  void initState() {
    super.initState();
    _referralCodeController.addListener(_validateCode);
    _nameController.addListener(_validateCode);
  }

  void _validateCode() {
    setState(() {
      final code = _referralCodeController.text;
      final name = _nameController.text;
      _isButtonActive = name.isNotEmpty &&
          (code.isEmpty ||
              (code.length == 6 && RegExp(r'^[a-zA-Z0-9]+$').hasMatch(code)));
    });
  }

  Future<void> saveLogin(String PUser) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString("userkey", PUser);
    await prefs.setBool("loggedIn", true);
  }

  void _submitCode() async {
    if (_formKey.currentState?.validate() ?? false) {
      var name = _nameController.text;
      var referral = _referralCodeController.text;

      print("name");
      print(name);
      print("ph");
      print(SendPhone);
      print("rf");
      print(referral);
      PUser = SendPhone;
      String state = 's3';
      try {
        var jsonResponse =
            await ApiService.confirm(SendPhone, name, referral, state);
        setState(() {
          print(jsonResponse);
          _message = 'کد معرف وارد شده: $referral';
        });

        await saveLogin(PUser);

        Navigator.pushReplacement(
          context,
          MaterialPageRoute(builder: (context) => Bottomnav()),
        );
      } catch (e) {
        setState(() {
          _message = 'خطا در ارسال کد معرف: ${e.toString()}';
        });
      }
    }
  }

  void _clearCode() async {
    _referralCodeController.clear();

    if (_formKey.currentState?.validate() ?? false) {
      var name = _nameController.text;
      var referral = "0";

      print("name");
      print(name);
      print("ph");
      print(SendPhone);
      print("rf");
      print(referral);
      PUser = SendPhone;
      String state = 's3';
      try {
        var jsonResponse =
            await ApiService.confirm(SendPhone, name, referral, state);
        setState(() {
          print('jsonResponse');
          print(jsonResponse);

          _message = 'معرفی ندارم';
        });

        await saveLogin(PUser);

        Navigator.pushReplacement(
          context,
          MaterialPageRoute(builder: (context) => Bottomnav()),
        );
      } catch (e) {
        setState(() {
          _message = 'خطا در ارسال کد معرف: ${e.toString()}';
        });
      }
    }
  }

  @override
  void dispose() {
    _referralCodeController.removeListener(_validateCode);
    _nameController.removeListener(_validateCode);
    _referralCodeController.dispose();
    _nameController.dispose();
    super.dispose();
  }

  @override
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: () async {
          return false;
        },
        child: Scaffold(
          body: SingleChildScrollView(
              child: Container(
            height: MediaQuery.of(context).size.height,
            child: Stack(
              alignment: Alignment.center,
              children: [
                Body3(),
                Align(
                  alignment: Alignment.topCenter,
                  child: SingleChildScrollView(
                    child: Padding(
                      padding: EdgeInsets.only(
                          top: MediaQuery.of(context).size.height * 0.48),
                      child: Padding(
                        padding: const EdgeInsets.all(24.0),
                        child: Form(
                          key: _formKey,
                          child: Column(
                            mainAxisSize: MainAxisSize.min,
                            children: <Widget>[
                              UserNameTextField(controller: _nameController),
                              SizedBox(height: 30),
                              Align(
                                alignment: Alignment.centerRight,
                                child: const Text(
                                  ': کد معرف ',
                                  textAlign: TextAlign.end,
                                  style: TextStyle(
                                    fontSize: 20,
                                    fontWeight: FontWeight.w300,
                                  ),
                                ),
                              ),
                              SizedBox(height: 10),
                              Container(
                                alignment: Alignment.centerRight,
                                child: TextFormField(
                                  controller: _referralCodeController,
                                  decoration: InputDecoration(
                                    border: OutlineInputBorder(
                                      borderRadius: BorderRadius.circular(12),
                                    ),
                                    contentPadding: const EdgeInsets.symmetric(
                                      vertical: 16.0,
                                      horizontal: 12.0,
                                    ),
                                  ),
                                  maxLength: 6,
                                  validator: (value) {
                                    if (value != null && value.isNotEmpty) {
                                      if (value.length != 6) {
                                        return 'کد معرف باید ۶ کاراکتر باشد';
                                      } else if (!RegExp(r'^[a-zA-Z]+$')
                                          .hasMatch(value)) {
                                        return 'کد معرف باید فقط حاوی حروف انگلیسی باشد';
                                      }
                                    }
                                    return null;
                                  },
                                ),
                              ),
                              SizedBox(height: 20),
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceEvenly,
                                children: [
                                  TextButton(
                                    onPressed:
                                        _isButtonActive ? _submitCode : null,
                                    style: TextButton.styleFrom(
                                      foregroundColor: _isButtonActive
                                          ? Colors.blue
                                          : Colors.grey,
                                      padding: const EdgeInsets.symmetric(
                                        horizontal: 32,
                                        vertical: 12,
                                      ),
                                      textStyle: const TextStyle(
                                        fontSize: 16,
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                    child: const Text('ارسال'),
                                  ),
                                  TextButton(
                                    onPressed: _clearCode,
                                    style: TextButton.styleFrom(
                                      foregroundColor: Colors.red,
                                      padding: const EdgeInsets.symmetric(
                                        horizontal: 32,
                                        vertical: 12,
                                      ),
                                      textStyle: const TextStyle(
                                        fontSize: 16,
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                    child: const Text('معرفی ندارم'),
                                  ),
                                ],
                              ),
                              SizedBox(height: 20),
                              Text(
                                _message,
                                style: TextStyle(
                                  fontSize: 16,
                                  color: _message.contains('کد معرف وارد شده')
                                      ? Colors.green
                                      : Colors.red,
                                ),
                                textDirection: TextDirection.rtl,
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          )),
        ));
  }
}
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter