I have a list of Strings (called namesList). For each String inside the list I want to create a button with one of the names.
As you can see in the code below, I have tried to make use of the for loop. However, when playing the code I can only see the first Button with the text "Anna".
import 'package:flutter/material.dart';
class ButtonsWithName extends StatefulWidget{
#override
State<StatefulWidget> createState() {
// TODO: implement createState
return _ButtonsWithNameState();
}
}
class _ButtonsWithNameState extends State<ButtonsWithName> {
String name1;
String name2;
String name3;
String name4;
String name5;
var namesList = new List<String>();
#override
void initState() {
name1 = 'Anna';
name2 = 'Bernd';
name3 = 'Christina';
name4 = 'David';
name5 = 'Elena',
namesList.add(name1);
namesList.add(name2);
namesList.add(name3);
namesList.add(name4);
namesList.add(name5);
super.initState();
}
Widget _buildButtonsWithNames() {
for(int i=0; i < namesList.length; i++){
RaisedButton(child: Text(answerList[0]));
}
return RaisedButton[i];
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Wrap(children: <Widget>[
_buildButtonsWithNames();
]);
)
}
}
I expect to have 5 RaisedButtons in the end with the texts of the String-list, namely a button with the text "Anna", a button with the text "Bernd", and so and so forth.
I would really I appreciate anyone's help on this matter!
The result you got is normal, because your _buildButtonsWithNames() list return just one button, instead of list of buttons. So the solution is to create this list, fill it and then return it. See below how it should be:
import 'package:flutter/material.dart';
class ButtonsWithName extends StatefulWidget {
#override
State<StatefulWidget> createState() {
// TODO: implement createState
return _ButtonsWithNameState();
}
}
class _ButtonsWithNameState extends State<ButtonsWithName> {
String name1;
String name2;
String name3;
String name4;
String name5;
var namesList = new List<String>();
List<RaisedButton> buttonsList = new List<RaisedButton>();
#override
void initState() {
super.initState();
name1 = 'Anna';
name2 = 'Bernd';
name3 = 'Christina';
name4 = 'David';
name5 = 'Elena';
namesList.add(name1);
namesList.add(name2);
namesList.add(name3);
namesList.add(name4);
namesList.add(name5);
}
List<Widget> _buildButtonsWithNames() {
for (int i = 0; i < namesList.length; i++) {
buttonsList
.add(new RaisedButton(onPressed: null, child: Text(namesList[i])));
}
return buttonsList;
}
#override
Widget build(BuildContext context) {
return Scaffold(body: Wrap(children: _buildButtonsWithNames()));
}
}
This works for me, thanks to previous answer with some improvements:
import 'package:flutter/material.dart';
import 'package:audioplayers/audio_cache.dart';
void main() => runApp(XylophoneApp());
class XylophoneApp extends StatelessWidget {
final player = AudioCache();
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SafeArea(
child: Container(
child: PlaySoundButtons()
),
),
),
);
}
}
class PlaySoundButtons extends StatefulWidget {
#override
_PlaySoundButtonsState createState() => _PlaySoundButtonsState();
}
class _PlaySoundButtonsState extends State<PlaySoundButtons> {
List<String> soundNames = [
'note1.wav',
'note2.wav',
'note3.wav',
'note4.wav',
'note5.wav',
'note6.wav',
'note7.wav',
];
List<FlatButton> buttonsList = [];
final player = AudioCache();
#override
void initState() {
super.initState();
for (int i = 0; i < soundNames.length; i++) {
buttonsList.add(new FlatButton(onPressed: () {
player.play(soundNames[i]);
}, child: Text(soundNames[i])));
}
}
#override
Widget build(BuildContext context) {
return Wrap(children: buttonsList);
}
}
I have a method to skip to the next list item, which works fine, but the method to display the previous list item doesn't seem to re-render.
When I print to console, the list item index it goes down by 1, but the text widget doesn't update like it does when it increases by 1.
I have shown the 2x methods below and an excerpt from the build. Help! :)
void _skipFlashcard () {
setState(() {
int currentIndex = allFlashcards.indexOf(widget.flashcardToShow);
var nextFlashcard = allFlashcards[currentIndex + 1];
widget.flashcardToShow = nextFlashcard;
print(widget.flashcardToShow.flashcardId);
});
}
void _previousFlashcard () {
int currentIndex = allFlashcards.indexOf(widget.flashcardToShow);
var previousFlashcard = allFlashcards[currentIndex - 1];
widget.flashcardToShow = previousFlashcard;
print(widget.flashcardToShow.flashcardId);
}
-------------------------
Container(
child: Row(
children: <Widget>[
Text(widget.flashcardToShow.flashcardId.toString()),
Wrap your code in setState, that's all that is missed :-)
void _previousFlashcard () {
setState() {
int currentIndex = allFlashcards.indexOf(widget.flashcardToShow);
var previousFlashcard = allFlashcards[currentIndex - 1];
widget.flashcardToShow = previousFlashcard;
print(widget.flashcardToShow.flashcardId);
}
}
I have Firebase info I'm getting back that includes an int property value. I've successfully stored them as a class. Now I would like to make that Class a Map or a List and then sort them descending according to my int Value and create Lists of each property to populate elements later. Here is my code...
class Top {
String videoId;
int rank;
String title;
String imageString;
Top({this.videoId, this.rank, this.title, this.imageString});
}
List<Top> videos = new List();
List onesRank = new List();
List onesIds = new List();
for (var items in titles) {
var top = new Top(videoId: items['vidId'], rank: items['Value'],
title: items['vidTitle'], imageString: items['vidImage']);
onesRank.add(top.rank);
onesIds.add(top.videoId);
}
print(onesRank);
print(onesIds);
Printing print(top.rank) successfully logs my int values and print(onesIds) logs my ids correctly like so...
[10, 6, 14, 12, 11, 5, 10, 1]
[4408NthSJis, 7n5ieHnu90w, XuSYtAsMxfY, 9bZkp7q19f0, sGRv8ZBLuW0, 2ips2mM7Zqw, 0Pinupmqwaw, m8MfJg68oCs]
But I would like to arrange all top properties in descending element order as top.rank like so...
[14, 12, 11, 10, 10, 6, 5, 1]
[XuSYtAsMxfY,9bZkp7q19f0,sGRv8ZBLuW0,4408NthSJis,0Pinupmqwaw,7n5ieHnu90w,
2ips2mM7Zqw,m8MfJg68oCs]
I accomplished this in Swift like so...
for items in snapshot.value as! NSDictionary
{
let ids = items.value["vidId"] as! String
let value = items.value["Value"] as! Int
let pics = items.value["vidImage"] as! NSString
let title = items.value["vidTitle"] as! String
let top = Top(videoID: ids, value: value, title: title, imageString: pics as String)
videos.append(top)
}
videos.sort { $0.value > $1.value }
self.topTitle = videos.map { $0.title }
self.topID = videos.map { $0.videoID }
self.topImage = videos.map { $0.imageString }
self.vidRank = videos.map { $0.value }
I still don't really understand what you try to accomplish.
If you have a list of Top you can do
List<Top> videos = new List();
// fill list
videos..sort((a, b) => a.id.compareTo(b.id));
print(videos);
I'm working with Chart.js and I'm wondering if there's a way when you click on part of a pie chart, it filters the bar chart.
Since this is a Chart.js question :-), this is how you do it Chart.js (and it's not too complex either)
Setting up the Pie Chart
// pie
var data = [
{
value: 300,
color: "#F7464A",
highlight: "#FF5A5E",
label: "Red",
subData: [28, 48, 40, 19, 86, 27, 190]
}, {
value: 50,
color: "#46BFBD",
highlight: "#5AD3D1",
label: "Green",
subData: [90, 28, 48, 40, 19, 86, 127]
}, {
value: 100,
color: "#FDB45C",
highlight: "#FFC870",
label: "Yellow",
subData: [28, 48, 40, 19, 86, 27, 190]
}
]
var canvas = document.getElementById("chart");
var ctx = canvas.getContext("2d");
var myPieChart = new Chart(ctx).Pie(data);
Setting up the Bar Chart using Pie Data
// bar using pie's sub data
var bardata = {
labels: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
datasets: [
{
label: "My Second dataset",
fillColor: "rgba(151,187,205,0.5)",
strokeColor: "rgba(151,187,205,0.8)",
highlightFill: "rgba(151,187,205,0.75)",
highlightStroke: "rgba(151,187,205,1)",
data: data[0].subData.map(function (point, i) {
var pointTotal = 0;
data.forEach(function (point) {
pointTotal += point.subData[i]
})
return pointTotal;
})
}
]
};
var subcanvas = document.getElementById("subchart")
var subctx = subcanvas.getContext("2d");
var myBarChart = new Chart(subctx).Bar(bardata);
Updating Bar data when Clicking Pie
// connect them both
canvas.onclick = function (evt) {
var activeSector = myPieChart.getSegmentsAtEvent(evt);
myBarChart.datasets[0].bars.forEach(function (bar, i) {
var pointTotal = 0;
data.forEach(function (point, j) {
if (activeSector.length === 0 || point.label === activeSector[0].label)
pointTotal += data[j].subData[i]
})
bar.value = pointTotal;
});
myBarChart.update();
};
Clicking outside the pie (but in the pie chart's canvas) resets the bar chart.
Fiddle - http://jsfiddle.net/0zwkjv8a/
Other answers posted already cover what I would generally advise here which is to use dc-js if you want crossfilter enabled charts out of the gate. I would have commented on this answer, but I don't have enough reputation so I'm posting this as option 'c.)' where 'a.)' is using dc-js and 'b.)' is making some modifications to an existing Chart.js chart.
Option 'c.)' is to extend the Chart.js chart type and make the child chart work like a dc-js chart. Chart.js chart types follow an inheritance hierarchy, so if you like a chart that already exists you can wrap its prototype methods with some of your own. Additionally important to this option, in the selected answer to the stack overflow question with heading 'dc.js - Listening for chart group render', it is described how the current implementation of dc-js's chartRegistry object is fairly decoupled from d3 or dc internals, so any chart implementing chartRegistry's interface can be part of a chartGroup.
I was in the position of wanting very much to use Polar Area Charts in a dataset where I was already using a chart group full of dc-js charts to crossfilter the data. I wrote an extension for Polar Area charts that could serve as an example of one way (I'm going to go ahead and say probably not the best way) to extend a chart type with dc-js like behaviors. The repo for this is at https://github.com/nsubordin81/Chart.dc.js, Licensed under an MIT License, and in case that ever goes anywhere, all of the code is copied into the example fiddle: http://jsfiddle.net/nsubordin81/3w725o3c/1/
Chart.dc.js v. 0.1.0
MIT Licensed: opensource.org/licenses/MIT
Copyright (c) 2015 Taylor Bird
(function () {
"use strict";
var root = this,
Chart = root.Chart,
dc = root.dc,
helpers = Chart.helpers,
//class for data structure that manages filters as they relate to chart segments. This should probably be generalized to chart elements of all kinds.
FilterManager = function (segmentList) {
//private member variable
var filterMap = [];
//constructor
//accepts a list of SegmentArcs that have had the extra properties added to them
for (var i = 0; i < segmentList.length; i++) {
add(segmentList[i].segmentID);
}
//private methods
function testOnAll(test) {
var testResult = true;
for (var i = 0; i < filterMap.length; i++) {
//one failure of test means testOnAll fails
if (!test(filterMap[i])) {
testResult = false;
}
}
return testResult;
}
//add a filter, pretty much just a wrapper for push
function add(segmentID) {
filterMap.push({
"segmentID": segmentID,
"active": false
});
}
//remove a filter by id, returns removed filter
function remove(segmentID) {
var removed = filterMap.find(segmentID);
filterMap = filterMap.filter(function (elem) {
return elem.segmentID !== segmentID;
});
return removed;
}
//return this segment if it is filtered
function find(segmentID) {
for (var i = 0; i < filterMap.length; i++) {
if (filterMap[i].segmentID === segmentID) {
return filterMap[i];
}
}
return -1;
}
//public methods
return {
//tell me if the filter for this segment is active
isActive: function (segmentID) {
var filter = find(segmentID);
if (filter === -1) {
console.error("something went wrong, the filter for this segment does not exist");
}
return filter.active;
},
//for the given segment, activate or deactivate its filter. return whether the filter is on or off.
flip: function (segmentID) {
var filter = find(segmentID);
if (filter === -1) {
console.error("something went wrong, the filter for this segment does not exist");
}
filter.active ? filter.active = false : filter.active = true;
return filter.active;
},
//if all filters are on, we want to be able to quickly deactivate them all
turnAllOff: function () {
for (var i = 0; i < filterMap.length; i++) {
filterMap[i].active = false;
}
},
//tell me if all of the filters are off
allOff: function () {
return testOnAll(function (elem) {
return !elem.active;
});
},
//tell me if all the filters are on
allOn: function () {
return testOnAll(function (elem) {
return elem.active;
});
}
}
};
//utility function, Takes an array that has some property as its key
//and forms a javascript object with the keys as properties so we can get O(1) access
function createKeyMap(arr, propName) {
var keyMap = {}
for (var i = 0; i < arr.length; i++) {
keyMap[arr[i][propName]] = arr[i];
}
return keyMap;
}
Chart.types.PolarArea.extend({
name: "PolarAreaXF",
//this will have to be a member
dimension: undefined,
colorTypes: {
"NORMAL": 0,
"HIGHLIGHT": 1,
"FILTER": 2,
"FILTER_HIGHLIGHT": 3
},
chartGroup: undefined,
filters: undefined,
originalDataKeys: undefined,
initialize: function (data) {
//--PRE--
var that = this;
//Polar Area initialize method is expecting (data, options) in arguments,
//but we pass in an array of components to merge. Let's clean this up.
var argsArray = Array.prototype.slice.call(arguments);
//remove the first element of arguments which is our array, then we do a bunch of Chartjs converison on it . . .
argsArray.splice(0, 1);
//TODO - check if data is an array, if not, put a message in a console explaining how you are supposed to send data in an array
this.dimension = data.dimension;
data.chartGroup ? this.chartGroup = data.chartGroup : this.chartGroup = 0;
//short but magical line. Now we are linked with all dc charts in this group!
dc.registerChart(this, this.chartGroup);
var data = this.setupChartData(data.colors, data.highlights, data.labels);
//... and push the result in its place.
argsArray.unshift(data);
//originalDataArray -- this is used as a reference to the original state of the chart, since segments can come and go,
//we use this to track what a segment's original colors were when adding it back in. This would mess up adding a truly new segment, but who
//is gonna do that? Assumption here is dimensions start with so many groups and that is it.
this.originalDataKeys = createKeyMap(data, "key");
//parent's initialize
Chart.types.PolarArea.prototype.initialize.apply(this, argsArray);
//--modify SegmentArcs--
//assign colors and ids to all existing segment arcs
var mySegments = this.segments;
for (var i = 0; i < mySegments.length; i++) {
mySegments[i].colorList = [undefined, undefined, "#777", "#aaa"];
mySegments[i].colorList[this.colorTypes.NORMAL] = mySegments[i].fillColor;
mySegments[i].colorList[this.colorTypes.HIGHLIGHT] = mySegments[i].highlight;
mySegments[i].segmentID = i;
mySegments[i].key = data[i].key;
}
//add methods to SegmentArc objects that will color them one way or the other depending on their filter
this.SegmentArc.prototype.setIncluded = function (include) {
if (include) {
this.fillColor = this.colorList[that.colorTypes.NORMAL];
this.highlight = this.colorList[that.colorTypes.HIGHLIGHT];
} else {
this.fillColor = this.colorList[that.colorTypes.FILTER];
this.highlight = this.colorList[that.colorTypes.FILTER_HIGHLIGHT];
}
}
//--initialize filters--
this.filters = new FilterManager(this.segments);
//handle clicks on segments as filter events, do the styling and crossfilter changes at the Chart level in the filter method.
helpers.bindEvents(this, ["mousedown"], function (evt) {
var activeSegment = Chart.types.PolarArea.prototype.getSegmentsAtEvent.apply(this, [evt])[0];
this.handleFilter(activeSegment);
});
},
//convert crossfilter dimension into chart.js Polar Area data object array
setupChartData: function (colors, highlights, labels) {
var chartJSible = [];
//probably need checks here to make sure client actually passed in a crossfilter dimension
var grouped = this.dimension.group().reduceCount().top(Infinity);
//probably need checks here to either fail if the arrays aren't all long enough or have some way to add random colors/highlights if they are shorter.
for (var i = 0; i < grouped.length; i++) {
var dataObject = {
value: grouped[i].value,
key: grouped[i].key,
color: colors[i],
highlight: highlights[i],
label: labels ? (labels[i] ? labels[i] : grouped[i].key) : grouped[i].key
};
chartJSible.push(dataObject);
}
return chartJSible;
},
//figure out what changed between Chart.js' internally maintained data object array and crossfilter's dimension data. use the saved information
//about what colors and highlight a key has to rebuild the segmentArc list 'segments'. can't trash the old, it might mess up the animations.
redraw: function () {
var grouped = this.dimension.group().reduceCount().top(Infinity);
var currentSegmentKeys = createKeyMap(this.segments, "key");
var crossfilterGroupKeys = createKeyMap(grouped, "key");
//loop through the segment list, if the segment for a group is already there, update the value, if it is not there, add it back using the
//original data as a guide for what it's color and highlight color should be. if there are segments in the existing list
var length = Math.max(this.segments.length, grouped.length);
//going through both lists, whichever is longer
for (var i = 0; i < length; i++) {
var sList = this.segments;
var gList = grouped;
//only do this part if we still have items in the new filtered list
if (gList[i]) {
//we already have a segment for this crossfilter group, just get that segment and update its value
if (currentSegmentKeys[gList[i].key]) {
currentSegmentKeys[gList[i].key].value = gList[i].value;
} else {
//the chart doesn't have the crossfilter group item, add a new segment with the right colors and values from original data
var theSegment = this.originalDataKeys[gList[i].key];
this.addData(theSegment, 0, true);
}
}
//only do this part if we still have items in the current chart segment list
if (sList[i]) {
//we don't have this segment in the new crossfilter group, remove it from the chart
if (!crossfilterGroupKeys[sList[i].key]) {
this.removeData(i);
}
}
}
this.update();
},
filterAll: function () {
this.dimension.filterAll();
this.filters.turnAllOff();
this.colorMeIn();
this.redraw();
},
handleFilter: function (clicked) {
//after we have all of the filters figured out, change the colors to reflect what they should be and update the chart
this.filters.flip(clicked.segmentID);
this.colorMeIn();
if (this.filters.allOn()) {
this.dimension = this.dimension.filterAll();
dc.redrawAll(this.chartGroup);
this.filters.turnAllOff();
}
dc.redrawAll(this.chartGroup);
},
colorMeIn() {
var activeFilters = [];
var segments = this.segments;
for (var i = 0; i < segments.length; i++) {
var segment = segments[i];
if (this.filters.isActive(segment.segmentID) || this.filters.allOff()) {
segment.setIncluded(true);
activeFilters.push(segment.key);
} else {
segment.setIncluded(false);
}
}
this.dimension = this.dimension.filterFunction(function (d) {
for (var i = 0; i < activeFilters.length; i++) {
if (d === activeFilters[i]) {
return true;
}
}
return false;
});
}
})
}).call(this);
Use dc.js: https://dc-js.github.io/dc.js/
It has exactly the functionality asked for.
in order to get familiar with dojo I'm working on a test project which consists of the following components:
data grid (created declaratively), filled with JSON data; clicking on a line will open a dialog containing a form (works)
form (created from template), with several input fields, filled with data from the grid store (works)
FilteringSelect (part of form) (doesn't work, no content)
The FilteringSelect contains dynamic data. In order to keep data traffic low, I thought it wise to get this data when the whole page is loaded and to pass it into the template initialization function.
In fact, I don't really know how to assign the store to the FilteringSelect.
Any help would be greatly appreciated.
Here's my code. I shorten it to the what I consider relevant parts so that it's easier to understand.
Grid Part:
var data_list = fetchPaymentProposalList.fetch();
/*create a new grid*/
var grid = new DataGrid({
id: 'grid',
store: store,
structure: layout
});
// store for FilteringSelect
var beneficiaryList = FetchBeneficiaryList.fetch();
var beneficiaryListStore = new Memory({
identifier : "id",
data : beneficiaryList
});
return {
// function to create dialog with form
instantiate:
function(idAppendTo) {
/*append the new grid to the div*/
grid.placeAt(idAppendTo);
/*Call startup() to render the grid*/
grid.startup();
grid.resize();
dojo.connect(grid, "onRowClick", grid, function(evt) {
var rowItem = this.getItem(evt.rowIndex);
var itemID = rowItem.id[0];
var store = this.store;
var paymentProposalForm = new TmpPaymentProposalForm();
paymentProposalForm._init(store.getValue(rowItem, "..."), ..., beneficiaryListStore);
});
}
};
The beneficiarylist comes as something like this:
return { 12: { id : 1, name : "ABC" }};
The FilteringSelect in the template looks like this:
<input data-dojo-type="dijit/form/FilteringSelect" name="recipient" id="recipient" value="" data-dojo-props="" data-dojo-attach-point="recipientNode" />
Template Init Code looks like this:
_init: function(..., beneficiaryListStore) {
this.recipientNode.set("labelAttr", "name");
this.recipientNode.set("searchAttr", "name");
// here should come the store assignment, I guess???
var dia = new Dialog({
content: this,
title: "ER" + incoming_invoice,
style: "width: 600px; height: 400px;"
});
dia.connect(dia, "hide", function(e){
dijit.byId(dia.attr("id")).destroyRecursive();
});
dia.show();
}
For anyone who's interested, here's my solution:
var beneficiaryList = FetchBeneficiaryList.fetch();
var beneficiaryData = {
identifier : "id",
items : []
};
for(var key in beneficiaryList)
{
if(beneficiaryList.hasOwnProperty(key))
{
beneficiaryData.items.push(lang.mixin({ id: key }, beneficiaryList[key]));
}
}
var beneficiaryListStore = new Memory({
identifier : "id",
data : beneficiaryData
});
That did the trick