John Joe
John Joe

Reputation: 12803

StreamBuilder flutter

I added two item in list, then add the list to sink.

var list = new List<String>();
AbcBloc _abcBloc = AbcBloc(repository: null);

 @override
  void didChangeDependencies() {
    _abcBloc = Provider.of<AbcBloc>(context);
    super.didChangeDependencies();
  }

@override
  void initState() {
    super.initState();

    list.add('Electrical');
    list.add('Inspection');

    _abcBloc.listSink.add(list);
  }

But when I try to print the list in TextField, it prints empty?

  StreamBuilder(
                      stream: _abcBloc.listStream,
                      builder: (context, snapshot) {
                        return TextField(
                          decoration: InputDecoration(
                              labelText: snapshot.data,
                             ....
                        );
                      },
                    ),

AbcBloc.dart

  final _list = BehaviorSubject<List<String>>();
  get listSink => _list.sink;
  get listStream => _list.stream;

Edit

After use the suggestion answers, it print null value. Why would this happened?

Upvotes: 0

Views: 1221

Answers (3)

John Joe
John Joe

Reputation: 12803

I was able to fix it.What I did was put the list and the stream in didChangeDependencies.

  @override
  void didChangeDependencies() {
     _abcBloc = Provider.of<AbcBloc>(context);      
     list.add('Electrical');
     list.add('Inspection');    
     _abcBloc.listSink.add(list);
     super.didChangeDependencies();

  }

Upvotes: 0

amugofjava
amugofjava

Reputation: 627

Firstly, snapshot.data is a list of String items so to display the list as a single String you need to add a toString(); Secondly, you need to be more specific with types - you need to specify what data your StreamBuilder expects, i.e.

    StreamBuilder<List<String>>(
      stream: _abcBloc.listStream,
      builder: (context, snapshot) {
        return TextField(
            decoration: InputDecoration(
          labelText: snapshot.data.toString(),
        ));
      },
    ),

Taking your example and making those two changes then resulted in [Electrical, Inspection] showing in the text field on my device.

Upvotes: 1

Igor Kharakhordin
Igor Kharakhordin

Reputation: 9903

Problems I see:

  • StreamBuilder has no generic type. Make it StreamBuilder<List<String>>
  • You're passing List to labelText parameter. You should pass String. (e.g. snapshot.data.toString())
  • You don't check whether your stream has data or not inside builder. You can do it using snapshot.hasData condition or set initialData parameter.

Upvotes: 0

Related Questions