How to keep the current option in group button flutter - flutter

I was used group_button package from flutter to make user can select many options. After upgrading the library to version 5.0.0 or above, the selectedButtons property has been deprecated. I was save options of user by it but no I can't use it now. I was use it as:
GroupButton(
selectedButtons: setSelectedBtn(index),
isRadio: false,
spacing: 10,
onSelected: (i, isSelected) =>
onFilterSelect(index, i, isSelected),
buttons: widget.filters[index].value
.map((e) => e.value)
.toList())),
setSelectedBtn(index) {
List<int> result = [];
var valueSet = widget.filters[index].value;
bool isSelected = valueSet
.firstWhere((element) => element.isSelected,
orElse: () => CategoryFilterValues("", false))
.isSelected;
if (!isSelected) {
return result;
}
for (int index = 0; index < valueSet.length; index++) {
if (valueSet.elementAt(index).isSelected) {
result.add(index);
}
}
return result;
}
group_button
How I can save the options now in new version? Anyone can help me to do it.
thank you

Use GroupButtonController.
Controller have list of methods to interact with options.
selectIndex(int i) - Select button by index in radio type
unselectIndex(int i) - Unselect button by index in checkbox and radio type
... etc.
More docs and examples you can find here

Related

How to preselect checkbox in showQuickPick in vscode

I am using quickpick to display list of items and allowing user to do multiselect. I am using quickpick like this.
context.subscriptions.push(vscode.commands.registerCommand('command', async () => {
const list = await vscode.window.showQuickPick(filedsList, { ignoreFocusOut: true, canPickMany: true});
}));
I trying to make like if user previously selected some items in the quick pick and next time use opened this quick pick I want to preselect the previously selected values.
Is it feasible to do it in vscode extension development.
There are two options. In both cases you'll have to make QuickPickItems out of your AccurevOperations.cpkFieldsList as you cannot just pass strings as the first argument and use the pre-selection capability. It isn't difficult to do this, just loop through that AccurevOperations.cpkFieldsList array and create objects with the QuickPickItem properties you want, like:
const arr = ["1", "2", "3"];
// const quickPickItems = arr.map(item => ( { label: item, picked: true } ) ); // but this would select them all
const quickPickItems = arr.map(item => {
if (Number(item) % 2 != 0) return { label: item, picked: true };
else return { label: item }
});
So you would use your logic to set the items you want pre-selected to have the picked:true object property. Then
const options = { canPickMany: true };
const qp = vscode.window.showQuickPick(quickPickItems, options);
should show a QuickPick with your selected items.
The other option is to use the createQuickPick method instead, because with that you can use its selectedItems property. So starting with your array:
const arr = ["1", "2", "3"];
const quickPickItems = arr.map(item => ( { label: item } ) ); // and whatever other properties each item needs, perhaps nothing other than label
const qp = vscode.window.createQuickPick();
qp.canSelectMany = true;
qp.items = quickPickItems;
qp.selectedItems = [quickPickItems[0], quickPickItems[2]]; // your logic here
qp.show();
You will have to create an array of objects to assign to the selectedItems property. Perhaps by filtering the quickPickItems array (from above) for the labels you want pre-selected:
qp.selectedItems = quickPickItems.filter(item => {
return item.label === "1" || item.label === "3";
});
the object vscode::QuickPickItem has a property
picked
Optional flag indicating if this item is picked initially.

Multiple Select in DropdownButton in flutter

