The data from my firestore isn't displayed - flutter

I tried to build an application, which shows the user some places on a google maps. The data for the places (location, name) should the app take from the firestore. The app already can display the maker in the google maps, but I also want some details in the bottom of the application in an Animated Builder, but it doesn't work. The problem is, that I can't get the name of the place with specify['name'] in my _restaurantList function, but in the initMarker function it works. I think it has to do something with the _restaurantList(specify) and the return _restaurantList(index) but I don't know what the mistake is. I also tried to use specify instead of index in the _restaurantList(index), but then I got an error. But I think I have to use _restaurantList(specify) in order to use specify['name'] afterwards.
Does anyone know what my mistake is?
That's my code:
void initMarker(specify, specifyId) async {
// await Firebase.initializeApp();
var markerIdVal = specifyId;
final MarkerId markerId = MarkerId(markerIdVal);
final Marker marker = Marker(
markerId: markerId,
position:
LatLng(specify['location'].latitude, specify['location'].longitude),
infoWindow: InfoWindow(title: specify['name'], snippet: 'Shop'),
);
print(specify['location'].latitude);
nameTest = specify['name'];
setState(() {
markers[markerId] = marker;
print(markerId.toString() + '__________________________');
});
}
getMarkerData() async {
Firestore.instance.collection('seller').getDocuments().then((myMockDoc) {
if (myMockDoc.documents.isNotEmpty) {
for (int i = 0; i < myMockDoc.documents.length; i++) {
length = myMockDoc.documents.length;
print(length);
initMarker(
myMockDoc.documents[i].data(), myMockDoc.documents[i].documentID);
}
}
});
}
_restaurantList(specify) {
return AnimatedBuilder(
animation: _pageController,
builder: (BuildContext context, Widget widget) {
double value = 1;
if (_pageController.position.haveDimensions) {
//value = _pageController.page - index;
value = (1 - (value.abs() * 0.3) + 0.06).clamp(0.0, 1.0);
}
return Center(
child: SizedBox(
height: Curves.easeInOut.transform(value) * 175.0,
width: Curves.easeInOut.transform(value) * 350.0,
child: widget,
),
);
},
child: InkWell(
onTap: () {
null;
},
child: Stack(
children: [
Center(
child: Container(
margin: EdgeInsets.symmetric(
horizontal: 10.0,
vertical: 20.0,
),
height: 125.0,
width: 275.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10.0),
boxShadow: [
BoxShadow(
color: Colors.black54,
offset: Offset(0.0, 4.0),
blurRadius: 10.0,
),
]),
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10.0),
color: Colors.white),
child: Text(
specify['name'],
),
),
),
)
],
),
),
);
}
And this is in the Scaffold:
Positioned(
bottom: 20.0,
child: Container(
height: 200.0,
width: MediaQuery.of(context).size.width,
child: PageView.builder(
controller: _pageController,
itemCount: length,
itemBuilder: (BuildContext context, int index) {
return _restaurantList(index);
},
),
),
)

Related

flutter infinite scrolling data from server in listview builder

