i have a technical doubt. Can you please let me know how to await a function in for loop within streambuilder. Function depends on data from streambuilder
I have streambuilder whics has stream of firestore data. Once the snapshot has data then i run a for loop to make a list of data within snapshot. Now the problem im facing is that how will i call a async function within for loop within streambuilder. This async function fetches data from other collection in firestore and depnds on streambuilder data
class LeagueGroupByListModel {
String? name;
Map? listData;
LeagueGroupByListModel({
required this.name,
required this.listData,
});
}
class PublicScreen extends StatefulWidget {
const PublicScreen({Key? key}) : super(key: key);
@override
State<PublicScreen> createState() => _PublicScreenState();
}
class _PublicScreenState extends State<PublicScreen> {
//late PublicListController _publicListController;
final FirebaseFirestore _db = FirebaseFirestore.instance;
final DBServicesFootball _dbServicesFootball = DBServicesFootball();
SeasonModelYear _seasonModelYear = SeasonModelYear();
List<Matches?> listofStatus = [];
String? wholeLeagueStatus;
var listofLeaguesAsRound = [];
List<LeagueModelFootball>? lgModelFootball = [];
List<dynamic> ftLeagues = [];
Map? groupedItems;
getDataFromSeasons(int roundNumber) async {
//lgModelFootball = await _dbServicesFootball.fetchDatafromDBWithDocID("fs_leagues_collection")
String round = "round_" + roundNumber.toString();
_seasonModelYear = await _dbServicesFootball.fetchDataFromSeasons(round);
if (_seasonModelYear == null || _seasonModelYear.matches == null)
return null;
var uniqueList = Set<String>();
listofStatus = _seasonModelYear.matches!.where((element) {
if (element.matchStatus != null) {
return uniqueList.add(element.matchStatus!);
} else
return false;
}).toList();
if (listofStatus.length == 1) {
wholeLeagueStatus = listofStatus[0]!.matchStatus;
//listofLeaguesAsStatus = [{wholeLeagueStatus: }]
print("Round number ${listofStatus.length}");
print(wholeLeagueStatus);
return wholeLeagueStatus;
} else
return null;
}
@override
void initState() {
// TODO: implement initState
// _publicListController = PublicListController();
super.initState();
}
var leagueModelFootballLiveList = [];
var leagueModelFootballFutureList = [];
String? publicLeagueName;
int? lifePerUSer;
bool? leaguePvt;
List<dynamic> publicLeagues = [];
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: ColorManager.primary,
body: StreamBuilder(
stream: _db.collection("fs_leagues_collection").snapshots(),
builder: (context, AsyncSnapshot snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
case ConnectionState.active:
case ConnectionState.done:
if (snapshot.hasData) {
print("It has data");
List<dynamic> data =
snapshot.data!.docs.map((DocumentSnapshot document) {
Map<String, dynamic> da =
document.data()! as Map<String, dynamic>;
return da;
}).toList();
// for (int i = 0; i < data.length; i++) {
// if (data[i].isLive == true) {
// leagueModelFootballLiveList.add(data[i]);
// } else {
// leagueModelFootballFutureList.add(data[i]);
// }
// //lgModelFootball![i] = data[i];
// // leaguePvt = data[i]["leaguePrivate"];
// // lifePerUSer = data[i]["lifePerUser"];
// // publicLeagueName = data[i]["name"];
// print(data[i].isLive);
// }
if (data.length > 0) {
//for (int i = 0; i < data.length; i++) {
//if (data[i]["leaguePrivate"] == true) {
var uniqueList = Set<String>();
publicLeagues = data.where((element) {
if (!element["leaguePrivate"])
return uniqueList.add(element["uuid"]);
else
return false;
}).toList();
//}
//}
print("Pvt ${publicLeagues.length}");
}
Map groupByListName(List items) {
return groupBy(items, (item) => item.name);
}
if (publicLeagues.length > 0) {
List<LeagueGroupByListModel> itemList = [];
for (int i = 0; i < publicLeagues.length; i++) {
//Call the below function it is async function
getDataFromSeasons(publicLeagues[i]["startRound"]);
print("Whole Lg status $wholeLeagueStatus");
itemList.add(LeagueGroupByListModel(
name: wholeLeagueStatus ?? "Nothing",
listData: publicLeagues[i]));
}
print("Ite ${itemList[0].name} ${itemList[0].listData}");
groupedItems = groupByListName(itemList);
}
return publicLeagues.length > 0
? Padding(
padding: const EdgeInsets.only(
top: AppPadding.p12,
bottom: AppPadding.p8,
left: AppPadding.p8,
right: AppPadding.p8),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Expanded(
//fit: FlexFit.loose,
child: ListView.builder(
itemCount: groupedItems!.length,
itemBuilder:
(BuildContext context, int index) {
String status =
groupedItems!.keys.elementAt(index);
print("Status $status");
print("It ${groupedItems![status]}");
List itemsInData = groupedItems![status];
return Column(
children: [
Text(
status,
//AppStrings.leagueName,
// widget.publicData["isLive"]
// ? AppStrings.leagueName
// : AppStrings.leagueFutureName,
style: getSemiBoldStyle(
color:
ColorManager.leagueTextColor1,
),
),
const SizedBox(
height: AppSize.s4,
),
Divider(
thickness: AppSize.s1_5,
color:
ColorManager.leagueDividerColor,
),
ListView.separated(
shrinkWrap: true,
physics: ClampingScrollPhysics(),
itemBuilder: (BuildContext context,
int index) {
print("Itms ${itemsInData[index]}");
return PublicListWidget(
publicData: itemsInData[index],
);
},
separatorBuilder: (context, index) {
return Divider();
},
itemCount: itemsInData.length,
),
],
);
},
),
),
],
),
)
: Center(
child: Text(
AppStrings.noPubLicLeagueText,
style: getBoldStyle(
color: ColorManager.white,
fontSize: FontSize.s16),
),
);
} else {
return Center(
child: Text(
AppStrings.noPubLicLeagueText,
style: getBoldStyle(
color: ColorManager.white, fontSize: FontSize.s16),
),
);
}
default:
return ErrorScreen();
}
}),
);
}
}
StreamBuilder. Please check the following example.