I know that there is many ways / package to implement multi select in dropdownbutton in flutter like --> this one
But with my little knowledge, I want to reinvent the wheel for basic building!!!
My scenario ->
I have a list of location's in json format like this -->
[{id: 928, location: Amtoli}, {id: 905, location: Ashok Tala}, {id: 899, location: Badur Tola}]
and two List -->
List _location = new List(); // this comes from API;
List _multiSelectLoc = new List();
And in DropDownButton's onChanged property -->
onChanged: (newValue) {
setState(() {
_location.forEach((e) {
if (e["id"] == newValue.toString()) {
_multiSelectLoc.add(e);
print(_multiSelectLoc);
}
});
_location.removeWhere(
(e) => e['id'] == newValue.toString());
print(_location);
});
},
I am curious to know why my code was not working, why I can't remove data from List _location, and and add to List _multiSelectLoc
I already simulated such condition in dartpad and it's just woking fine!
I guess I found the problem,
rewritten code -->
onChanged: (newValue) {
_location.forEach((e) {
if (e['id'].toString() == newValue.toString()) {
_multiSelectLoc.add(e);
// print(_multiSelectLoc);
}
});
_location.removeWhere(
(e) => e['id'].toString() == newValue.toString());
setState(() {
// print(_location);
});
},
I think the problem was, I was using a dynamic type to compare with string type, when I added .toString() the code started to giving me the results!

How to extend adding functionality of two objects in Dart?

I am using as a Latex renderer in my flutter project. I want to add a latex value to an existing Catex object. I have a List of Strings which hold latex values and a listview to display them in order. I want to add a list item to the Catex every time an OnTap method is called.
so far, + operator is not supported
The operator '+' isn't defined for the type 'CaTeX'.
CaTeX catex = r'\mu =: \sqrt{x}' as CaTeX;
int value = 0;
...
List<String> get data => [
r'\mu =: \sqrt{x}',
r'\eta = 7^\frac{4}{2}',
r'\epsilon = \frac 2 {3 + 2}',
r'x_{initial} = \frac {20x} {\frac{15}{3}}',
// ignore: no_adjacent_strings_in_list
r'\colorbox{red}{bunt} \boxed{ '
r'\rm{\sf{\bf{'
r'\textcolor{red} s \textcolor{pink} i \textcolor{purple}m '
r'\textcolor{blue}p \textcolor{cyan} l \textcolor{teal} e} '
r'\textcolor{lime}c \textcolor{yellow}l \textcolor{amber} u '
r'\textcolor{orange} b}}}',
r'\TeX',
r'\LaTeX',
r'\KaTeX',
r'\CaTeX',
'x_i=a^n',
r'\hat{y} = H y',
r'12^{\frac{\frac{2}{7}}{1}}',
r'\varepsilon = \frac{\frac{2}{1}}{3}',
r'\alpha\beta\gamma\delta',
// ignore: no_adjacent_strings_in_list
r'\colorbox{black}{\textcolor{white} {black} } \colorbox{white} '
r'{\textcolor{black} {white} }',
r'\alpha\ \beta\ \ \gamma\ \ \ \delta',
r'\epsilon = \frac{2}{3 + 2}',
r'\tt {type} \textcolor{teal}{\rm{\tt {writer} }}',
'l = a * t * e * x',
r'\rm\tt{sp a c i n\ \bf\it g}',
r'5 = 1 \cdot 5',
'{2 + 3}+{3 +4 }=12',
r'\backslash \leftarrow \uparrow \rightarrow \$',
r'42\uparrow 99\Uparrow\ \ 19\downarrow 1\Downarrow',
'5x = 25',
r'10\cdot10 = 100',
'a := 96',
];
...
changeListItems(int val) {
setState(() {
this.value = val;
if (this.value != 0) {
catex += data[this.value];
}
});
}
...
body: ListView.builder(
itemCount: this.value,
itemBuilder: (context, index) {
return Column(children: [catex]);
}),
...
onTap: (int index) {
index == 0
? this.value = this.value - 1
: this.value = this.value + 1;
changeListItems(this.value);
}
You can override the + operator for the Catex class with an extension:
extension Sum on Catex{
Catex operator +(Catex other) {
return Catex(this.input + other.input);
}
}
This is not very reliable since it depends on the input property of the Catex Package. Also, you are storing a constant Widget in your class which is also not recommended.
Widgets are meant to be created during the Build process so the Flutter framework can work on it properly.
The correct way to do it would be to have in your state a String which contains the input that will be passed to the Catex:
String catexInput = r'\mu =: \sqrt{x}';
[...]
catexInput += data[this.value];
[...]
return Catex(catexInput);
Edit:
If you want to have a Column with multiple Catex Widgets, you can do the same thing except that your state will need to contain a list of Strings:
List<String> catexInputs = [r'\mu =: \sqrt{x}'];
[...]
catexInput.add(data[this.value]);
[...]
return Column(children: [for (String input in catexInput) Catex(input)]);;