I am using graphql_flutter to load data from the server and I should update moreId for the update page in my server and get more data to load, and I need to use infinite for it.
How can I do it?
class MoreEpd extends StatefulWidget {
final String moreId;
const MoreEpd({Key? key, required this.moreId}) : super(key: key);
#override
_MoreEpdState createState() => _MoreEpdState();
}
class _MoreEpdState extends State<MoreEpd> {
double pageWidth = 0;
double pageHeigh = 0;
int pageNum = 0;
final String leftArrow = 'assets/icons/left-arrow.svg';
String getSearchResult = """
query homeview(\$moreId: ID!, \$page: Int! ){
homeview(HM_ID: \$moreId, page: \$page){
HM_ID
HM_Type_ID
HM_Type_Name
HM_NAME
Priority
Details{
HM_Det_ID
HM_ID
Ep_ID
Pod_ID
Link
Image
title
Pod_title
}
}
}
""";
#override
Widget build(BuildContext context) {
pageWidth = MediaQuery.of(context).size.width;
pageHeigh = MediaQuery.of(context).size.height;
return Container(
child: Query(
options: QueryOptions(
document: gql(getSearchResult),
variables: {'moreId': widget.moreId, 'page': pageNum},
),
builder: (
QueryResult result, {
Refetch? refetch,
FetchMore? fetchMore,
}) {
return handleResult(result);
},
),
);
}
Widget handleResult(QueryResult result) {
var data = result.data!['homeview']['Details'] ?? [];
return Container(
child: ListView.builder(
padding: EdgeInsets.only(top: 15),
shrinkWrap: true,
itemCount: data.length ,
itemBuilder: (context, index) {
return InkWell(
onTap: () {},
child: Padding(
padding: EdgeInsets.only(
top: pageWidth * 0.0,
right: pageWidth * 0.08,
left: pageWidth * 0.08,
bottom: pageWidth * 0.0),
child: Container(
child: Stack(
children: [
Column(
children: [
Padding(
padding:
EdgeInsets.only(bottom: pageWidth * 0.060),
child: Row(
children: [
Padding(
padding:
EdgeInsets.only(left: pageWidth * 0.01),
child: Container(
// alignment: Alignment.centerRight,
width: pageWidth * 0.128,
height: pageWidth * 0.128,
decoration: BoxDecoration(
image: DecorationImage(
fit: BoxFit.cover,
image: CachedNetworkImageProvider(
data[index]['Image'],
)),
borderRadius: BorderRadius.all(
Radius.circular(15)),
// color: Colors.redAccent,
border: Border.all(
color: MyColors.lightGrey,
width: 1,
)),
),
),
Expanded(
child: Row(
children: [
Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
Container(
width: pageWidth * 0.5,
alignment: Alignment.centerRight,
child: Text(
data[index]['title'],
textAlign: TextAlign.right,
overflow: TextOverflow.ellipsis,
maxLines: 1,
// softWrap: true,
style: TextStyle(
// fontWeight: FontWeight.bold,
fontSize: 14,
),
),
),
],
),
],
),
)
],
),
),
],
),
],
),
),
),
);
}));
}
}
First error is happening because of not handling the states of Query. In order to do that on builder:
delearing data on state level var data = [];
builder: (
QueryResult result, {
Refetch? refetch,
FetchMore? fetchMore,
}) {
if (result.hasException) {
return Text(result.exception.toString());
}
if (result.isLoading) {
return Column(
children: [
Expanded(
child: handleResult(data)), // show data while loading
const Center(
child: CircularProgressIndicator(),
),
],
);
}
data.addAll(result.data!['homeview']['Details'] ?? []);
return handleResult(data);
},
All we need now to increase the pageNum to get more data. I'm using load more button, better will be creating the load button end of list by increasing itemLength+=1.
Update using ScrollController.
// on state class
final ScrollController controller = ScrollController();
bool isLoading = false;
Load data on scroll
#override
void initState() {
super.initState();
controller.addListener(() {
/// load date at when scroll reached -100
if (controller.position.pixels >
controller.position.maxScrollExtent - 100) {
print("Scroll on loading");
if (!isLoading) {
print("fetching");
setState(() {
pageNum++;
isLoading = true;
});
}
}
});
}
Full Snippet on Gist
And about the position issue, you can check this

Flutter FutureBuilder calling function continuously

