Flutter: Can't access 'this' in a field initializer to read 'msgTextStyle', when trying to refer to a variable from another variable - flutter-layout

I got error when trying to refer to a variable from another variable. In below code, error happen when refer to msgTextStyle in msgList.
Error: "Can't access 'this' in a field initializer to read 'msgTextStyle'."
How to fix this while still keep the my intention, and what is the best practice?
Thank you!
final msgTextStyle = TextStyle(
fontFamily: 'Roboto',
fontSize: 18,
letterSpacing: 0.5,
height: 2,
);
final msgList = Column( children: [
Text('text 1.',style: msgTextStyle),
Text('sync: added 4 numbers into call blacklist.',style: msgTextStyle)
]);

It seems like you're trying to access an instance variable (msgTextStyle), in another instance variable(msgList) before constructor is initialized. This is disallowed as you're trying to access something that isn't. Move the initialization of msgList to constructor or initState or perhaps try converting msgTextStyle to const.

Related

A non-null String must be provided to a Text widget

I'm trying to add the option for the quantity to be adjusted but I get an error saying "A non-null String must be provided to a Text widget"
How do I provide this, to this code?
trailing: Container(
height: 60,
width: 60,
padding: EdgeInsets.only(left: 10),
child: Column(
children: <Widget>[
new GestureDetector(child: Icon(Icons.arrow_drop_up), onTap: () {}),
new Text(cart_prod_qty),
new GestureDetector(child: Icon(Icons.arrow_drop_down), onTap: () {})
],
),
You should check null safe
Text(cart_prod_qty??'default value'),
Just check for null and give a default
Text(cart_prod_qty!=null?cart_prod_qty:'default value'),
You can keep it empty if you wish
Text(cart_prod_qty!=null?cart_prod_qty:''),
Or else you can make text widget optional
cart_prod_qty!=null? Text(cart_prod_qty): Container()
The error itself shows what's wrong in the code, Text widget works only with string and for null they intentionally have thrown an exception.
Check text.dart file implementation where they added throwing an exception.
assert(
data != null,
'A non-null String must be provided to a Text widget.',
),
To solve above error you have to provide some default text.
new Text(cart_prod_qty!=null?cart_prod_qty:'Default Value'),
An advice for you in this case and all who are reading this.
When you add an non direct String value to the Text() don't directly insert it like you did in this example:
Text(cart_prod_qty)
Because you can get "A non-null String must be provided to a Text widget" like I did.
So I advise you to practice this in the future it's more safe:
Text('${cart_prod_qty}')
if you know for certain that it's not null, then you can safely do this:
Text(cart_prod_qty!),
to me, when it's definitely not null in the usage case, it's cleaner than doing this:
Text(cart_prod_qty ?? ''),
The value may be empty therefore youre getting a null error try this if its an optional field:
new Text(cart_prod_qty == null ? '' : cart_prod_qty),
If you know that your string is nullable you could do something like this. Although I used the visibility widget because I don't want my widget to be displayed if it's null.
class NullableTextWidget extends StatelessWidget {
final String? text;
final TextStyle? textStyle;
const NullableTextWidget({Key? key, this.text,this.textStyle}) : super(key: key);
#override
Widget build(BuildContext context) {
return Visibility(
visible: text != null,
child: Text(
text ?? "",
style: textStyle,),
);
}
}
just set Text widget value optional like
Text(value ?? ""),
The problem is visible. You're passing null to Text widget. new Text(cart_prod_qty) This can be due to delay of response from api (if you're using it). Or there is no value in the variable "cart_prod_qty". You can handle it like this: new Text(cart_prod_qty != null ? cart_prod_qty.toString : '')
I faced the same problem while fetching data from Firebase . It was initially: Text(widget.title) - it caused the error .
Later, I transformed the Text() into this format:
Text('${widget.title}')
this interpolates the fetched data inside the Text() widget .
If you receive a null value return , that would be a server issue .
Hope this might help someone .
I have faced that same problem.... I have resolved it by using a
"new" keyword before Text...
child: new Text(mydata[1]["2"][k]),
I GOT SAME ERROR DUE TO THIS
BEFORE:
title: Text(widget.title)
AFTER:
title: Text('ram')
THIS SOLVED MY ERROR
To solve this error Add Double quote or single quote title: Text('ram')