Dart Not understanding how forEach is supposed to work

I simply wanted to use forEach to set all values in a List to false, but I don't understand why it doesn't work. I created a filled list with fixed length like this:
List<bool> myList = List<bool>.filled(6, false);
Then I set one value to true:
setState(() => myList[3] = true);
Then I try to reset all values to false again, but as you can see from the print output it does not work:
setState(() {
myList.forEach((val) => val = false);
print(myList);
});
I/flutter (29049): [false, false, false, true, false, false]
You can check the answer why you can't update the values inside forEach here: List.forEach unable to modify element?
Dart does not have variable references, all elements are passed as a reference to an object, not to a variable. (In other words, Dart is purely "call-by-sharing" like both Java and JavaScript).
That means that the e parameter to the forEach callback is just a normal local variable, and assigning to it has no effect outside the callback. The same goes for iterators: they return the value in the iterable, but it has no reference back to the iterable after that.
You can do what you want using filled method like you used to create the list.
setState(() {
myList = List<bool>.filled(myList.length, false);
print(myList);
});
forEach element can not modify the actual element in the list. Assume this code:
var list = [false, true, false, false];
list.forEach((item) {
item = false;
});
print("List: $list");
The output is still:
List: [false, true, false, false]
So what you can do is using an indexed for:
for (int i=0; i < list.length; i++) {
list[i] = false;
}
Or map it and reassign it:
var list = [true, true, false];
list = list.map((item) {
return false;
}).toList();
You'll get:
List: [false, false, false, false]
As pointed out above, the forEach function does not give you write access to the list, it just provides you with the value. Changing the parameter of the forEach callback function has no effect outside of that function call, it's just changing a local variable.
To change the list, you must store to its element slots directly. Either:
for (int i = 0; i < list.length; i++) list[i] = false;
or
list.fillRange(0, list.length, false);
should do the job.

syncfusion ej chart redraw [n] undefined

