Uncategorized

How To Get User ID on Checkout Form Field

Following was our previous code of the checkout screen



import 'package:ecommerce_app/MyAccount/thankyou.dart';
import 'package:ecommerce_app/cart/Cart.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:ecommerce_app/Home/Home.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../MyAccount/login.dart';

class CheckoutScreen extends StatefulWidget {
  const CheckoutScreen({super.key});

  @override
  State<CheckoutScreen> createState() => _CheckoutScreenState();
}

class _CheckoutScreenState extends State<CheckoutScreen> {
  //define all the variables

  final _formKey = GlobalKey<FormState>();
  String selectedState = 'Select State';
  String userMobile = '';




  List<String> indianStates = [
    'Select State',
    'Andhra Pradesh',
    'Arunachal Pradesh',
    'Assam',
    'Bihar',
    'Chhattisgarh',
    'Goa',
    'Gujarat',
    'Haryana',
    'Himachal Pradesh',
    'Jharkhand',
    'Karnataka',
    'Kerala',
    'Madhya Pradesh',
    'Maharashtra',
    'Manipur',
    'Meghalaya',
    'Mizoram',
    'Nagaland',
    'Odisha',
    'Punjab',
    'Rajasthan',
    'Sikkim',
    'Tamil Nadu',
    'Telangana',
    'Tripura',
    'Uttar Pradesh',
    'Uttarakhand',
    'West Bengal',
    // Rest of the states
  ];



  Widget _buildStateDropdown() {

    return DropdownButtonFormField<String>(
      decoration: InputDecoration(
        labelText: 'Your State',
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(50),
          borderSide: BorderSide(color: Colors.pink),
        ),
      ),
      value: selectedState,
      items: indianStates.map((state) {
        return DropdownMenuItem<String>(
          value: state,
          child: Text(state),
        );
      }).toList(),
      onChanged: (value) {
        setState(() {
          selectedState = value!;
        });
      },
    );
  }

  @override
  void initState() {
    super.initState();

    _getUserInfo();
  }
  Future<void> _getUserInfo() async {
    try {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      String usermobile = prefs.getString('userMobile') ?? ''; // Get user email

      if (usermobile.isEmpty) {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => LoginScreen(),
          ),
        );
      } else {
        setState(() {
          userMobile = usermobile;
        });
      }
      ;
    } catch (error) {
      print('Error retrieving user info: $error');
    }
  }


  //Define Controllers Here

  TextEditingController yourName = TextEditingController();
  TextEditingController yourMobile = TextEditingController();
  TextEditingController yourAddress = TextEditingController();


  @override
  void dispose(){
    yourName.dispose();
    yourMobile.dispose();
    yourAddress.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Checkout Now'),
        backgroundColor: Colors.pink,
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            Container(
              margin: EdgeInsets.all(30),
              child: Image.network('https://aboutassam.in/flutter_app/assets/img/cart.png'),
            ),
            Container(
              child: Text('Checkout Screen', style: TextStyle(fontSize: 30),),
            ),

            Form(

              key: _formKey,
              child: Column(
                children: <Widget>[

                  _buildTextInputField('Your Name', yourName),
                  SizedBox(height: 10,),
                  _buildTextInputField('Your Mobile', yourMobile, userMobile : userMobile, readOnly: true),
                  SizedBox(height: 10,),
                  _buildStateDropdown(),
                  SizedBox(height: 10,),
                  _buildTextInputField('Your Address', yourAddress),
                  SizedBox(height: 10,),
                  ElevatedButton(
                      onPressed: (){
                        if(_formKey.currentState!.validate()){
                          sendDataToServer();
                        }

                      },
                      child: Text('Submit')
                  )

                ],
              )
              ,
            )
          ],
        ),
      ),
    );
  }

  void sendDataToServer () async {
    // Create a map of the form data.
    Map<String, String> formData = {
      'name': yourName.text,
      'mobile': yourMobile.text,
      'state': selectedState,
      'address': yourAddress.text,
    };

    // Make an HTTP POST request to send the form data.
    final response = await http.post(
      Uri.parse('https://aboutassam.in/flutter_app/api/checkout.php'),
      body: formData,
    );


    if (response.statusCode == 200) {
      print('Response===== ${response.body}');
      Navigator.push(context,
      MaterialPageRoute(
          builder: (context) => ThankYouScreen())
      );
    } else {
      print('Response===== ${response.body}');
    }
  }
}



Widget _buildTextInputField(




String labelText, TextEditingController controller, {
      TextInputType inputType = TextInputType.text,
      String? Function(String?)? validator,
      String userMobile = '',
      bool readOnly = false,

    }) {



  if(labelText == 'Your Mobile'){

    controller.text = userMobile;
  }


  return TextFormField(
    controller: controller,
    enabled: !readOnly,
    decoration: InputDecoration(
      labelText: labelText,
      border: OutlineInputBorder(
        borderRadius: BorderRadius.circular(50),
        borderSide: BorderSide(color: Colors.pink),
      ),
    ),
    keyboardType: inputType,
    validator: validator,
  );
}


Modified Checkout screen



import 'package:ecommerce_app/MyAccount/thankyou.dart';
import 'package:ecommerce_app/cart/Cart.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:ecommerce_app/Home/Home.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../MyAccount/login.dart';

