Having issue while changing values in pie chart flutter - flutter

I tried this code and its working fine for the first time.
double a = 2, b = 3, c = 5;
var color;
Map<String, double> dataMap = Map();
List<Color> colorList = [
Colors.red,
Colors.green,
Colors.yellow,
];
void changeGraph() {
dataMap.putIfAbsent("Fat", () => c);
dataMap.putIfAbsent("Protein", () => b);
dataMap.putIfAbsent("Carbs", () => a);
}
void initState() {
super.initState();
changeGraph();
}
and
PieChart(
dataMap: dataMap,
animationDuration: Duration(milliseconds: 800),
chartLegendSpacing: 32.0,
chartRadius: MediaQuery.of(context).size.width / 2.7,
showChartValuesInPercentage: true,
showChartValues: true,
showChartValuesOutside: false,
chartValueBackgroundColor: Colors.grey[200],
colorList: colorList,
showLegends: true,
legendPosition: LegendPosition.right,
decimalPlaces: 1,
showChartValueLabel: true,
initialAngle: 0,
chartValueStyle: defaultChartValueStyle.copyWith(
color: Colors.blueGrey[900].withOpacity(0.9),
),
chartType: ChartType.disc,
)
then after getting values from user i tried this method for changing the graph
setState(() {
a = newA;
b = newB;
c = newC;
});
also i try to call changeGraph() method but the graph is not changing and its showing the value that it shows first time.
Is there any way to change the values ?

What your'e doing here is changing the values of the variables only and not the values inside the map.The map has the value of a = 2 and not a reference to a.
Meaning that when you say dataMap.putIfAbsent("Carbs", () => a); the value of "Carbs" is not a but it's actually 2 since the value here is an int and not a reference.
In order to change the value of Carbs in the map you need to directly change it from the map itself by doing for example datamap["Carbs"] = newA. Same goes to b and c
Let me know if that doesn't work

Related

how to write both values in value from rangeslider

I have several methods from API in my websockets, so i need to create the range slider which put value from sliders to Map. Now it works perfectly fine only with setting the max value not the min value. What should I change in my code to make min and max values works fine together? how can I write the values from the range slider to the value like it is in print alternately? The logic is this: the user moves the beginning of the slider and the value is written, then the user moves the end of the slider and the value from the end of the slider is also written. So can be done?
My API request:
Future<Map?> fetchGains(num values, num valueMax) async {
await hubConnection.start();
Map? gains;
num compensation = 1;
if (hubConnection.state == HubConnectionState.Connected) {
await hubConnection
.invoke('SetGainMax', args: <Object>[valueMax])
.then((value1) => compensation = valueMax)
.then((value2) => hubConnection
.invoke('GetGainMax')
.then((value3) => gains = value3 as Map))
.then((value) => hubConnection
.invoke('SetGain', args: [values])
.then((value) => compensation = values)
.then((value) => hubConnection
.invoke('GetGain')
.then((value) => gains = value as Map?)));
}
hubConnection.onclose(({error}) {
throw Exception(error);
});
print(gains!['min']);
print(gains);
return gains;
}
}
My range sliders where I want to manipulate with min and max value:
var _currentRangeValues = const RangeValues(1, 16);
#override
Widget build(BuildContext context) {
return FutureBuilder<Map?>(
future: GetGainsForCameras().fetchGains(
GetGainsForCameras().fetchGains(
_currentRangeValues.start.round().toInt(),
_currentRangeValues.end.round().toInt()),
builder: (context, snapshot) {
SizedBox(
child: RangeSlider(
values: _currentRangeValues,
activeColor: Colors.green,
min: 1,
max: 16,
inactiveColor: Colors.green,
onChanged: (RangeValues value) {
setState(() {
_currentRangeValues = value;
});
},
),
)
]);
},
}
Now I can set onle max value not the min value and this I get in print {min: 1, max: 16, value: 10.0, step: 1.0}
May thanks to everyone in answer section who noticed my mistake.
Is is going to work as I want or backend devs should make some changes?
your are calling .end for both min and max
_currentRangeValues.end.round().toInt(),
_currentRangeValues.end.round().toInt()
range has both start and end constructors. so
_currentRangeValues.start.round().toInt(),
_currentRangeValues.end.round().toInt()
You're not using _currentRangeValues.start which is the min value of the slider. Probably your fetchGains call should include that.

Cannot clear map marker with Animarker Solve : The method 'clearMarkers' isn't defined for the type 'Completer'?

