Listen to a new value of a bloc and generate a list of listened items - flutter

I have this StreamSubscription field called followSubscribtion. It listens if there is a new follower and then calls populateFollower to load follower profile.
followsSubscription =
getBloc(context).followsHandler.stream.listen((value) async {
if (value.status == Status.success) {
await populateFollows();
}
});
});
populateFollows() async{
if (getBloc(context).followsModel.length > 0) {
for (var i = 0; i < getBloc(context).followsModel.length; i++) {
getBloc(context).loadFollowsProfile(getBloc(context).followsModel[i].userId);
break;
}
}
}
This works fine, But I want each profile that will be loaded to be added to a list, How do I do that?
loadFollowsProfile method
loadFollowsProfile(int id , List<UserProfileModel> profileList) {
getFollowsProfileHandler.addNetworkTransformerStream(
Network.getInstance().getUserProfile(id), (_) {
userProfileModelBloc = UserProfileModel.fromJson(_);
profileList.add(userProfileModelBloc);
return userProfileModelBloc;
});
}

You can do this by setting up loadFollowsProfile() to return a UserProfileModel, adding that to a list in the for loop of populateFollows(), and then returning that list from populateFollows().
List<ProfileObject> populateFollows() async{
List<ProfileObject> profileList = [];
if (getBloc(context).followsModel.length > 0) {
for (var i = 0; i < getBloc(context).followsModel.length; i++){
profileList.add(getBloc(context).loadFollowsProfile(
getBloc(context).followsModel[i].userId
));
break;
}
}
return profileList;
}
followsSubscription =
getBloc(context).followsHandler.stream.listen((value) async {
if (value.status == Status.success) {
profileList = await populateFollows();
}
});
});

Related

The function finds only one element, even if there is more than one

The function below finds only one item in the list, even if there are multiple items, how do I fix this function to find all items?
List newList = [];
if (value.isNotEmpty) {
for (var element in pressures) {
if (element.pressure.contains(value) ||
element.date.toString().contains(value)) {
newList.clear();
newList.add(element);
}
}
items.value = newList;
} else {
items.value = pressures;
}
You are clearing the list on loop
if (value.isNotEmpty) {
newList.clear(); // you can clear it on top of the loop
for (var element in pressures) {
if (element.pressure.contains(value) ||
element.date.toString().contains(value)) {
// newList.clear(); //remove this
newList.add(element);
}
}
items.value = newList;
} else {
items.value = pressures;
}

XMLHTTPRequest error but only when added to main project

