How to give a default value to a textfield when using bloc framework
You can give your behaviorSubject a seed value that will be used as its initial value by doing this.
final nameStreamController = BehaviorSubject<String>.seeded('InitialName');
for older versions of rxDart, use
final nameStreamController = BehaviorSubject<String>(seedValue:'InitialName');
Without knowing what you want to do with the name field, there are a few routes you can go.
You could supply a hintText
to the InputDecoration
(InputDecoration(hintText: 'name')
).
You could set an initial value on the StreamBuilder:
StreamBuilder( stream: bloc.nameStream, initialData: 'Initial Name', builder: (context, snapshot) { return TextField( onChanged: bloc.nameChangedStream, decoration: InputDecoration(labelText: 'Enter name' ), ); } ),
Though, that won't persist that value in the stream, so if the user doesn't change the text field, 'Initial Name' won't be in your nameStreamController
's stream.
As @nonybrighto mentioned, you can seed your nameStreamController
with the initial value.
If you cannot use a seeded value, you could also add an initial value to your stream during the bloc's init:
class Bloc { final nameStreamController = BehaviorSubject<String>(); Stream<String> get nameStream => nameStreamController.stream; Function(String) get nameChangedStream => nameStreamController.sink.add; Bloc() { String initialValue = _getInitialValue(); nameStreamController.add(initialValue); }}
Here's a more full, real-world example: we found this authentication and login BLoC example in which we followed a lot of the stuff laid out here: Didier Boelens BloC Example. It shows you how can use BLoC, reactive programming, and streams to set up a registration form and auth.