【发布时间】:2019-12-15 19:40:31
【问题描述】:
我第一次尝试使用流将我的视图模型连接到我的屏幕,但我很难完全掌握这个概念。
我的屏幕:
class LoginAndSignupScreen extends StatefulWidget {
LoginAndSignupScreen({@required this.viewModel});
final LoginAndSignupScreenViewModelType viewModel;
@override
State<StatefulWidget> createState() => new _LoginAndSignupScreenState();
}
class _LoginAndSignupScreenState extends State<LoginAndSignupScreen> {
Widget showErrorMessage() {
return StreamBuilder<String>(
initialData: "",
stream: widget.viewModel.errorText,
builder: (context, snapshot) {
return new Text(
snapshot.data,
style: TextStyle(
fontSize: 13.0,
color: Colors.red,
height: 1.0,
fontWeight: FontWeight.w300
),
);
}
);
}
我的视图模型:
abstract class LoginAndSignupScreenViewModelType {
Stream<String> get errorText;
void signIn(String email, String password);
void signUp(String email, String password, String firstName, String lastName);
}
class LoginAndSignupScreenViewModel implements LoginAndSignupScreenViewModelType {
LoginAndSignupScreenViewModel({@required this.authenticationService,
@required this.cloudStoreService});
final AuthenticationServiceType authenticationService;
final CloudStoreServiceType cloudStoreService;
final errorController = StreamController<String>.broadcast();
@override
Stream<String> get errorText => errorController.stream;
@override
void signIn(String email, String password) async {
try {
String userId = await authenticationService.signIn(email, password);
User user = await cloudStoreService.fetchUserWithId(userId)
.whenComplete(loginCallback);
print('Signed in: ${user.firstName} ${user.lastName}');
} catch (error) {
errorController.add(error);
}
}
@override
void signUp(String email, String password, String firstName, String lastName) async {
try {
String userId = await authenticationService.signUp(email, password);
User user = new User(userId, firstName, lastName);
await cloudStoreService.createUser(user)
.then(showHomeScreenIfValidUser);
print('Signed up user: ${user.id}');
} catch (error) {
errorController.add(error);
}
}
}
当我这样做并运行时,我收到一条错误消息,指出 snapshot.data = null 我理解。我的问题是,如果没有错误字符串,我希望没有小部件。
谁能帮忙?
【问题讨论】:
-
我看不到你在哪里使用
snapshot.data... -
@Benjamin 抱歉,已更新
_LoginAndSignupScreenState -
如果您不希望小部件出现,请使用
Visibility小部件,您可以将其设置为根据条件不显示小部件。在您的情况下,我假设数据是否为空。 -
实际上 @Benjamin Visibity 对我不起作用,如果 snapshot.data 为 null 它仍然失败