so I have this code:
import 'dart:convert';
import 'package:http/http.dart' as http;
List getMenuDay(String day, List canteenMenu) {
if (day == "tuesday") {
return canteenMenu[0];
}
else if (day == "wednesday") {
return canteenMenu[1];
}
else if (day == "thursday") {
return canteenMenu[2];
}
else if (day == "friday") {
return canteenMenu[3];
}
else if (day == "saturday") {
return canteenMenu[4];
}
else if (day == "sunday") {
return canteenMenu[5];
}
else {
return [];
}
}
String getDayPlate(String day, String plate, List canteenMenu) {
List dayMenu = getMenuDay(day, canteenMenu);
if (plate == "sopa") {
return dayMenu[0];
}
else if (plate == "carne") {
return dayMenu[1];
}
else if (plate == "peixe") {
return dayMenu[2];
}
else if (plate == "dieta") {
return dayMenu[3];
}
else if (plate == "vegetariano") {
return dayMenu[4];
}
return "";
}
void main() async {
List list = [];
List helper = [];
const canteenUrl = 'https://sigarra.up.pt/feup/pt/mob_eme_geral.cantinas';
var response = await http.get(Uri.parse(canteenUrl));
if (response.statusCode == 200) {
var data = json.decode(response.body);
for (int i = 0; i < 4; i++) { // loop through different days
for (int j = 0; j < 5; j++) { // loop through different types of food
var parkInfo = data[3]["ementas"][i]["pratos"][j]["descricao"];
helper.add(parkInfo);
//print(parkInfo);
}
list.add(helper);
helper = [];
//print("--------------");
}
/*
for (int i = 0; i < list.length; i++) {
print(list[i]);
}
*/
print(getDayPlate("thursday", "carne", list));
} else {
throw Exception('Failed to read $canteenUrl');
}
}
and when I just create a new project, type it into the main.dart file and run it, it works fine. But when I add it to make whole project, including other files (making the necessary changed like changing the name of the function, etc), it gives me the XMLHTTPRequest error. What could be causing that? The way I'm calling it withing the main project is as follows:
ElevatedButton(
style: style,
onPressed: () {
CanteenInfo canteen = CanteenInfo("tuesday","sopa");
print(canteen.getDayPlate());
},
child: const Text('ShowLen (WIP)'),
Thanks for any help you could give!
Edit 1: I do get a warning when running just the code,
lib/main.dart: Warning: Interpreting this as package URI, 'package:new_test/main.dart'.

Why loadInitTopStory method called after calling loaded state in flutter?

HackerNewsLoadedState is called before HackerNewsLoadingState and it loads all data from API but does not integrate to _topStories list as well as store data to _topstories after calling HackerNewsLoadedState.
#override
Stream<HackerNewsState> mapEventToState(HackerNewsEvent event) async* {
if (event is FetchHackerNewsEvent) {
yield HackerNewsLoadingState();
try {
_loadInitTopStories();
yield HackerNewsLoadedState(story: _topStories);
} catch (e) {
yield HackerNewsErrorState(message: e.toString());
}
}
}
void _loadInitTopStories() async {
try {
_topStoryIds.addAll(await _repository.loadTopStoryIds());
} catch (e) {
_topStoriesStreamController.sink.addError('Unknown Error');
return;
}
loadMoreTopStories(pageSize: INIT_PAGE_SIZE);
}
void loadMoreTopStories({int pageSize = PAGE_SIZE}) async {
if (_isLoadingMoreTopStories) return;
_isLoadingMoreTopStories = true;
final storySize = min(_currentStoryIndex + pageSize, _topStoryIds.length);
for (int index = _currentStoryIndex; index < storySize; index++) {
try {
_topStories.add(await _repository.loadStory(_topStoryIds[index]));
} catch (e) {
print('Failed to load story with id ${_topStoryIds[index]}');
}
}
_currentStoryIndex = _topStories.length;
_topStoriesStreamController.sink.add(_topStories);
_isLoadingMoreTopStories = false;
}
Found the solution it's return void but it's a mistake, it returns Stream
Stream<HackerNewsState> _loadInitTopStories() async* {
yield HackerNewsLoadingState();
try {
_topStoryIds.addAll(await repository.loadTopStoryIds());
} catch (e) {
_topStoriesStreamController.sink.addError('Unknown Error');
return;
}
yield* loadMoreTopStories(pageSize: INIT_PAGE_SIZE);
yield HackerNewsLoadedState(story: _topStories);
}
Stream<HackerNewsState> loadMoreTopStories(
{int pageSize = PAGE_SIZE}) async* {
if (_isLoadingMoreTopStories) return;
_isLoadingMoreTopStories = true;
final storySize = min(_currentStoryIndex + pageSize, _topStoryIds.length);
for (int index = _currentStoryIndex; index < storySize; index++) {
try {
_topStories.add(await repository.loadStory(_topStoryIds[index]));
} catch (e) {
print('Failed to load story with id ${_topStoryIds[index]}');
}
}
_currentStoryIndex = _topStories.length;
_topStoriesStreamController.sink.add(_topStories);
_isLoadingMoreTopStories = false;
}

Using the below script i am working on Pagination using Protractor script where is am seeing "summaryPage" is not defined

this.getPaginationsize = element.all(by.repeater('page in groupArray track by $index'));
summaryPage.getPaginationsize.count().then(function (pagination) {
if (pagination > 0) {
for (var i = 0; i < pagination; i++) {
summaryPage.getPaginationsize.get(i).click();
}
} else {
console.log('Pagination not exists');
}
});
this.getPaginationsize = element.all(by.repeater('page in groupArray track by $index'));
this.getPaginationsize.count().then(function (pagination) {
if (pagination > 0) {
for (var i = 0; i < pagination; i++) {
summaryPage.getPaginationsize.get(i).click();
}
} else {
console.log('Pagination not exists');
}
you should change it to this as you are referring to the same module you are present in

Flutter play list of files after each other

I'm trying to play a list of files one after the other, but it plays all together, anyone can help?
I'm using the library AudioPlayers for that
thanks
case 2: {
//statements;
for(int i = 0; i < letterList1().length; i++){
String file = letterList1()[i]['audio'];
advancedPlayer = await player.play(file);
if(advancedPlayer.state == AudioPlayerState.PLAYING){
advancedPlayer.onPlayerCompletion.listen((onDone) async {
advancedPlayer.state = AudioPlayerState.COMPLETED;
});
}
playingFile = file;
}
}
break;
case 1: {
//statements;
for(int i = 0; i < letterList1().length; i++){
String file = letterList1()[i]['audio'];
advancedPlayer = await player.play(file);
playingFile = file;
while(advancedPlayer.state == AudioPlayerState.PLAYING){
print("while: ${advancedPlayer.state}");
await Future.delayed(Duration(seconds: 1));
print(i);
if(advancedPlayer.state == AudioPlayerState.PLAYING){
advancedPlayer.onPlayerCompletion.listen((onDone) async {
print("object");
player.clear(file);
advancedPlayer.state = AudioPlayerState.COMPLETED;
await advancedPlayer.stop();
});
}
if(advancedPlayer.state == AudioPlayerState.COMPLETED){
print("if: ${advancedPlayer.state}");
await advancedPlayer.stop();
break;
}
}
}
}
break;