Learning Flutter - flutter

I am Ali from Senegal. I am 60 years old(maybe this is my real problem - smiley!!!).
I am learning Flutter and Dart. Today I wanted to use a list of given data model (it's name is Mortalite, please see in the code below).
I try to use dartpad. I am very sad because I do not understand why the following snipet does not run:
//https://www.dartpad.dev/
void main(){
print('Beginning');
List<Mortalite>pertes;
var causes = ['Bla0', 'Bla1', 'Bla2', 'Bla3'];
var lstDate = ['21/09/2020', '22/09/2020', '23/09/2020', '24/09/2020'];
var perteInst = [2, 4, 3, 1];
var total=0;
for (int i = 0; i < 4; i++) {
total += perteInst[i];
print(i); // prints only '0'
pertes[i] = new Mortalite(
causesPerte: causes[i],
datePerte: lstDate[i],
perteInstant:perteInst[i],
totalPertes: total);
};
print(pertes.length); // nothing printed
print('Why?'); // nothing printed
}
class Mortalite {
String datePerte;
String causesPerte;
int perteInstant; // pertes du jour
int totalPertes; // Total des pertes.
Mortalite(
{this.datePerte,
this.causesPerte,
this.perteInstant,
this.totalPertes}
);
}
Thank you well for help.
A.KOTE

The reason above code doesn't work is because you have List pertes initialized and you are passing to the elements of pertes. When you try to pass to 0 index of pertes, it cannot find it and it throws range error because pertes doesn't have an index 0 yet. Please take a look at fix below and let me know if you need help with anything.
void main(){
print('Beginning');
List<Mortalite>pertes=[];
var causes = ['Bla0', 'Bla1', 'Bla2', 'Bla3'];
var lstDate = ['21/09/2020', '22/09/2020', '23/09/2020', '24/09/2020'];
var perteInst = [2, 4, 3, 1];
var total=0;
for (int i = 0; i < causes.length; i++) {
total += perteInst[i]; // prints only '0'
pertes.add (new Mortalite(
causesPerte: causes[i],
datePerte: lstDate[i],
perteInstant:perteInst[i],
totalPertes: total));
};
print(pertes.length); // nothing printed // nothing printed
}
class Mortalite {
String datePerte;
String causesPerte;
int perteInstant; // pertes du jour
int totalPertes; // Total des pertes.
Mortalite(
{this.datePerte,
this.causesPerte,
this.perteInstant,
this.totalPertes}
);
}

Related

get all the naturals less than a number in ascending order

I'm making a quiz app, and the options are storage this way:
option1 = 'First option'
option2 = 'Second option'
option3 = 'Third option'
numberOfOptions = 3
As some questions will have 4 alternatives, others 2, I'm trying to create a method to dynamically retrieve the number of alternatives available.
For that, I have the numberOfOptions variable. Based on this number, I need to get all the natural numbers less than it until 1 (as in the example, [1, 2, 3]), where I need to add to 'option'. The final result must be:
['option1', 'option2', 'option3'];
For now, what I did was:
void options() {
int numberOfOptions = 3;
for (int i = 0; i < numberOfOptions; i++) {
print('option${i + 1}');
}
}
On the output I get option1, option2, option3, but I'm stuck trying to return it as a List
One elegant solution would be to make use of the List.generate() constructor and achieve our objective with just one line:
List<String>.generate(numberOfOptions, (int index) => 'option${index + 1}');
The List.generate() constructor takes two arguments:
length;
a generator function that has an index variable;
You can read more about it on the official documentation.
It can be useful as it's much easier to read and leaner than a for-loop.
As outlined by #jamesdlin, another option would be to use the collection-for:
List<String> options = [
for(int i = 0; i < numberOfOptions; i++) 'option${i + 1}'
];
You need to create a list in your options() functions and fill it in the foor loop like so:
List<String> options(int numberOfOptions) {
final List<String> options = [];
for (int i = 0; i < numberOfOptions; i++) {
print('option${i + 1}');
options[i] = 'option${i + 1}';
}
return options;
}

Flutter, Dart Split sentence every one character to 2 characters size, for flutter custom tts project

Example:
var sentence = (hello there, I am Bob.)
var result = [
'he',
'el',
'll',
'lo',
' ',
'th',
'he',
'er',
're',
',',
' ',
'I',
' ',
'am',
' ',
'bo',
'ob',
'.']
I've found here working example, though it is in Javascript and I don't really know how to adopt it for Dart, and not sure how will behave once white space and punctuation is added in. Punctation and white space I need always split on its own not in combination with letters, I need them as well, as I will use them to add pauses in between words and sentences.
Thank you
var a = 12345678;
a= a.toString();
var arr=[];
for (var i =0; i<a.length-1; i++) {
arr.push(Number(a[i]+''+a[i+1]));
}
console.log(arr);
You could use regular expressions to split the sentence. For example:
void main() {
var exp = RegExp('([A-Za-z]{1,2}|[,!.?\s ])');
var str = "hello there, I am Bob.";
var matches = exp.allMatches(str);
for (var m in matches) {
print(m.group(0));
}
}
This looks for letters (A-Z or a-z) in groups of either 1 or 2, or single punctuation characters (,!.?) \s represents a white space.
Running the above would produce:
he
ll
o
th
er
e
,
I
am
Bo
b
.
Another approach
void main() {
var a = "1234!5678";
a = a.toString();
var arr = [];
for (var i = 0; i < a.length - 1; i++) {
if (a[i + 1] == '!') {
continue;
}
if (a[i] == '!') {
arr.add(a[i]);
continue;
}
arr.add(a[i] + '' + a[i + 1]);
}
print(arr);
}
I don't know dart much but I wrote this simple algorithm on dartpad and it works
If someone is having same issue, this is how I solved it
void main(String string) {
var test = "I Hello there I am Bob 23!";
List<String> nameArray = test.split('');
for (int curIndex = 0; curIndex < nameArray.length; curIndex++) {
if (curIndex >= 1 && nameArray[curIndex].contains(new RegExp(r'[a-zA-Z]')) && nameArray[curIndex-1].contains(new RegExp(r'[a-zA-Z]'))) {
print(nameArray[curIndex-1] + nameArray[curIndex]); // checks if current curIndex and previous curIndex are letters, if so returns previous and curent letters joined
} else {
if (curIndex >= 1 && nameArray[curIndex].contains(new RegExp(r'[a-zA-Z]')) && nameArray[curIndex+1].contains(new RegExp(r'[a-zA-Z]'))) {
null; // checks if curIndex and next curIndex are letters, if so returns null
}else{
print(nameArray[curIndex]);
}
}
}
}
Which returns
I
He
el
ll
lo
th
he
er
re
I
am
Bo
ob
2
3
!

Not getting frequency values in webaudio-api

I am using this spectrogram.js from github to plot spectrogram and obtain frequency values in real-time.
Github Repo
I have written this extra stopSong function:
function stopSong() {
var analyser = audioContext.createAnalyser();
var ctx = new AudioContext();
var osc = ctx.createOscillator();
osc.connect(ctx.destination);
osc.start(0);
spectro.stop();
var freqData= new Uint8Array(analyser.frequencyBinCount);
analyser.getByteFrequencyData(freqData);
//var f = Math.round(freqData[1]);
// var text = f + ' Hz';
var idx = 0;
for (var j=0; j < analyser.frequencyBinCount; j++) {
if (freqData[j] > freqData[idx]) {
idx = j;
}
}
var frequency = idx * ctx.sampleRate / analyser.fftSize;
console.log(frequency);
//document.getElementById("frec").innerHTML = text;
}
But everytime i am running it it give 0 as output. Can anybody tell whats wrong with my code.
You need to connect the oscillator to the analyser:
oscillator.connect(analyser);
Also you might want to call getByteFrequencyData multiple times, maybe in requestAnimationFrame, or something like setTimeout.

List all Labels of an email to Spreadsheet

My emails usually has more than one Labels assigned. I like to search emails with a specific label then list them into the spreadsheet and show all other labels also assigned to the email.
Here's what i have so far, can't figure out how to get the other labels...
function myFunction() {
var ss = SpreadsheetApp.getActiveSheet();
var threads = GmailApp.search("label:Test");
for (var i=0; i<threads.length; i++)
{
var messages = threads[i].getMessages();
for (var j=0; j<messages.length; j++)
{
var sub = messages[j].getSubject();
var from = messages[j].getFrom();
var dat = messages[j].getDate();
ss.appendRow([dat, sub, from])
}
}
}
As far as Apps Script is concerned, Gmail labels are applied to threads and not to individual messages. (There are other contexts where this isn't necessarily true, as a Web Apps post details).
So, you should use the getLabels method of the Thread object. It then makes sense to structure the output so that each row corresponds to a thread, rather than a message. This is what I did below. The script takes subject/from/date from the first message in each thread. The 4th column is the comma-separated list of labels, except the one you search for.
function myFunction() {
var sheet = SpreadsheetApp.getActiveSheet();
var search_label = 'Test';
var threads = GmailApp.search('label:' + search_label);
var output = [];
for (var i=0; i < threads.length; i++) {
var firstMessage = threads[i].getMessages()[0];
var sub = firstMessage.getSubject();
var from = firstMessage.getFrom();
var dat = firstMessage.getDate();
var labels = threads[i].getLabels();
var otherLabels = [];
for (var j = 0; j < labels.length; j++) {
var labelName = labels[j].getName();
if (labelName != search_label) {
otherLabels.push(labelName);
}
}
output.push([dat, sub, from, otherLabels.join(', ')]);
}
sheet.getRange(1, 1, output.length, output[0].length).setValues(output);
}
I prefer not to add one row at a time, instead gathering the double array output and inserting it all at once. Of course you can use appendRow as in your script. Then you wouldn't necessarily need a comma-separated list,
sheet.appendRow([dat, sub, from].concat(otherLabels));
would work.

easeljs cannot dispatch event

I want to dispatch my event,but it doesn't work. this is my code and I've deleted some irrelevant parts .
(function(window){
function HeroSelectView(){
this.initialize();
}
createjs.EventDispatcher.initialize(HeroSelectView.prototype);
HeroSelectView.prototype = new createjs.Container();
var selectedName;
HeroSelectView.prototype.Container_initialize=HeroSelectView.prototype.initialize;
HeroSelectView.prototype.initialize=function(){
this.Container_initialize();
this.initView();
}
HeroSelectView.prototype.initView = function(){
for (var i = 0; i < heroArray.length; i++) {
heroArray[i].x=100+40*i;
heroArray[i].y=200;
this.addChild(heroArray[i]);
heroArray[i].addEventListener("click",onSelectHero);
};
}
function onSelectHero(event){
selectedName=event.target.name;
var myevent = {
type: "selectedEvent",
param: selectedName
};
//var myevent=new createjs.Event("selectedEvent"); //createjs 0.7 doesnot work either.
this.dispatchEvent(myevent);
}
window.HeroSelectView=HeroSelectView;
}(window))
in the onSelectedHero, at first I tried it with createjs-0.61. you can see the "myevent" .But there is an error " TypeError: Argument 1 of EventTarget.dispatchEvent is not an object.". Then I tried it with version 0.7, but still got the same error. How can I fix this?
Thanks