I have simple function which is calling data from firestore and filtering data. But issue is my futurebuilder keeps on loader situation (Data is called successfully i can see in console but now showing in future) I think its because my fucntion is calling in loop or something i have try to print something in my function which indicates me that my function is not stopping and thats why i think my futureBuilder keeps on loading.
My code
Future<List> getCustomerList() async {
print('calling');
String uUid1 = await storage.read(key: "uUid");
String uName1 = await storage.read(key: "uName");
String uNumber1 = await storage.read(key: "uNumber");
setState(() {
uUid = uUid1;
uName = uName1;
uNumber = uNumber1;
});
CollectionReference _collectionRef =
FirebaseFirestore.instance.collection('Customers');
QuerySnapshot querySnapshot = await _collectionRef.get();
// Get data from docs and convert map to List
List allData = querySnapshot.docs
.where((element) => element['sellerUID'] == uUid)
.map((doc) => doc.data())
.toList();
double gGive = 0;
double gTake = 0;
double gCal = 0;
for (int i = 0; i < allData.length; i++) {
// print(allData[i]);
// print('give ${double.parse(allData[i]['give'].toString()) }');
// print('take ${double.parse(allData[i]['take'].toString()) }');
double.parse(allData[i]['give'].toString()) -
double.parse(allData[i]['take'].toString()) >
0
? gGive += double.parse(allData[i]['give'].toString()) -
double.parse(allData[i]['take'].toString())
: gTake += double.parse(allData[i]['give'].toString()) -
double.parse(allData[i]['take'].toString());
}
// print(gGive);
// print(gTake);
setState(() {
Gtake = gGive.toString().replaceAll("-", "");
Ggive = gTake.toString().replaceAll("-", "");
});
if (greenBox) {
var check = allData.where((i) => i['take'] > i['give']).toList();
return check;
} else if (redBox) {
var check = allData.where((i) => i['give'] > 1).toList();
return check;
} else {
return allData;
}
}
And my futureBuilder look like this
Expanded(
child: Container(
height: Height * 0.5,
child: FutureBuilder(
future: getCustomerList(),
builder: (context, snapshot) {
if (snapshot.hasData) {
list = snapshot.data;
return SingleChildScrollView(
child: Column(
children: [
Container(
height: Height * 0.5,
child: ListView.builder(
shrinkWrap: true,
itemCount: list.length,
itemBuilder:
(BuildContext context,
int index) {
var showThis = list[index]
['give'] -
list[index]['take'];
return list[index]
['customerName']
.toString()
.contains(searchString)
? GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
CustomerData(
data: list[
index])),
);
},
child: Padding(
padding:
const EdgeInsets
.only(
left: 13,
right: 13),
child: Container(
decoration:
BoxDecoration(
border: Border(
top: BorderSide(
color: Colors
.grey,
width:
.5)),
),
child: Padding(
padding:
const EdgeInsets
.all(
13.0),
child: Row(
mainAxisAlignment:
MainAxisAlignment
.spaceBetween,
children: [
Row(
children: [
CircleAvatar(
child:
Text(
list[index]['customerName'][0]
.toString(),
style:
TextStyle(fontFamily: 'PoppinsBold'),
),
backgroundColor:
Color(0xffF7F9F9),
),
SizedBox(
width:
20,
),
Text(
list[index]['customerName']
.toString(),
style: TextStyle(
fontFamily:
'PoppinsMedium'),
),
],
),
Text(
'RS ${showThis.toString().replaceAll("-", "")}',
style: TextStyle(
fontFamily:
'PoppinsMedium',
color: list[index]['give'] - list[index]['take'] <
0
? Colors.green
: Colors.red),
),
],
),
),
),
),
)
: Container();
},
),
)
],
),
);
} else
return Center(
heightFactor: 1,
widthFactor: 1,
child: SizedBox(
height: 70,
width: 70,
child: CircularProgressIndicator(
strokeWidth: 2.5,
),
),
);
}),
),
),
I am damn sure its because futurebuilder keeps calling function which is returning data but because of keeps calling functions my Futurebuilder keeps showing loading.
You should not call setState inside the future that you are giving to the FutureBuilder.
The state actualization will cause the FutureBuilder to re-build. Meaning triggering the future again, and ... infinite loop !

change story items as dynamic widgets in flutter

