Flutter 块值问题

问题描述 投票:0回答:1

我对sign_in_controller内的值有问题,尽管由于sign_in_bloc正确打印了电子邮件和密码,但当我单击按钮时,sign_in_controller内的值始终为空。

我/扑 (31187): 电子邮件 ---> I/flutter (31187): 密码 ---> I/flutter (31187):电子邮件为空 我/flutter(31187):密码为空

import 'package:equatable/equatable.dart';

class SignInState extends Equatable {
  const SignInState({this.email = '', this.password = ''});

  final String email;
  final String password;

  SignInState copyWith({String? email, String? password}) {
    return SignInState(
      email: email ?? this.email,
      password: password ?? this.password,
    );
  }

  @override
  // TODO: implement props
  List<Object?> get props => throw UnimplementedError();
}


import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:login_firebase/screens/loginpage/bloc/sign_in_event.dart';
import 'package:login_firebase/screens/loginpage/bloc/sign_in_state.dart';

class SignInBloc extends Bloc<SignInEvent, SignInState> {
  SignInBloc() : super(const SignInState()) {
    //on<EmailEvent>((event, emit) {
    //  emit(state.copyWith(email: event.email));
    //});
    on<EmailEvent>(_emailEvent);
    on<PasswordEvent>(_passwordEvent);
  }

  void _emailEvent(EmailEvent event, Emitter<SignInState> emit) {
    print('My email is ${event.email}');
    emit(state.copyWith(email: event.email));
  }

  void _passwordEvent(PasswordEvent event, Emitter<SignInState> emit) {
    print('My password is ${event.password}');
    emit(state.copyWith(password: event.password));
  }
}

abstract class SignInEvent {
  const SignInEvent();
}

class EmailEvent extends SignInEvent {
  final String email;
  EmailEvent(this.email);
}

class PasswordEvent extends SignInEvent {
  final String password;
  PasswordEvent(this.password);
}

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:login_firebase/screens/loginpage/bloc/sign_in_bloc.dart';

class SignInController {
  final BuildContext context;
  const SignInController({required this.context});

  Future<void> handleSignIn(String type) async {
    try {
      if (type == 'email') {
        final String emailAddress =
            BlocProvider.of<SignInBloc>(context).state.email;
        final String password =
            BlocProvider.of<SignInBloc>(context).state.password;
        print('EMAIL ---> $emailAddress');
        print('PASSWORD ---> $password');
        if (emailAddress.isEmpty) {
          print('email is empty');
        } else {
          print('email is $emailAddress');
        }

        if (password.isEmpty) {
          print('password is empty');
        } else {
          print('password is $password');
        }
        try {
          final credential =
              await FirebaseAuth.instance.signInWithEmailAndPassword(
            email: emailAddress,
            password: password,
          );
          if (credential.user == null) {
            print('user does not exits');
          }
          if (!credential.user!.emailVerified) {}

          var user = credential.user;
          if (user != null) {
            print('user exist');
            // we got verificated user from firebase!
          } else {
            // error while getting user from firebase!
            print('no user');
          }
        } on FirebaseAuthException catch (e) {
          if (e.code == 'user-not-found') {
            print('no user found for that email');
          } else if (e.code == 'wrong password') {
            print('wrong password');
          } else if (e.code == 'invalid-email') {
            print('your email format is wrong');
          }
        }
      }
    } catch (e) {
      print(e.toString());
    }
  }
}

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:login_firebase/screens/loginpage/bloc/sign_in_bloc.dart';
import 'package:login_firebase/screens/loginpage/bloc/sign_in_event.dart';
import 'package:login_firebase/screens/loginpage/bloc/sign_in_state.dart';
import 'package:login_firebase/screens/loginpage/sign_in_controller.dart';

