Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert Stream<List<String>> to List<String> in flutter

Tags:

flutter

dart

I am trying to convert a Stream<List<String>> to List<String> in flutter here is my code

Stream<List<String>> _currentEntries;

/// A stream of entries that should be displayed on the home screen.
Stream<List<String>> get categoryEntries => _currentEntries;

_currentEntries is getting populated with data from a database. I want to convert _currentEntries into List<String>

I tried the following code but doesn't work:

List<List<String>> categoryList () async  {
  return await _currentEntries.toList();
}

I get the following error:

A value of type List<List<String>> can't be returned from method categoryList because it has a return type of List<List<String>>

Can someone help how to solve this issues and convert a Stream<List<String> to List<String>?

like image 1000
yoohoo Avatar asked May 27 '20 23:05

yoohoo


2 Answers

The issue seems to be with your return type for categoryList. You're returning as List of Lists when the Stream only contains a single layer of List. The return type should be Future<List<String>>.

Use .first, .last, or .single in addition to await to get just a single element, and toList() should be removed.

Future<List<String>> categoryList () async  {
  return await _currentEntries.first;
}

Also a quick tip: Dart automatically generates getters and setters for all fields so the getter method you show isn't necessary.

like image 72
Christopher Moore Avatar answered Oct 20 '22 06:10

Christopher Moore


As title said, question is how to convert stream of some items to item. So what Christopher answered it is ok but only if you want to take the first value from the stream. As streams are asynchronous, they can provide you a value in any point of a time, you should handle all events from the stream (not only the first one).

Let's say you are watching on a stream from database. You will receive new values from database on each database data modification, and by that you can automatically update GUI according to newly received values. But not if you are taking just first value from stream, it will be updated only the first time.

You can take any value and handle it ("convert it") by using listen() method on a stream. Also you can check this nicely written tutorial on Medium. Cheers!

 Stream<List<String>> _currentEntries = watchForSomeStream();

 _currentEntries.listen((listOfStrings) {
    // From this point you can use listOfStrings as List<String> object
    // and do all other business logic you want

    for (String myString in listOfStrings) {
      print(myString);
    }
 });
like image 42
bkekelic Avatar answered Oct 20 '22 05:10

bkekelic