I want to implement story items as different widgets. Like in this example:
In this picture, only images are changed, but I want to change as whole widgets as story items.
I have tried the story_view package. But, in this package, only images and videos can be added. Is there any other library for that?
As explained by https://stackoverflow.com/users/8164116/daksh-gargas, story view can be easily implemented using stack pageview and a simple gesture detector.
Made a simple story view -
import 'package:flutter/material.dart';
class CustomStoryView extends StatefulWidget{
#override
_CustomStoryViewState createState() => _CustomStoryViewState();
}
class _CustomStoryViewState extends State<CustomStoryView> with SingleTickerProviderStateMixin {
final List _colorsList = [Colors.blue, Colors.red, Colors.green, Colors.yellow, Colors.grey, Colors.brown];
final PageController _controller = PageController();
double _progressIndicators;
int _page = 0;
AnimationController _animationController;
bool dragEnded = true;
Size _pageSize;
#override
void initState() {
_animationController = AnimationController(vsync: this, duration: Duration(seconds: 2));
_animationController.addListener(animationListener);
_animationController.forward();
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
_pageSize = MediaQuery.of(context).size;
_progressIndicators = (_pageSize.width - 100) / 6;
});
super.initState();
}
#override
void dispose() {
_animationController?.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: [
PageView.builder(
controller: _controller,
physics: NeverScrollableScrollPhysics(),
itemBuilder: (context, index)=>GestureDetector(
onLongPressStart: _onLongPressStart,
onLongPressEnd: _onLongPressEnd,
onHorizontalDragEnd: _onHorizontalDragEnd,
onHorizontalDragStart: _onHorizontalDragStart,
onHorizontalDragUpdate: _onHorizontalDragUpdate,
onTapUp: _onTapDown,
child: Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
color: _colorsList[index],
child: Center(child: InkWell(
onTap: (){
print("thiswasclicked $index");
},
child: Text("Somee random text", style: TextStyle(fontSize: 36),)),),
),
),
itemCount: _colorsList.length,
),
Positioned(
top: 48,
left: 0,
right: 0,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: ([0,1,2,3,4,5].map((e) =>
(e == _page) ? Stack(
children: [
Container(
width: _progressIndicators,
height: 8 ,
color: Colors.black54,
),
AnimatedBuilder(
animation: _animationController,
builder: (ctx, widget){
return AnimatedContainer(
width: _progressIndicators * _animationController.value,
height: 8 ,
color: Colors.white,
duration: Duration(milliseconds: 100),
);
},
),
],
): Container(
width: _progressIndicators,
height: 8 ,
color: (_page >= e) ? Colors.white : Colors.black54,
)).toList()),
),)
],
),
);
}
animationListener(){
if(_animationController.value == 1){
_moveForward();
}
}
_moveBackward(){
if(_controller.page != 0){
setState(() {
_page = (_controller.page - 1).toInt();
_page = (_page < 0) ? 0 : _page;
_controller.animateToPage(_page, duration: Duration(milliseconds: 100), curve: Curves.easeIn);
_animationController.reset();
_animationController.forward();
});
}
}
_moveForward(){
if(_controller.page != (_colorsList.length - 1)){
setState(() {
_page = (_controller.page + 1).toInt();
_controller.animateToPage(_page, duration: Duration(milliseconds: 100), curve: Curves.easeIn);
_animationController.reset();
_animationController.forward();
});
}
}
_onTapDown(TapUpDetails details) {
var x = details.globalPosition.dx;
(x < _pageSize.width / 2) ? _moveBackward() : _moveForward();
}
_onHorizontalDragUpdate(d){
if (!dragEnded) {
dragEnded = true;
if (d.delta.dx < -5) {
_moveForward();
} else if (d.delta.dx > 5) {
_moveBackward();
}
}
}
_onHorizontalDragStart(d) {
dragEnded = false;
}
_onHorizontalDragEnd(d) {
dragEnded = true;
}
_onLongPressEnd(_){
_animationController.forward();
}
_onLongPressStart(_){
_animationController.stop();
}
}
This can be easily achieved with Stack, Container, and a GestureDetector to switch between pages/stories.
Why Stacks?
Flutter's Stack is useful if you want to overlap several
children in a simple way, for example, having some text and an image,
overlaid with a gradient and a button attached to the bottom.
To handle your "fixed" views, which are, in this case:
Top Progress bar... you can create your custom progress bar if you want.
That image and the user name...
Let's call them myTopFixedWidgets()
Row(children: [CircleAvatar(...),Column(children: [Text(...),Text(...)],)],)
Now, put your Widget that you want to display and that changes (your "story") as the first item of the Stacks and place the Widgets 1. and 2. (mentioned above) in the second item of the list.
Maintain a variable index to choose the widget that you want to display.
Stack(
children: <Widget>[
widgetsToShowAsAStory[index],
myTopFixedWidgets() //mentioned above
],
)
Wrap it inside GestureDetector
List<Widget> widgetsToShowAsAStory = [];
var index = 0;
....
GestureDetector(
onTap: () {
//If the tap is on the LEFT side of the screen then decrement the value of the index
index-= 1; //(check for negatives)
//If the tap is on the RIGHT side of the screen then increment the value of the index
index+= 1; //(check for the size of list)
//call
setState() {}
},
child: Stack(
children: <Widget>[
widgetsToShowAsAStory[index],
myTopFixedWidgets()
],
),)
and boom, you're good to go!
I found solutions from the story_view. But it doesnot match my requirement. We can only show different widgets as stories items in story_view.We can't perform any actions on widgets. To implement this story_view and to show different widgets as stories. Do like this.
First import story_view flutter dependencies from here.
Then import this in main.dart file.
import "package:story_view/story_view.dart";
StoryView(
controller: controller,
storyItems: [
StoryItem.inlineImage(
url:
"https://images.unsplash.com/photo-1536063211352-0b94219f6212?ixid=MXwxMjA3fDB8MHxzZWFyY2h8MXx8YmVhdXRpZnVsJTIwZ2lybHxlbnwwfHwwfA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60",
controller: controller,
),
StoryItem(
new Container(
margin: EdgeInsets.all(12),
child: StaggeredGridView.countBuilder(
crossAxisCount: 2,
crossAxisSpacing: 10,
mainAxisSpacing: 12,
itemCount: imageList.length,
itemBuilder: (context, index) {
return Container(
decoration: BoxDecoration(
color: Colors.transparent,
borderRadius: BorderRadius.all(
Radius.circular(15))),
child: ClipRRect(
borderRadius: BorderRadius.all(
Radius.circular(15)),
child: FadeInImage.memoryNetwork(
placeholder: kTransparentImage,
image: imageList[index],
fit: BoxFit.cover,
),
),
);
},
staggeredTileBuilder: (index) {
return StaggeredTile.count(
1, index.isEven ? 1.2 : 1.8);
}),
),
duration: aLongWeekend,
shown: true),
StoryItem(
new Container(
margin: EdgeInsets.all(12),
child: StaggeredGridView.countBuilder(
crossAxisCount: 2,
crossAxisSpacing: 10,
mainAxisSpacing: 12,
itemCount: imageList.length,
itemBuilder: (context, index) {
return Container(
decoration: BoxDecoration(
color: Colors.transparent,
borderRadius: BorderRadius.all(
Radius.circular(15))),
child: ClipRRect(
borderRadius: BorderRadius.all(
Radius.circular(15)),
child: FadeInImage.memoryNetwork(
placeholder: kTransparentImage,
image: imageList[index],
fit: BoxFit.cover,
),
),
);
},
staggeredTileBuilder: (index) {
return StaggeredTile.count(
1, index.isEven ? 1.2 : 1.8);
}),
),
duration: aLongWeekend,
shown: true),
],
onStoryShow: (s) {
print("Showing a story");
},
onComplete: () {
print("Completed a cycle");
},
progressPosition: ProgressPosition.top,
repeat: false,
inline: false,
),

