Skip to main content
2 de 3
Correcciones en redacción y formato, ruido removido
padaleiana
  • 3.3k
  • 13
  • 19
  • 27

Capturar el valor de DropdownButtonFormField en Flutter

Necesito capturar el valor seleccionado para poder enviarlo como parámetro. Estoy trabajando con Flutter (Dart) y Supabase como base de datos.

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:worker_attendance/constants/constants.dart';
import 'package:worker_attendance/models/area_model.dart';
import 'package:worker_attendance/models/cargo_model.dart';
import 'package:worker_attendance/models/cce_model.dart';
import 'package:worker_attendance/models/boss_model.dart';
import 'package:worker_attendance/models/modality_model.dart';
import 'package:worker_attendance/services/auth_service.dart';
import 'package:worker_attendance/services/db_service.dart';

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

  @override
  State<RegisterScreen> createState() => _RegisterScreenState();
}


class _RegisterScreenState extends State<RegisterScreen> {
  final TextEditingController _emailController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _bussines_nameController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    double screenWidth = MediaQuery.of(context).size.width;
    double screenHeight = MediaQuery.of(context).size.height;

    final dbService = Provider.of<DbService>(context);
    // Using below conditions because build can be called multiple times
    dbService.allCce.isEmpty ? dbService.getAllCce() : null;
    dbService.allArea.isEmpty ? dbService.getAllArea() : null;
    dbService.allCargo.isEmpty ? dbService.getAllCargo() : null;
    dbService.allBoss.isEmpty ? dbService.getAllBoss() : null;
    dbService.allModality.isEmpty ? dbService.getAllModality() : null;

  return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.blueAccent,
        elevation: 0,
      ),
      body: Center(
          child: SingleChildScrollView(
              padding: const EdgeInsets.all(10),
              child: Form(
                //key: _formKey,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [

                    Padding(
                      padding: const EdgeInsets.all(10),
                      child: Column(
                        children: [
                          TextField(
                            decoration: const InputDecoration(
                              label: Text("Employee Email ID"),
                              prefixIcon: Icon(Icons.person),
                              border: OutlineInputBorder(),
                            ),
                            controller: _emailController,
                          ),
                          const SizedBox(
                            height: 20,
                          ),
                          TextField(
                            decoration: const InputDecoration(
                              label: Text("Password"),
                              prefixIcon: Icon(Icons.lock),
                              border: OutlineInputBorder(),
                            ),
                            controller: _passwordController,
                            obscureText: true,
                          ),
                          const SizedBox(
                            height: 20,
                          ),
                          TextField(
                            decoration: const InputDecoration(
                              label: Text("name"),
                              prefixIcon: Icon(Icons.person),
                              border: OutlineInputBorder(),
                            ),
                            controller: _nameController,
                          ),
                          const SizedBox(
                            height: 20,
                          ),
                          TextField(
                            decoration: const InputDecoration(
                              label: Text("Razón social"),
                              prefixIcon: Icon(Icons.person),
                              border: OutlineInputBorder(),
                            ),
                            controller: _bussines_nameController,
                          ),
                          const SizedBox(
                            height: 20,
                          ),

//Aquí muestro la información en una lista directamente desde supabase:

 dbService.allCce.isEmpty
      ? const LinearProgressIndicator()
      : SizedBox(
          width: double.infinity,
          child: DropdownButtonFormField(
            hint: Text('Select CCE'),
            decoration: const InputDecoration(
                border: OutlineInputBorder()),
            // value: dbService.userCce ?? dbService.allCce.first.id,
            items:
                dbService.allCce.map((CceModel item) {
              return DropdownMenuItem(
                  value: item.id,
                  child: Text(
                    item.ccostos,
                    style:
                        const TextStyle(fontSize: 20),
                  ));
            }).toList(),
            onChanged: (_selectedval) {
              dbService.userCce = _selectedval;
              print(_selectedval);
            },
          ),
        ),

//Aquí nos dirige a otra clase llamada registerWorker enviándole los siguientes parámetros: _emailController.text.trim(),_passwordController.text.trim(), _nameController.text.trim()

//Aquí necesitaría enviar el parámetro de DropdownButtonFormField

   Consumer<AuthService>(
    builder: (context, authServiceProvider, child) {
      return SizedBox(
        height: 60,
        width: double.infinity,
        child: authServiceProvider.isLoading
            ? const Center(
                child: CircularProgressIndicator(),
              )
            : ElevatedButton(
                onPressed: () {
                  authServiceProvider.registerWorker(
                      _emailController.text.trim(),
                      _passwordController.text.trim(),
                      _nombreController.text.trim(),
                      _razonController.text.trim(),
                      //_selectedCCE.toInt(),

                      context);
                },
                style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.blueAccent,
                    shape: RoundedRectangleBorder(
                        borderRadius:
                            BorderRadius.circular(30))),
                child: const Text(
                  "REGISTER",
                  style: TextStyle(fontSize: 20),
                ),
              ),
      );
    },
  ),

//clase auth_service - registerWorker

    Future registerWorker(
      String email, String password, String name, String business_name ,BuildContext context) async {
    try {
      setIsLoading = true;
      if (email == "" || password == "") {
        throw ("All Fields are required");
      }
      final AuthResponse response =
      await _supabase.auth.signUp(email: email, password: password);
      if (response != null) {
        await _dbService.insertNewUser(email, response.user!.id, name
            );

        Utils.showSnackBar("Successfully registered !", context,
            color: Colors.green);
        await loginWorker(email, password, context);
        Navigator.pop(context);
      }
    } catch (e) {
      setIsLoading = false;
      Utils.showSnackBar(e.toString(), context, color: Colors.blueAccent);
    }
  }

//clase db_service - insertNewUser

 class DbService extends ChangeNotifier {
      final SupabaseClient _supabase = Supabase.instance.client;
    
        List<CceModel> allCce = [];
        int? userCce;
    
      String generateRandomUserId() {
        final random = Random();
        const allChars = "faangFAANG0123456789";
        final randomString =
        List.generate(8, (index) => allChars[random.nextInt(allChars.length)])
            .join();
        return randomString;
      }
    
    
  Future<void> getAllCce() async {
    final List result =
    await _supabase.from(Constants.cceTable).select();
    allCce = result
        .map((cce) => CceModel.fromJson(cce))
        .toList();
    notifyListeners();
  }
    
    
    Future insertNewUser(String email,var id,String name, String business_name ) async {
        await _supabase.from(Constants.userTable).insert({
          'id': id,
          'name': name,
          'email': email,
          'user_id': generateRandomUserId(),
    
        });
      }