Flutter StreamBuilder not working after Page Reload - flutter
I have a Registration page with TextField Form Validators in my App with a button. The text field will display form validation error messages if business rules haven't been met and the "next" button will be tap-able once all criteria has been met. This is currently all working well in my app but I find that once I leave the page and return to it, the validation error messages stops displaying and the button stops working as well. Looking at the console logs in my IDE (android studio) the only relevant error message I am getting is
[VERBOSE-2:ui_dart_state.cc(148)] Unhandled Exception: Bad state:
Stream is already closed
#0 _SinkTransformerStreamSubscription._add
(dart:async/stream_transformers.dart:66:7)
#1 _EventSinkWrapper.add
(dart:async/stream_transformers.dart:15:11)
I'm not exactly sure what this means, does the stream close and not reopen once the page has been reloaded? If not, is there a way i could fix this or is there something i'm missing? This is what i'm experiencing
Stream Builder Code:
Widget emailField(authBloc) {
return StreamBuilder(
stream: authBloc.emailStream,
builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
return TextField(
onChanged: authBloc.updateEmail,
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(
border: UnderlineInputBorder(
borderSide: BorderSide(
color: Colors.deepOrange
)
),
hintText: 'Enter Email',
labelText: 'Email Address',
errorText: snapshot.error
),
);
},
);
}
Widget passwordField( authBloc) {
return StreamBuilder(
stream: authBloc.passwordStream,
builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
return TextField(
onChanged: authBloc.updatePassword,
obscureText: true,
decoration: InputDecoration(
hintText: 'Enter password',
labelText: 'Password',
errorText: snapshot.error,
),
);
},
);
}
Widget checkPasswordField( authBloc) {
return StreamBuilder(
stream: authBloc.validatePasswordStream,
builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
return TextField(
onChanged: authBloc.updateValidatePassword,
obscureText: true,
decoration: InputDecoration(
hintText: 'Re-enter password',
labelText: 'Confirm Password',
errorText: snapshot.error,
),
);
},
);
}
Widget nextBtn(authBloc) {
return StreamBuilder(
stream: authBloc.submitValid,
builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
return RaisedButton(
child: Text('Next'),
color: Colors.deepOrange,
shape: BeveledRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(7.0))
),
onPressed: snapshot.hasData
? () => Navigator.pushNamed(context, '/register')
: null,
);
}
);
}
Streams:
/// REGISTER VARIABLES
static final _emailController = BehaviorSubject<
String>(); //RxDart's implementation of StreamController. Broadcast stream by default
static final _passwordController = BehaviorSubject<String>();
static final _validatePasswordController = BehaviorSubject<
String>(); // Will check that the password entered the 2nd time is correct
/// REGISTER STREAM & METHODS
//Retrieve data from the stream
Stream<String> get emailStream => _emailController.stream
.transform(performEmailValidation); //Return the transformed stream
Stream<String> get passwordStream =>
_passwordController.stream.transform(performPasswordValidation);
Stream<String> get validatePasswordStream =>
_validatePasswordController.stream.transform(performIsPasswordSame);
//Merging email, password and validate password
Stream<bool> get submitValid => Observable.combineLatest3(
emailStream, passwordStream, validatePasswordStream, (e, p1, p2) => true);
//Add data to the stream
Function(String) get updateEmail => _emailController.sink.add;
Function(String) get updatePassword => _passwordController.sink.add;
Function(String) get updateValidatePassword =>
_validatePasswordController.sink.add;
// performing user input validations
final performEmailValidation = StreamTransformer<String, String>.fromHandlers(
handleData: (email, sink) async {
String emailValidationRule =
r'^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$';
RegExp regExp = new RegExp(emailValidationRule);
if (await doesNameAlreadyExist("email", _emailController.value) == true)
sink.addError("That email already exists");
else if (regExp.hasMatch(email)) {
sink.add(email);
} else {
sink.addError(StringConstant.emailErrorMessage);
}
});
final performPasswordValidation =
StreamTransformer<String, String>.fromHandlers(
handleData: (_passwordController, sink) {
if (_passwordController.length >= 6) {
sink.add(_passwordController);
} else {
sink.addError(StringConstant.passwordErrorMessage);
}
});
final performIsPasswordSame = StreamTransformer<String, String>.fromHandlers(
handleData: (password, sink) {
if (password != _passwordController.value)
sink.addError(StringConstant.invalidPasswordMessage);
else
sink.add(password);
});
Entire Screen Code:
class SignUp extends StatefulWidget {
#override
_SignUpState createState() => _SignUpState();
}
class _SignUpState extends State<SignUp> {
AuthBloc _authBloc;
#override
void didChangeDependencies() {
super.didChangeDependencies();
_authBloc = AuthBlocProvider.of(context);
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
alignment: Alignment.center,
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: <Widget>[
SizedBox(height: 80,),
Text("Register", style: Style.appTextStyle),
SizedBox(height: 100,),
emailField(_authBloc),
SizedBox(height: 30),
passwordField(_authBloc),
SizedBox(height: 30),
checkPasswordField(_authBloc),
SizedBox(height: 30),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
cancelBtn(),
nextBtn(_authBloc),
],
)
// checkPasswordField(authBloc),
],
),
)
),
);
}
Widget emailField(authBloc) {
return StreamBuilder(
stream: authBloc.emailStream,
builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
return TextField(
onChanged: authBloc.updateEmail,
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(
border: UnderlineInputBorder(
borderSide: BorderSide(
color: Colors.deepOrange
)
),
hintText: 'Enter Email',
labelText: 'Email Address',
errorText: snapshot.error
),
);
},
);
}
Widget passwordField( authBloc) {
return StreamBuilder(
stream: authBloc.passwordStream,
builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
return TextField(
onChanged: authBloc.updatePassword,
obscureText: true,
decoration: InputDecoration(
hintText: 'Enter password',
labelText: 'Password',
errorText: snapshot.error,
),
);
},
);
}
Widget checkPasswordField( authBloc) {
return StreamBuilder(
stream: authBloc.validatePasswordStream,
builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
return TextField(
onChanged: authBloc.updateValidatePassword,
obscureText: true,
decoration: InputDecoration(
hintText: 'Re-enter password',
labelText: 'Confirm Password',
errorText: snapshot.error,
),
);
},
);
}
Widget nextBtn(authBloc) {
return StreamBuilder(
stream: authBloc.submitValid,
builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
return RaisedButton(
child: Text('Next'),
color: Colors.deepOrange,
shape: BeveledRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(7.0))
),
onPressed: snapshot.hasData
? () => Navigator.pushNamed(context, '/register')
: null,
);
}
);
}
Widget cancelBtn(){
return RaisedButton(
child: Text('Cancel'),
color: Colors.white30,
shape: BeveledRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(7.0))
),
onPressed: () => Navigator.pop(context),
);
}
#override
void dispose() {
super.dispose();
_authBloc.dispose();
}
Bloc Code:
/// REGISTER VARIABLES
static final _emailController = BehaviorSubject<
String>(); //RxDart's implementation of StreamController. Broadcast stream by default
static final _passwordController = BehaviorSubject<String>();
static final _validatePasswordController = BehaviorSubject<
String>(); // Will check that the password entered the 2nd time is correct
/// REGISTER STREAM & METHODS
//Retrieve data from the stream
Stream<String> get emailStream => _emailController.stream
.transform(performEmailValidation); //Return the transformed stream
Stream<String> get passwordStream =>
_passwordController.stream.transform(performPasswordValidation);
Stream<String> get validatePasswordStream =>
_validatePasswordController.stream.transform(performIsPasswordSame);
//Merging email, password and validate password
Stream<bool> get submitValid => Observable.combineLatest3(
emailStream, passwordStream, validatePasswordStream, (e, p1, p2) => true);
//Add data to the stream
Function(String) get updateEmail => _emailController.sink.add;
Function(String) get updatePassword => _passwordController.sink.add;
Function(String) get updateValidatePassword =>
_validatePasswordController.sink.add;
// performing user input validations
final performEmailValidation = StreamTransformer<String, String>.fromHandlers(
handleData: (email, sink) async {
String emailValidationRule =
r'^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$';
RegExp regExp = new RegExp(emailValidationRule);
if (await doesNameAlreadyExist("email", _emailController.value) == true)
sink.addError("That email already exists");
else if (regExp.hasMatch(email)) {
sink.add(email);
} else {
sink.addError(StringConstant.emailErrorMessage);
}
});
final performPasswordValidation =
StreamTransformer<String, String>.fromHandlers(
handleData: (_passwordController, sink) {
if (_passwordController.length >= 6) {
sink.add(_passwordController);
} else {
sink.addError(StringConstant.passwordErrorMessage);
}
});
final performIsPasswordSame = StreamTransformer<String, String>.fromHandlers(
handleData: (password, sink) {
if (password != _passwordController.value)
sink.addError(StringConstant.invalidPasswordMessage);
else
sink.add(password);
});
dispose() {
_emailController.close();
_passwordController.close();
_validatePasswordController.close();
}
Well, looking to full source and the GIF that you show I can see what is causing this problem.
Your mistake is call dispose() BLoC instance method in dispose() SingUp widget class method.
Why is a mistake?
In your specific case when you're in SingUp screen and go to a next route/screen dispose method from SingUp is called and in this moment the streams of your BLoC instance is going to be closed. But the next allows the user go back to SingUp screen and when this happen SingUp instance gets the same BLoC instance that was used before but this BLoC instance has the streams already closed.
How can I solve this in a simple way?
In SingUp class :
#override
void dispose() {
super.dispose();
/// DON'T CALL BLoC dispose here
/// _authBloc.dispose();
}
Don't dispose you BloC here because the user can back to this screen any moment. Since you're using InheritedWidget to get BLoC instance and this gives you access the same BLoC instance in different places I advise you call yourBloc.dispose() in the moment where the user is ending all the sing up process.
Related
How to pass data with StreamProvider correctly?
Screenshot I'm trying to send the data 'area name' from textfield at the side of map to google map, and here's my code // sideBar.dart class StreamTitle { StreamTitle({required this.getTitle}); final String getTitle; Stream<String> get showTitle async* { yield getTitle; } ..... Container( child: Consumer<String>( builder: (context, String showTitle, child) => googleMap(showTitle) ), ), TextField( controller: Controller, onSubmitted: (value) { StreamProvider<String>( create: (_) => StreamTitle(getTitle:Controller.text).showTitle, initialData: Controller.text); }, ), googleMap.dart
Flutter how to check if textfield is not empty on submit using rxdart
I have 2 text fields that checks if empty On value change but the problem is if I press the submit function and the text fields are empty it does not show the error. How do I implement checking values on submit and show the error on text field? UI Widget buildColumn() => Form( child: Column( mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ Padding( padding: const EdgeInsets.all(8.0), child: buildTitle(), ), SizedBox( height: 10, ), Padding( padding: const EdgeInsets.all(8.0), child: buildDesription(), ), buildSubmit() ], )); Widget buildTitle() => StreamBuilder<String>( stream: manager.title, builder: (context, snapshot) { debugPrint(snapshot.toString()); return TextField( onChanged: manager.inTitle.add, decoration: InputDecoration( labelText: 'Title', labelStyle: TextStyle(fontWeight: FontWeight.bold), errorText: snapshot.error == null ? null : snapshot.error.toString()), ); }); Widget buildDesription() => StreamBuilder<String>( stream: manager.description, builder: (context, snapshot) { return TextField( onChanged: manager.inDescription.add, decoration: InputDecoration( labelText: 'Description', labelStyle: TextStyle(fontWeight: FontWeight.bold), errorText: snapshot.error == null ? null : snapshot.error.toString()), ); }); Widget buildSubmit() => StreamBuilder<Object>( stream: manager.isFormValid, builder: (context, snapshot) { return ElevatedButton( onPressed: () { if (snapshot.hasData) { manager.submit(); debugPrint("YEs"); } }, child: Text("SEND")); }); } Manager On submit does not check if title and description is empty class CreatePostManager with Validation { final _repository = PostRepository(); final _postsFetcher = PublishSubject<Post>(); Stream<Post> get addPost => _postsFetcher.stream; final _title = BehaviorSubject<String>(); Stream<String> get title => _title.stream.transform(validateTitle); Sink<String> get inTitle => _title.sink; final _description = BehaviorSubject<String>(); Stream<String> get description => _description.stream.transform(validateDescription); Sink<String> get inDescription => _description.sink; final _loading = BehaviorSubject<bool>(); Stream<bool> get loading => _loading.stream.transform(checkLoading); Sink<bool> get inLoading => _loading.sink; Stream<bool> get isFormValid => Rx.combineLatest2(title, description, (a, b) => true); Future submit() async { inLoading.add(true); String title = _title.value; String description = _description.value; Post itemModel = await _repository.addPost(title, description); _postsFetcher.sink.add(itemModel); inLoading.add(false); return itemModel; } dispose() { _postsFetcher.close(); } } Validator mixin Validation { final validateTitle = StreamTransformer<String, String>.fromHandlers(handleData: (value, sink) { if (value.isEmpty) { sink.addError("Title cannot be empty"); }else { sink.add(value); } }); final validateDescription = StreamTransformer<String, String>.fromHandlers(handleData: (value, sink) { if (value.isEmpty) { sink.addError("Description cannot be empty"); }else { sink.add(value); } }); final checkLoading = StreamTransformer<bool, bool>.fromHandlers(handleData: (value, sink) { sink.add(value); }); } On submit I want to check if textfields are empty and show the Error message. Currently it only shows when user types.
On submission, the TextField can be validated using its Controllers. _textFieldController = TextEditingController(); ... TextField( controller: _textFieldController, ) The TextField value can then be fetched using TextEditingController().value.text. Add a checker against this value on submission. Another way of validating TextFields is with the use of the validator in TextFormField TextFormField( // When a String is returned, it's displayed as an error on the TextFormField validator: (String? value) { return (value == null || value == '') ? 'Field should not be empty.' : null; }, )
Flutter Dynamic Textfield Autocompletion
I use the library autocomplete_textfield to create a textfield with autocompletion. Every time the text is changed I make a request to fetch a specific list of users and then set them to the suggestion of my AutocompleteTextfield. The list seems to be updated (when I print(list.length)) but visually it isn't. Any idea? My AutocompletionTextfield: AutoCompleteTextField<User>( textChanged: (item) async { await model.searchRecommendation(item); }, decoration: InputDecoration( border: OutlineInputBorder( borderRadius: BorderRadius.circular(0) ), labelText: 'Recommendations', labelStyle: TextStyle(color: AppColors.blackColor) ), key: autocompleteUserSearchTextFieldKey, suggestionsAmount: 3, controller: _userSearchController, itemSubmitted: (item) {}, suggestions: model.userRecommendations, itemBuilder: (context, suggestion) => new Padding( padding: EdgeInsets.all(16), child: ListTile( title: Text(suggestion.email) ), ), itemSorter: (a, b) => a.email.compareTo(b.email), itemFilter: (suggestion, input) => suggestion.email.toLowerCase().startsWith(input.toLowerCase()), ), my viewmodel: List<User> userRecommendations = []; Future searchRecommendation(String filter) async { var token = await SharedPreferenceUtils().getStringValue('jwt'); final response = await _api.filterUserSearch(filter, currentUser, token); if (response is SuccessState) { List<dynamic> tmp = response.value.payload; tmp ??= []; userRecommendations = List<User>.from(tmp.map((x) => User.fromJson(x))); notifyListeners(); } else if (response is ErrorState) { String error = response.msg; print('Error $error'); } else { print('Error'); } }
Nvm I found the answer! AutocompleteTextfield has a method called updateSuggestions(). I just had to use it.
I don't see all of your code, but I assume the widget tree isn't being rebuilt. You have to wrap AutoCompleteTextField with FutureBuilder or StreamBuilder (depending on your implementation, anyway StreamBuilder seems more appropriate there) that listens to recommendations result. You could also implement StatefulWidget or use StatefulBuilder. Example with StatefulBuilder (it's dirty but should work, ideally you'd use StreamBuilder): return StatefulBuilder( builder: (context, setState) => AutoCompleteTextField<User>( textChanged: (item) async { await model.searchRecommendation(item); setState(() {}); }, decoration: InputDecoration( border: OutlineInputBorder(borderRadius: BorderRadius.circular(0)), labelText: 'Recommendations', labelStyle: TextStyle(color: AppColors.blackColor)), key: autocompleteUserSearchTextFieldKey, suggestionsAmount: 3, controller: _userSearchController, itemSubmitted: (item) {}, suggestions: model.userRecommendations, itemBuilder: (context, suggestion) => new Padding( padding: EdgeInsets.all(16), child: ListTile(title: Text(suggestion.email)), ), itemSorter: (a, b) => a.email.compareTo(b.email), itemFilter: (suggestion, input) => suggestion.email.toLowerCase().startsWith(input.toLowerCase()), ), );
type 'BehaviorSubject<dynamic>' is not a subtype of type 'Stream<String>' of 'stream'
I have this weird error I'm getting and I can't seem to fix this. I am implementing the bloc pattern in my login page. I can't seem to point out what I am doing wrong. Here is my code login_bloc.dart import 'package:rxdart/rxdart.dart'; import 'dart:async'; class LoginBloc extends Object with Validators { final _emailController = BehaviorSubject<dynamic>(); final _passwordController = BehaviorSubject<dynamic>(); Function(String) get emailChanged => _emailController.sink.add; Function(String) get passwordChanged => _passwordController.sink.add; Stream<String> get emailValidator => _emailController.stream.transform(emailValidators); Stream<String> get passwordValidator => _passwordController.stream.transform(passwordValidators); Stream<bool> get submitCheck => Rx.combineLatest2(emailValidator, passwordValidator, (e, p) => true); dispose() { _emailController?.close(); _passwordController?.close(); } } mixin Validators { var emailValidators = StreamTransformer<String, String>.fromHandlers(handleData: (email, sink) { if (email.contains("#")) { sink.add(email); } else { sink.addError("Email is not valid"); } }); var passwordValidators = StreamTransformer<String, String>.fromHandlers( handleData: (password, sink) { if (password.length > 0) { sink.add(password); } else { sink.addError("Password Field should not be empty"); } }); } final loginBloc = LoginBloc(); here is the widget i created calling the bloc Widget _emailPasswordWidget() { return Column( children: <Widget>[ Container( margin: EdgeInsets.symmetric(vertical: 10), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text( 'Email ID', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 15), ), SizedBox( height: 10, ), StreamBuilder<String>( stream: loginBloc.emailValidator, builder: (context, snapshot) { return TextField( onChanged: loginBloc.emailChanged, obscureText: false, decoration: InputDecoration( errorText: snapshot.error, border: InputBorder.none, fillColor: Color(0xfff3f3f4), filled: true)); } ) ], ), ) loginBloc.passwordChanged), ], ); } I would appreciate any help whatsoever. I have checked online and I have not seen any help. I am using rxdart version ^0.23.1. I have used a streamcontroller instead of the behaviour subject and I have used a publishsubject too and i still get the error.
there is no need for the BehaviorSubject to be of type dynamic when everything going through will be Strings, so the best fix is to type it like so : BehaviorSubject<String>()
How to implement validation with keyboard done button Flutter, observable, streamBuilder
I'm building an app with Flutter and Bloc like architecture. I'm trying to call submit func with not only login button but also keyboard done button with password; only when email and password are valid. I could implement login button version with combineLatest, but I'm not sure keyboard version. I need to validate both email and password when keyboard done button pressed before calling submit. I could nest streamBuilder, but I feel it is not good practice. Is there any way to get the latest value from combineLatest? BehaviorSubject<bool>().value Or any possible advice to implement this. sample code: final _emailController = BehaviorSubject<String>(); final _passwordController = BehaviorSubject<String>(); // Add data to stream Stream<String> get email => _emailController.stream.transform(validateEmail); Stream<String> get password => _passwordController.stream.transform(validatePassword); Stream<bool> get submitValid => Observable.combineLatest2(email, password, (e, p) => true); // change data Function(String) get changeEmail => _emailController.sink.add; Function(String) get changePassword => _passwordController.sink.add; submit() { final validEmail = _emailController.value; final validPassword = _passwordController.value; print('Email is $validEmail, and password is $validPassword'); } import 'package:flutter/material.dart'; import '../blocs/bloc.dart'; import '../blocs/provider.dart'; class LoginScreen extends StatelessWidget { #override Widget build(BuildContext context) { final bloc = Provider.of(context); return Container( margin: EdgeInsets.all(20.0), child: Column( children: <Widget>[ emailField(bloc), passwordField(bloc), Container( margin: EdgeInsets.only(top: 25.0), ), submitButton(bloc), ], ), ); } Widget emailField(Bloc bloc) { return StreamBuilder( stream: bloc.email, builder: (context, snapshot) { return TextField( onChanged: bloc.changeEmail, keyboardType: TextInputType.emailAddress, decoration: InputDecoration( hintText: 'ypu#example.com', labelText: 'Email Address', errorText: snapshot.error, ), ); }, ); } Widget passwordField(Bloc bloc) { return StreamBuilder( stream: bloc.password, builder: (context, snapshot) { return TextField( obscureText: true, onChanged: bloc.changePassword, decoration: InputDecoration( hintText: 'Password', labelText: 'Password', errorText: snapshot.error, ), textInputAction: TextInputAction.done, onSubmitted: () {}, // <- here ); }); } Widget submitButton(Bloc bloc) { return StreamBuilder( stream: bloc.submitValid, builder: (context, snapshot) { return RaisedButton( child: Text('Login'), color: Colors.blue, onPressed: snapshot.hasData ? bloc.submit : null, ); }, ); } }
You can wrap Your Password streamBuilder with another streamBilder and onSubmitted call submit method. Widget passwordField(Bloc bloc) { return StreamBuilder( stream: bloc.submitValid, builder: (context, snap) { return StreamBuilder( stream: bloc.password, builder: (context, snapshot) { return TextField( obscureText: true, onChanged: bloc.changePassword, decoration: InputDecoration( hintText: 'Password', labelText: 'Password', errorText: snapshot.error, ), textInputAction: TextInputAction.done, onSubmitted: snap.hasData ? bloc.submit : null, ); }); }); }