I am using ASP MVC and I have a ej chart built in script, and I need to refresh its content:
my chart is built like this:
var modelSummaryList = getMySummaryModel();
var summaryChartDataManager = ej.DataManager(($scope.FirstLoad && IsCurrentUserDpiUser()) ? null : modelSummaryList);
jQuery("#MySummaryChart").ejChart({
range: { min: summaryChartDataManager == null ? -1 : summaryChartDataManager.ChartMin, max: summaryChartDataManager == null ? 1 : summaryChartDataManager.ChartMax },
series: [{
name: "MTM",
tooltip: {
visible: true,
format: "#point.x#: #point.y# #series.name#"
},
dataSource: summaryChartDataManager,
xName: "CtpyShort",
yName: "MTM"
}, {
name: "Threshold",
tooltip: {
visible: true,
format: "#point.x#: #point.y# #series.name#"
},
dataSource: summaryChartDataManager,
xName: "CtpyShort",
yName: "Threshold"
}, {
name: "My Held/(Posted)",
tooltip: {
visible: true,
format: "#point.x#: #point.y# #series.name#"
},
dataSource: summaryChartDataManager,
xName: "CtpyShort",
yName: "Held"
}],
type: 'column',
});
which is working good, but upon filter and change of data, I need to redraw the chart so I did this:
$scope.RefreshChart = function (data) {
var chart = $("#MySummaryChart").ejChart("instance");
chart.model.range.min = data.MyTradeSummaryVM.ChartMin;
chart.model.range.max = data.MyTradeSummaryVM.ChartMax;
for (var s = 0; s <= chart.model.series.length - 1; s++) {
var pts = IsCurrentUserDpiUser() ? $.grep(data.MyTradeSummaryVM, function (item) {
return item.ClientID == localStorage.getItem("MyPosting_client_sticky");
}) : data.MyTradeSummaryVM;
chart.model.series[s].points = [];
for (var p = 0; p <= pts.length - 1; p++) {
var newPt = new Object();
newPt.x = pts[p].CtpyShort;
if (chart.model.series[s].name == "MTM")
newPt.y = pts[p].MTM;
else if (chart.model.series[s].name == "Threshold")
newPt.y = pts[p].Threshold;
else if (chart.model.series[s].name == "My Held/(Posted)")
newPt.y = pts[p].Held;
newPt.visible = true;
chart.model.series[s].points.push(newPt);
}
}
chart.redraw();
};
which throws the error TypeError: n[0] is undefined on the chart.redraw() line, and I am stumped. Please note that the RefreshChart() works if I build the chart via cshtml and not javascript like this:
#(Html.EJ().Chart("MySummaryChart")
.PrimaryXAxis(pr => pr.Title(tl => tl.Text("")))
.PrimaryYAxis(pr => pr.Range(ra => ra.Max(Model.ChartMax).Min(Model.ChartMin)).Title(tl => tl.Text("")))
.CommonSeriesOptions(cr => cr.Type(SeriesType.Column).EnableAnimation(true).Marker(mr => mr.DataLabel(dt => dt.Visible(true).EnableContrastColor(true)))
.Tooltip(tt => tt.Visible(true).Format("#point.x# : #point.y# #series.name# ")))
.Series(sr =>
{
.
.
.
})
.Load("loadTheme")
.IsResponsive(true)
.Size(sz => sz.Height("400"))
.Legend(lg => { lg.Visible(true).Position(LegendPosition.Bottom); }))
but I am opting to use JS coz I need to handle null and firstload(meaning no data should appear on the chart upon first load, and unless user picks a client(filter), no data should be loaded. Which I cant seem to make it work if via html, I couldn't erase the chart xaxisregions label along with other data, the only things erased are the main Y axis points but not labels.
We have analyzed the reported scenario. We would like to you know that, when the data for chart is bind using dataSource, then while refreshing the chart with new data, you need to bind the data to series.dataSource property not to series.points, so that only chart will refresh properly. We have prepared a sample with respect the above scenario. Find the code snippet to achieve this requirement.
<input type="button" id="refreshChart" onclick="refresh()" value="Refresh Chart" />
function refresh(sender) {
var chart = $("#MySummaryChart").ejChart("instance");
for (var s = 0; s <= chart.model.series.length - 1; s++) {
//Obtained random data,
var pts = GetData().data;
var newPt = [];
for (var p = 0; p <= pts.length - 1; p++) {
if (chart.model.series[s].name == "MTM")
newPt.push({ "CtpyShort": pts[p].CtpyShort, "MTM": pts[p].MTM });
else if (chart.model.series[s].name == "Threshold")
newPt.push({ "CtpyShort": pts[p].CtpyShort, "Threshold": pts[p].Threshold });
else if (chart.model.series[s].name == "My Held/(Posted)")
newPt.push({ "CtpyShort": pts[p].CtpyShort, "Held": pts[p].Held });
}
//Assign the updated data to dataSource property
chart.model.series[s].dataSource = newPt;
}
chart.redraw();
}
In the above code in a button click event, we have refreshed the chart data. Here you need to assign the x value to CtpyShort and y values of three series to MTM, Threshold and Held, since we have mapped these properties while rendering the chart initially.
Screenshot before updating data:
Screenshot after updating data:
Sample for reference can be find from below link.
Sample Link
If you face still any concern, kindly revert us by modifying the above sample with respect to your scenario or provide your sample with replication steps which will helpful in further analysis and provide you the solution sooner.
Thanks,
Dharani.