class LoginPage extends StatelessWidget {
  const LoginPage({super.key});

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<SignInBloc, SignInState>(
      bloc: SignInBloc(),
      builder: (context, state) {
        return Scaffold(
          backgroundColor: Colors.white,
          appBar: AppBar(),
          body: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 30),
            child: SingleChildScrollView(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const SizedBox(height: 40),
                  Text(
                    "Let's Sign you in.",
                    style: GoogleFonts.poppins(
                        fontSize: 30, fontWeight: FontWeight.w600),
                  ),
                  const SizedBox(height: 5),
                  Text(
                    "Welcome back",
                    style: GoogleFonts.poppins(
                        fontSize: 18, fontWeight: FontWeight.w400),
                  ),
                  Text(
                    "you've been missed!",
                    style: GoogleFonts.poppins(
                        fontSize: 18, fontWeight: FontWeight.w400),
                  ),
                  const SizedBox(height: 50),
                  customTextField(
                      context, const Icon(Icons.person), 'Enter your email',
                      (value) {
                    context.read<SignInBloc>().add(EmailEvent(value));
                  }),
                  const SizedBox(height: 20),
                  customTextField(
                      context, const Icon(Icons.lock), 'Enter your password',
                      (value) {
                    context.read<SignInBloc>().add(PasswordEvent(value));
                  }),
                  const SizedBox(height: 320),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(
                        "Don't have account?",
                        style: GoogleFonts.poppins(
                            fontSize: 14,
                            fontWeight: FontWeight.w400,
                            color: Colors.black.withOpacity(0.5)),
                      ),
                      Text(
                        " Register",
                        style: GoogleFonts.poppins(
                            fontSize: 14,
                            fontWeight: FontWeight.w600,
                            color: Colors.black.withOpacity(0.7)),
                      ),
                    ],
                  ),
                  const SizedBox(height: 10),
                  customLoginButton(
                    context,
                    'Login',
                    () {
                      SignInController(context: context).handleSignIn('email');
                    },
                  )
                ],
              ),
            ),
          ),
        );
      },
    );
  }
}

Widget customTextField(BuildContext context, Icon icon, String hintText,
    void Function(String value)? func) {
  return Container(
    padding: const EdgeInsets.symmetric(horizontal: 10),
    width: MediaQuery.of(context).size.width,
    height: 60,
    decoration: BoxDecoration(
      borderRadius: BorderRadius.circular(16),
      border: Border.all(color: Colors.black.withOpacity(0.4)),
    ),
    child: Center(
      child: TextField(
        onChanged: (value) => func!(value),
        style: GoogleFonts.poppins(fontSize: 16, fontWeight: FontWeight.w400),
        decoration: InputDecoration(
          prefixIcon: icon,
          border: InputBorder.none,
          enabledBorder: InputBorder.none,
          focusedBorder: InputBorder.none,
          hintText: hintText,
          prefixIconColor: MaterialStateColor.resolveWith((states) =>
              states.contains(MaterialState.focused)
                  ? Colors.grey
                  : Colors.grey),
          hintStyle:
              GoogleFonts.poppins(fontSize: 16, fontWeight: FontWeight.w400),
        ),
      ),
    ),
  );
}

Widget customLoginButton(
    BuildContext context, String text, void Function()? ontap) {
  return GestureDetector(
    onTap: ontap,
    child: Container(
      height: 60,
      width: MediaQuery.of(context).size.width,
      decoration: BoxDecoration(
        color: Colors.black,
        borderRadius: BorderRadius.circular(18),
      ),
      child: Center(
        child: Text(
          text,
          style: GoogleFonts.poppins(
              fontSize: 18, fontWeight: FontWeight.w500, color: Colors.white),
        ),
      ),
    ),
  );
}

我试图使用 bloc 文档修复它,但没有发现任何有用的东西

flutter dart firebase-authentication bloc
1个回答
0
投票

解决了道具错误

  @override
  // TODO: implement props
  List<Object?> get props => [email, password];
© www.soinside.com 2019 - 2024. All rights reserved.