Hello i'am using Animarker package (https://pub.dev/packages/flutter_animarker) and I cannot clear map markers using it, it is a big problem .
I end up with marker adding each time, carousel list is scrolled, by the user instead of only showing marker one by one.
I have to set the controller like this :
late final Completer<GoogleMapController> _mapController = Completer();
in order to use futur in mapId required Animaker element
Animarker(
mapId: _mapController.future.then<int>((value) => value.mapId),
rippleRadius: 0.6, //[0,1.0] range, how big is the circle
rippleColor: Colors.grey, // Color of fade ripple circle
rippleDuration: Duration(milliseconds: 2500),
markers:_storeMarkers.toSet(),
runExpressAfter: 1,
I have tried solution from this but without success Remove marker in google_maps_flutter
My call is that when this function is called it is clearing the map and then add the new marker
void _carouselCallback(Product product) {
var fe= product.store?.id;
// _mapController.clearMarkers();
//_storeMarkers.remove(_storeMarkers.firstWhere((Marker marker) => marker.markerId.value == '3'));
_storeMarkers.clear();
final marker= RippleMarker(
markerId: MarkerId('${product.store?.id}'),
alpha: 1,
icon: _storePin ?? BitmapDescriptor.defaultMarker,
position: LatLng(product.store?.lat ?? 0, product.store?.long ?? 0),
ripple: false,
onTap: () {
if (product.store != null) {
_carouselModePinCallback(product.store);
}
},
);
_storeMarkers.add(marker);
_moveToStore(product.store);
setState(() {});
}
_storeMarker is a Set
Could someone help ? Thank you
Try to use this:
markers[myMarkerId] = Marker(markerId: myMarkerId, visible: false);
and the problem will be solved.

Slider becomes laggy once there are divisions

This is how a Slider's animation normally looks like:
This is how a Slider looks when I try to add the value label:
This is the sample code:
Slider(
value: sliderValue,
activeColor: color,
min: 0.0,
max: 100.0,
divisions: 2000, //TO COMMENT
label: sliderValue.toStringAsFixed(2), //TO COMMENT
onChanged: (value) {
setState(() {
sliderValue = value;
});
}),
In this code, if I comment out the marked //TO COMMENT lines which are the divisions and label properties, the `label goes away as expected, and the animation is smooth again.
I assume this is due to divisions, and any amount of it, even just 100 does not change the lag in any way.
Additionally, it seems that the label property does not work on its own.
It needs the divisions property to also be set so that the value
label can be displayed.
What is the workaround so that I can achieve a Slider with the smoothness shown in the first image, but have the default value label or what looks the same?
If you take a look on source code, you can find _positionAnimationDuration which is responsible to animate the slider
Change it to
static const Duration _positionAnimationDuration = Duration.zero;
Changing on source-code will affect on others project, instead create a local dart file, paste the full slider code and make changes.
Let say we have created customSlider.dart file
. Make sure to replace some(./xyz.dart) top imports with import 'package:flutter/cupertino.dart'; or material on our customSlider.dart.
Then replace _positionAnimationDuration.
To use this, import the file
import 'customSlider.dart' as my_slider;
...
//use case
my_slider.Slider(....)
// create class
// .yaml > another_xlider: ^1.0.0
import 'package:another_xlider/another_xlider.dart';
import '../res/res_controller.dart';
import '../utils/utils_controller.dart';
import 'package:flutter/material.dart';
class RangeBar extends StatelessWidget {
final List<double>? values;
final double? min;
final double? max;
final Function(int, dynamic, dynamic)? onDragging;
const RangeBar(
{Key? key,
#required this.values,
#required this.onDragging,
#required this.min,
#required this.max})
: super(key: key);
#override
Widget build(BuildContext context) {
return FlutterSlider(
values: values!,
// pre set values
rangeSlider: true,
handlerAnimation: FlutterSliderHandlerAnimation(
curve: Curves.elasticOut,
reverseCurve: Curves.bounceIn,
duration: Duration(milliseconds: 500),
scale: 1.5),
jump: true,
min: min ?? 0,
max: max ?? 0,
touchSize: Sizes.s13,
trackBar: FlutterSliderTrackBar(
activeTrackBar: BoxDecoration(color: AppColors.orange),
),
tooltip: FlutterSliderTooltip(
boxStyle: FlutterSliderTooltipBox(
decoration: BoxDecoration(
color: Colors.greenAccent,
borderRadius: BorderRadius.all(Radius.circular(Sizes.s5)),
border: Border.all(
color: AppColors.steelGray,
),
),
),
positionOffset: FlutterSliderTooltipPositionOffset(top: -Sizes.s15),
alwaysShowTooltip: true,
textStyle:
TextStyles.defaultRegular.copyWith(fontSize: FontSizes.s11),
),
onDragging: onDragging);
}
}
// try to call
Container(
child: _size(),
)
Widget _size() {
{
double sizeMin;
double sizeMax;
sizeMin = 0;
sizeMax = 0;
sizeMax = sizeMin.round() == sizeMax.round() ? sizeMax + 1 : sizeMax;
return RangeBar(
values: [
// add values
],
min: sizeMin,
max: sizeMax.ceilToDouble(),
onDragging: (p0, lowerValue, upperValue) {
log(lowerValue);
log(upperValue);
},
);
return C0();
}
}

Getx fetch changes of variables

I have a getx Controller. In it i have declared two variables, which will be updated
var percentageEVS = 0.obs;
var percentOthers =0.obs;
Im trying to change the values of these variables using the following function
calculatespentTime(){
final totalDuration = dashboard[0].duration??0;
final durationEVS = dashboard[1].duration!.toInt();
final _percentageEVS = (durationEVS/totalDuration)*100;
percentageEVS.value = _percentageEVS.toInt() ;
}
How ever I'm not getting the changed values
final List<ChartData> chartData = [
ChartData(x: 'Maths', y:_controller.percentageEVS.value.toDouble(), color: Colors.red),
ChartData(x: 'English', y: 38, color: Colors.blue),
]
How can i get the changed value and pass it to chartData??
Change the line
ChartData(x: 'Maths', y:_controller.percentageEVS.value.toDouble(), color: Colors.red)
to
Obx(()=>ChartData(x: 'Maths', y:_controller.percentageEVS.value.toDouble(), color: Colors.red))

InitialValue isn't working properly in Multi-Select package Flutter

so I am using MultiSelectBottomSheetField in this package. I posted on their github as well as an issue but it seems fairly inactive so i came here looking for help.
And I am having some issues with the initialValue parameter for it. So at the moment, I have data saved in firestore as a string but its in the format of a list. And what i was trying to do was get the string data from firestore -> convert to a list with the respective class -> and then show as initial value in the above package/widget. But whats happening is that the initial value isnt showing, even though the value is not empty.
So for context this is how I change to list from firestore string:
List<Skill?> skillList = [];
void changeSkillToList(String? stringList) {
int indexOfOpenBracket = stringList!.indexOf("[");
int indexOfLastBracket = stringList.lastIndexOf("]");
var noBracketString =
stringList.substring(indexOfOpenBracket + 1, indexOfLastBracket);
var list = noBracketString.split(", ");
for (var i = 0; i < list.length; i++) {
skillList.add(Skill(id: 1, name: list[i].toString()));
}
}
this is how i use the acc widget:
final _skillItems =
skill.map((skill) => MultiSelectItem<Skill>(skill, skill.name)).toList();
MultiSelectBottomSheetField<Skill?>(
selectedColor: Color(0xFF5DB075),
selectedItemsTextStyle:
TextStyle(color: Colors.white),
initialChildSize: 0.4,
decoration: BoxDecoration(),
listType: MultiSelectListType.CHIP,
initialValue: skillList,
searchable: true,
items: _skillItems,
buttonText: Text("Select your skills...",
style: GoogleFonts.inter(
color: Color(0xFFBDBDBD),
fontSize: 16)),
onConfirm: (values) {
context
.read(pharmacistSignUpProvider.notifier)
.changeSkillList(values);
},
chipDisplay: MultiSelectChipDisplay(
items: context
.read(pharmacistSignUpProvider.notifier)
.skillList
?.map((e) =>
MultiSelectItem(e, e.toString()))
.toList(),
chipColor: Color(0xFF5DB075),
onTap: (value) {
context
.read(
pharmacistSignUpProvider.notifier)
.skillList
?.remove(value);
return context
.read(
pharmacistSignUpProvider.notifier)
.skillList;
},
textStyle: TextStyle(color: Colors.white),
),
),
And this is my initState:
List<Skill?> skillList = [];
#override
void initState() {
skillList = changeSkillToList(context
.read(pharmacistMainProvider.notifier)
.userDataMap?["knownSkills"]);
print(skillList);
super.initState();
}
If someone could help me out, it would be very appreciated. Let me know if you guys have any questions
Thanks!!
I get some problem and I fix it by adding the == operator to my entity in your case skill
#override
bool operator ==(Object other) {
return other is Skill && this.id == other.id;
}
inside your Skill class