selectize.js lockOptgroupOrder throwing exception

I have a selectize where I set optgroups, give them an $order, and then try to set lockOptgroupOrder, which ends up throwing an exception: "Uncaught TypeError: Cannot read property '$order' of undefined".
This all works perfectly before I try to use lockOptgroupOrder (except that it sorts wrong). I cannot figure out why it can't find $order, when I'm clearly passing $order in as part of optgroups. (I've also tried setting optgroupOrder: ['first', 'recents', 'favorites', 'all'] with no luck.)
var stuff = $('#stuff').selectize({
optgroups: [
{value: 'first', label: '', $order: 1},
{value: 'recents', label: 'Recents', $order: 2},
{value: 'favorites', label: 'Favorites', $order: 3},
{value: 'all', label: 'All', $order: 4}
],
optgroupField: 'type',
lockOptgroupOrder: true,
//more things like load() and onChange()...
});
The error:
It's breaking in this loop:
I have exhausted all other forms of researching this error. Has anyone come across this before?
So after many, many hours of googling, chrome debugging, and general crying, I figured out the issue and now I'm posting my solution in case anyone else comes across this error.
Thanks to this discussion board:
lockOptgroupOrder breaks onChange
I was able to piece together that one of my data elements was missing a 'type' field (optgroupField). I stepped through all 1350 options before realizing that it was actually the default option I added to the select before turning it into a selectize. In this instance, I need this option to stay, so I can't just get rid of that line of html. But I also can't add a "type" attribute to the option, or even a data-type attribute, it doesn't pass it along.
Finally I figured out from this discussion board:
Add data-attribute to selectize.js options
that I can assign a data-data attribute and pass it the name and value, and then it would pass that attribute along when it turns into a selectize. So my final solution was to add what I needed via the option before it turns into a selectize:
<option selected disabled value="default" data-data='{"type":"first"}'>The Stuff</option>
May this help some other poor soul from having to go through this in the future.

How to set target anchor when creating a link

I'm trying to set a specific anchor point when creating a link. I believe I'm doing everything correctly, but the anchor options are being ignored. In fact, any options I pass in are being ignored.
My code looks something like this:
new joint.shapes.standard.Link().target({id: 'xxx'}, {
anchor: {
name: 'center',
args: { dy: -15 }
}
});
The target id is being correctly handled, but whatever I pass in the second parameter is totally ignored.
Has anyone come across this before?
After experimenting, I worked out that when passing an object with id, rather than parsing a target element, that the opts need to go inside the object with the id. This is not documented AFAIK.
i.e.
.target({id: element.id, opts})
In my specific case, I'm passing the following:
.target({ id: to.id, anchor: { name: 'center', args: { dy: -15 }}})
This seems to work correctly

How to update the data in an ng2-chartjs2 chart in Angular 2 and Node JS

I am using NodeJS, Angular2, and the ng2-chartjs2. Below I listed the relevant parts of my code that is rendering charts. The data is loaded into this.data from an API using a fixed date range. I would like to allow the user to select a date range and then update the chart. From here I know that you can call update() on the chart object to update the data in it, but I don't know how to get a hold of the chart object, since the component code never actually has a reference to it - it's done automagically when the template is rendered. Looking at the source code (line 13) I see that the author intended to make the object available. I contacted the author but haven't received a response yet and need to get moving. I have learned a lot about Angular2 but am no expert yet, so perhaps a deeper understanding of Angular2 makes this obvious. How can I either get access to the object to call update() on it, or do it some other clean way?
The template contains
<chart [options]="simple.options"></chart>
and the component typescript code contains
import { ChartComponent } from 'ng2-chartjs2';
...
#Component({
selector: 'home',
templateUrl: 'client/components/home/home.component.html',
styleUrls: ['client/components/home/home.component.css'],
directives: [DashboardLayoutComponent, CORE_DIRECTIVES, ChartComponent],
pipes: [AddCommasPipe],
})
...
setCurrentSimpleChart = (simpleType: number): void => {
this.simple.options = {
type: 'line',
options: this.globalOptions,
data: {
labels: this.data[simpleType].labels,
datasets: [{
label: this.titles[simpleType],
data: this.data[simpleType].data,
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255,99,132,1)',
borderWidth: 1
}],
},
};
...
}
Update: In case this helps anyone: I actually have two different charts on the page, so I googled around based on the accepted answer and found ViewChildren, and mapped them to different variables so I can update them both separately, with
[this.simpleChart, this.liftChart] = this.chartComponents.toArray().map(component => component.chart);
(Note also that this was using an rc of angular2 - since then directives, etc have been moved out of the components themselves.)
You can hold reference to component by using ViewChild:
#ViewChild(ChartComponent) chartComp;
And then you can get chart object:
let chart = this.chartComp.chart;
Here is the corresponding plunker

