从BehaviorSubject获取价值时遇到问题。我创建了一个 屏幕上有两个TextField和一个Button的颤动,我收到了 他们的数据具有集团模式。
但是当我更改TextFields的值时,BehaviorSubject的值 连接到TextFiled会得到null,当我更改TextField值时, 连接到TextFields的两个TextFiled的值将为空。
使用颤抖和飞镖:
import 'dart:async';
import 'package:bloc_provider/bloc_provider.dart';
import 'package:rxdart/rxdart.dart';
import 'package:sense_app_flutter/models/user.dart';
import 'package:sense_app_flutter/resources/user/provider.dart';
enum LoginStatus { SUCCESS, LOADING, ERROR }
class LoginState {
final LoginStatus status;
final String message;
LoginState({this.status, this.message});
}
class LoginBloc implements Bloc {
final UserRepository _userRepository = UserRepository();
final PublishSubject<LoginState> _loginStateSubject = new PublishSubject();
final _user = PublishSubject<User>();
final _usernameController = BehaviorSubject<String>();
final _passwordController = BehaviorSubject<String>();
Observable<LoginState> get loginStateStream => _loginStateSubject.stream;
Function(String) get usernameChange => _usernameController.sink.add;
Function(String) get passwordChange => _passwordController.sink.add;
void changeLoginStatus({LoginState state}) =>
_loginStateSubject.sink.add(state);
Stream<String> get username =>
_usernameController.stream.transform(_updateEmail);
Stream<String> get password =>
_passwordController.stream.transform(_updatePassword);
Stream<bool> get submitCheck =>
Observable.combineLatest2(username, password, (e, p) => true);
void loginSubmit() async {
String valUsername = _usernameController.value;
print(valUsername);
changeLoginStatus(
state: LoginState(status: LoginStatus.LOADING, message: "loading"));
// print("asdas ${username.last.toString()}");
try {
User user = await _userRepository.login("stevanus1997", "asdasd123");
print(user);
_user.sink.add(user);
changeLoginStatus(
state: LoginState(status: LoginStatus.SUCCESS, message: "success"));
} catch (err) {
print(err);
changeLoginStatus(
state:
LoginState(status: LoginStatus.ERROR, message: err.toString()));
}
}
@override
void dispose() {
_usernameController.close();
_passwordController.close();
_loginStateSubject.close();
_user.close();
}
var _updateEmail =
StreamTransformer<String, String>.fromHandlers(handleData: (email, sink) {
if (email == "" || email.trim() == "") {
sink.addError("Email can not be empty");
} else {
sink.add(email);
}
});
var _updatePassword = StreamTransformer<String, String>.fromHandlers(
handleData: (password, sink) {
if (password == "" || password.trim() == "") {
sink.addError("Password can not be empty");
} else {
sink.add(password);
}
});
}
我希望输入不出来,但总是返回null。
答案 0 :(得分:0)
尝试这样的事情
final _usernameController = BehaviorSubject<String>.seeded("");
代替
final _usernameController = BehaviorSubject<String>();
您可以在种子函数中提供默认值