class CheckoutScreen extends StatefulWidget {
  const CheckoutScreen({super.key});

  @override
  State<CheckoutScreen> createState() => _CheckoutScreenState();
}

class _CheckoutScreenState extends State<CheckoutScreen> {
  //define all the variables

  final _formKey = GlobalKey<FormState>();
  String selectedState = 'Select State';
  String userMobile = '';
  String userId = '';




  List<String> indianStates = [
    'Select State',
    'Andhra Pradesh',
    'Arunachal Pradesh',
    'Assam',
    'Bihar',
    'Chhattisgarh',
    'Goa',
    'Gujarat',
    'Haryana',
    'Himachal Pradesh',
    'Jharkhand',
    'Karnataka',
    'Kerala',
    'Madhya Pradesh',
    'Maharashtra',
    'Manipur',
    'Meghalaya',
    'Mizoram',
    'Nagaland',
    'Odisha',
    'Punjab',
    'Rajasthan',
    'Sikkim',
    'Tamil Nadu',
    'Telangana',
    'Tripura',
    'Uttar Pradesh',
    'Uttarakhand',
    'West Bengal',
    // Rest of the states
  ];



  Widget _buildStateDropdown() {

    return DropdownButtonFormField<String>(
      decoration: InputDecoration(
        labelText: 'Your State',
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(50),
          borderSide: BorderSide(color: Colors.pink),
        ),
      ),
      value: selectedState,
      items: indianStates.map((state) {
        return DropdownMenuItem<String>(
          value: state,
          child: Text(state),
        );
      }).toList(),
      onChanged: (value) {
        setState(() {
          selectedState = value!;
        });
      },
    );
  }

  @override
  void initState() {
    super.initState();

    _getUserInfo();
  }
  Future<void> _getUserInfo() async {
    try {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      String usermobile = prefs.getString('userMobile') ?? ''; // Get user email
      int userId = prefs.getInt('userId') ?? 0; // Get user email

      print('-------User id is $userId');

      if (usermobile.isEmpty) {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => LoginScreen(),
          ),
        );
      } else {
        setState(() {
          userMobile = usermobile;
          this.userId = userId.toString();
          yourId.text = this.userId;
        });
      }
      ;
    } catch (error) {
      print('Error retrieving user info: $error');
    }
  }


  //Define Controllers Here

  TextEditingController yourName = TextEditingController();
  TextEditingController yourMobile = TextEditingController();
  TextEditingController yourAddress = TextEditingController();
  TextEditingController yourId = TextEditingController();


  @override
  void dispose(){
    yourName.dispose();
    yourMobile.dispose();
    yourAddress.dispose();
    yourId.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Checkout Now'),
        backgroundColor: Colors.pink,
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            Container(
              margin: EdgeInsets.all(30),
              child: Image.network('https://aboutassam.in/flutter_app/assets/img/cart.png'),
            ),
            Container(
              child: Text('Checkout Screen', style: TextStyle(fontSize: 30),),
            ),

            Form(

              key: _formKey,
              child: Column(
                children: <Widget>[

                  _buildTextInputField('Your Name', yourName),
                  SizedBox(height: 10,),
                  _buildTextInputField('Your Mobile', yourMobile, userMobile : userMobile, readOnly: true),
                  SizedBox(height: 10,),

                  _buildTextInputField('Your ID', yourId, userId : userId, readOnly: true),
                  SizedBox(height: 10,),
                  _buildStateDropdown(),
                  SizedBox(height: 10,),
                  _buildTextInputField('Your Address', yourAddress),
                  SizedBox(height: 10,),
                  ElevatedButton(
                      onPressed: (){
                        if(_formKey.currentState!.validate()){
                          sendDataToServer();
                        }

                      },
                      child: Text('Submit')
                  )

                ],
              )
              ,
            )
          ],
        ),
      ),
    );
  }

  void sendDataToServer () async {
    // Create a map of the form data.
    Map<String, String> formData = {
      'name': yourName.text,
      'mobile': yourMobile.text,
      'state': selectedState,
      'address': yourAddress.text,
      'user_id' : yourId.text
    };

    // Make an HTTP POST request to send the form data.
    final response = await http.post(
      Uri.parse('https://aboutassam.in/flutter_app/api/checkout.php'),
      body: formData,
    );


    if (response.statusCode == 200) {
      print('Response===== ${response.body}');
      Navigator.push(context,
      MaterialPageRoute(
          builder: (context) => ThankYouScreen())
      );
    } else {
      print('Response===== ${response.body}');
    }
  }
}



Widget _buildTextInputField(




String labelText, TextEditingController controller, {
      TextInputType inputType = TextInputType.text,
      String? Function(String?)? validator,
      String userMobile = '',
      String userId = '',
      bool readOnly = false,

    }) {



  if(labelText == 'Your Mobile'){

    controller.text = userMobile;
  }

  if(labelText == 'Your ID'){

    controller.text = userId;
  }


  return TextFormField(
    controller: controller,
    enabled: !readOnly,
    decoration: InputDecoration(
      labelText: labelText,
      border: OutlineInputBorder(
        borderRadius: BorderRadius.circular(50),
        borderSide: BorderSide(color: Colors.pink),
      ),
    ),
    keyboardType: inputType,
    validator: validator,
  );
}


Leave a Reply

Your email address will not be published. Required fields are marked *