How to spot different locations with colors on Map?

Let me tell you what my motive is. I am making an app in which the locations which are highly affected by COVID is displayed by red, orange, and green colors. They are actually containers which are circular in shape and of these three colors.
But, I am not getting the output as I have created this.
Please see the code:-
import 'package:flutter/material.dart';
import 'package:latlong/latlong.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
class MapIntegration extends StatefulWidget {
#override
_MapIntegrationState createState() => _MapIntegrationState();
}
class _MapIntegrationState extends State<MapIntegration> {
List redZoneData = new List();
List orangeZoneData = new List();
List greenZoneData = new List();
Map overallData = {
"Gujarat": LatLng(20.5937, 78.9629),
"Dehi": LatLng(20.5937, 78.9629)
};
int n = 2;
Map mapData;
var totalConfirmed;
var dataCalc;
var death;
var stateCode;
mapDataValue() async {
final url = 'https://api.rootnet.in/covid19-in/stats/latest';
final response = await http.get(url);
mapData = json.decode(response.body);
if (response.statusCode == 200) {
setState(() {
for (int index = 0;
index < mapData['data']['regional'].length;
index++) {
totalConfirmed = mapData['data']['regional'][index]['totalConfirmed'];
death = mapData['data']['regional'][index]['deaths'];
dataCalc = double.parse((totalConfirmed / death).toStringAsFixed(2));
stateCode = mapData['data']['regional'][index]['loc'];
if (dataCalc <= 40.00) {
redZoneData.add(stateCode);
} else {
// print(stateCode);
if (dataCalc > 40.00 && dataCalc <= 50.00) {
orangeZoneData.add(stateCode);
} else {
greenZoneData.add(stateCode);
}
}
}
print(redZoneData);
print(orangeZoneData);
print(greenZoneData);
});
} else {
throw Exception('loading failed...');
}
}
Widget dataEvaluation() {
var marker;
for (int index = 0; index < mapData['data']['regional'].length; index++) {
if (redZoneData.contains(mapData['data']['regional'][index]['loc'])) {
marker = new Marker(
width: 80.0,
height: 80.0,
point: new LatLng(20.5937, 78.9629),
builder: (ctx) => new Container(
height: 10,
width: 10,
decoration: new BoxDecoration(
shape: BoxShape.circle,
color: Colors.red,
),
),
);
} else if (orangeZoneData
.contains(mapData['data']['regional'][index]['loc'])) {
marker = new Marker(
width: 80.0,
height: 80.0,
point: new LatLng(20.5937, 78.9629),
builder: (ctx) => new Container(
height: 10,
width: 10,
decoration: new BoxDecoration(
shape: BoxShape.circle,
color: Colors.orange,
),
),
);
} else if (greenZoneData
.contains(mapData['data']['regional'][index]['loc'])) {
marker = new Marker(
width: 80.0,
height: 80.0,
point: new LatLng(20.5937, 78.9629),
builder: (ctx) => new Container(
height: 10,
width: 10,
decoration: new BoxDecoration(
shape: BoxShape.circle,
color: Colors.green,
),
),
);
}
}
return marker;
}
#override
void initState() {
mapDataValue();
super.initState();
}
#override
Widget build(BuildContext context) {
return Container(
height: MediaQuery.of(context).size.height / 1.3,
child: Column(
children: [
Container(
decoration: new BoxDecoration(
borderRadius: new BorderRadius.circular(30.0),
),
height: MediaQuery.of(context).size.height / 1.5,
alignment: Alignment.centerRight,
child: FlutterMap(
options: new MapOptions(
center: LatLng(22.5937, 78.9629),
zoom: 4.3,
),
layers: [
new TileLayerOptions(
urlTemplate:
'https://api.mapbox.com/styles/v1/shivam7007/ckevbwl2u6ty11an4bfbicex7/tiles/256/{z}/{x}/{y}#2x?access_token=pk.eyJ1Ijoic2hpdmFtNzAwNyIsImEiOiJja2VsMzRrcmcweW9vMnlwaXNiMzFrYjV2In0.CVRHP4CkMz_5UybuZ3CaIA',
additionalOptions: {
'acessToken':
'pk.eyJ1Ijoic2hpdmFtNzAwNyIsImEiOiJja2V0bXl4OXIxbmRrMnRvZWdkaWM5a29zIn0.doc-sYseA4b-Z7ylnp0Ttg',
'id': 'mapbox.mapbox-streets-v8',
},
),
new MarkerLayerOptions(
markers: [
dataEvaluation(),
],
),
],
),
),
Text('$dataCalc'),
],
),
);
}
}
And calling dataEvaluation() in MarkerLayerOption widget throws an error called "The element type 'Widget' can't be assigned to the list type 'Marker'."
Actually I have created a function calling dataEvaluation() which will calculate whether the STATE is present in the red, orange, or green zone, and according to that it will return the container based on the color red, orange, or gree, and that container will work as a spot on the map.
Please solve this, if you are finding any difficulty in understanding the question then please let me know. But please solve this. I am stuck finding nowhere.
API is = https://api.rootnet.in/covid19-in/stats/latest
I found this. It is easy as flutter provides you to write the single line code in the Widgets, so you can easily do the same.
for (var index in mapDataFinal)
if (redZoneData.contains(index))
new Marker(
width: 80.0,
height: 80.0,
point: new LatLng(26.8467, 80.9462),
builder: (ctx) => new Container(
height: 10,
width: 10,
decoration: new BoxDecoration(
shape: BoxShape.circle,
color: Colors.red,
),
),
)
Don't need to put curly braces over there.
Full Code is here:
new MarkerLayerOptions(markers: [
for (var index in mapDataFinal)
if (redZoneData.contains(index))
new Marker(
width: 80.0,
height: 80.0,
point: new LatLng(26.8467, 80.9462),
builder: (ctx) => new Container(
height: 10,
width: 10,
decoration: new BoxDecoration(
shape: BoxShape.circle,
color: Colors.red,
),
),
)
else if (orangeZoneData.contains(index))
new Marker(
width: 80.0,
height: 80.0,
point: new LatLng(10.8505, 76.2711),
builder: (ctx) => new Container(
height: 10,
width: 10,
decoration: new BoxDecoration(
shape: BoxShape.circle,
color: Colors.orange,
),
),
)
else if (greenZoneData.contains(index))
new Marker(
width: 80.0,
height: 80.0,
point: new LatLng(22.2587, 71.1924),
builder: (ctx) => new Container(
height: 10,
width: 10,
decoration: new BoxDecoration(
shape: BoxShape.circle,
color: Colors.green,
),
),
)
]),