Fabric: error loading subclass object from JSON

In this jsfiddle I have a line that is created from a subclass (it's basically a line with two additional attributes). I'm trying to serialize/deserialize the line to/from JSON. I can serialize with no problems (including the two additional attributes) but when I try to deserialize with loadFromJSON I get the Cannot read property 'async' of undefined exception.
Uncomment the last line in the jsfiddle to get the error.
I implemented the fromObject() method, but I'm not sure it's correct. What's wrong with this code?
Javascript:
var canvas = new fabric.Canvas('c');
fabric.PolySegment = fabric.util.createClass(fabric.Line, {
type: 'seg',
initialize: function(points,options) {
options || (options = { });
this.callSuper('initialize', points,options);
this.set('poly', options.poly);
this.set('id', options.id);
},
toObject: function() {
return fabric.util.object.extend(this.callSuper('toObject'), {
poly: this.get('poly'),
id: this.get('id')
});
},
_render: function(ctx) {
this.callSuper('_render', ctx);
}
});
fabric.PolySegment.fromObject = function (object, callback) {
return new fabric.PolySegment(object);
};
fabric.PolySegment.async = true;
var coords1 = [ 10, 10, 100, 100 ];
var seg1 = new fabric.PolySegment(coords1, {
stroke: 'black',
strokeWidth: 6,
originX: 'left',
originY: 'top',
poly: 111111,
id: 222222
});
canvas.add(seg1);
var json = JSON.stringify(canvas);
document.getElementById('t').innerHTML = json;
// uncomment the line below, you'll get an exception
//canvas.loadFromJSON(json);
In looking at your Fiddle, it seems like the issue is the type value you have given your new class. If I change:
type: 'seg',
to
type: 'polySegment',
and uncomment the last line, I don't get the error. However, I also don't get the line to load on the canvas. But I guess I'm not 100% sure what is happening in your script there - you're loading the polySegment, then converting it to JSON and reloading it? I'm assuming this is merely for illustration purposes.
While what I suggest here gets rid of your error, I'm personally not 100% sure why it works. In reading the FabricJS documentation on Subclassing, it doesn't specify that the subclass type needs to match that of the subclass definition, but it seems to work...
I hope that helps in some way.
One last comment about this, I've always used the toJSON method to transfer a canvas element to JSON. Though this retrieves a JSON object, not a string like you are doing. Also, the toJSON method requires that you specify what properties you want to capture, so maybe this isn't the best method for your case. It's discussed on this page. But my point for bringing this up, is I know for certain that the toJSON method works well with the loadFromJSON method. So I mention that in case you find the JSON.stringify method to be the issue, there is a alternate method to approach the same concept.

Resources