GestureDetector not detecting inside of List.generate

I have the following streambuilder below. If I put the GestureDetector on the Row widget (as indicated below) it receives the gesture. However, when I put it as shown, it does not. My current theory is that it is due to the List.generation there, however, I guess it could be because there are other widgets above it? It's in a Stack widget...although, if that's the case, why would the GestureDetector work on the Row widget?)
return StreamBuilder<List<List<Event>>>(
stream: widget.controller.stream.map(_filter),
initialData: Provider.of<CalendarData>(context).dayEvents,
builder: (context, snapshot) {
return Row(
//GESTUREDETECTOR WORKS HERE
children: List.generate(8, (col) {
if (col == 0) {
return Expanded(
child: GestureDetector(
behavior: HitTestBehavior.translucent,
onTap: () {
print('tapped: beer'); //<-- col
},
onScaleStart: (scaleDetails) => setState(() {
print('previousNumOfDays:$previousNumOfDays');
print('numberOfDays:$numberOfDays');
// dayIndexScaleCenter = col;
print('dayIndexScaleCenter: $dayIndexScaleCenter');
previousNumOfDays = numberOfDays;
}),
onScaleUpdate: (ScaleUpdateDetails scaleDetails) {
setState(() {
int newNumberOfDays =
(previousNumOfDays / scaleDetails.scale).round();
print('previousNumOfDays:$previousNumOfDays');
print('numberOfDays:$numberOfDays');
print('newNumberOfDays:$newNumberOfDays');
if (newNumberOfDays <= 14 && newNumberOfDays > 1) {
numberOfDays = newNumberOfDays;
}
});
},
child: Column(
children: List.generate(
hours.length,
(row) => Container(
height: Provider.of<CalendarData>(context).rowHeight,
decoration: BoxDecoration(
color: ColorDefs.colorTimeBackground,
border: Border(
top: BorderSide(
width: 1.0,
color: ColorDefs.colorCalendarHeader),
),
),
child: Center(
child: AutoSizeText(hours[row],
maxLines: 1,
group: timeAutoGroup,
minFontSize: 5,
style: ColorDefs.textSubtitle2),
),
),
),
),
),
);
}