class LevelUp extends GetxController {
Map<String, String> params = Get.arguments;
var myTest = params.[comLevel];
}
Error report--"The instance member 'params' can't be accessed in an initializer." I am new to programming and this is being called directly from a widget. I checked the LevelUp map and it has contents. The error occurs where I am trying to assign the param value to myTest. It doesn't matter if I put the key in quotes or provide an integer. Any advice would be greatly appreciated.
You can't access params before you've initialized the object. To fix your example, move your myTest initialization into a constructor.
Also, I don't believe you should have a period before [comLevel].
class LevelUp extends GetxController {
Map<String, String> params = Get.arguments;
String myTest;
LevelUp() {
myTest = params[comLevel];
}
}
Null safety update:
Use late keyword: Dart 2.12 comes with late keyword which helps you do the lazy initialization which means until the field bar is used it would remain uninitialized.
class Test {
int foo = 0;
late int bar = foo; // No error
}
Although this question has been answered for the OP's case, I want to offer a solution to those receiving this error in a StatefulWidget scenario.
Consider a situation where you would want to have a list of selectable items that dictate which category to display. In this case, the constructor might look something like this:
CategoryScrollView({
this.categories,
this.defaultSelection = 0,
});
final List<String> categories;
final int defaultSelection;
Note the property defaultSelection is responsible for specifying which category should be selected by default. You would probably also want to keep track of which category is selected after initialization, so I will create selectedCategory. I want to assign selectedCategory to defaultSelection so that the default selection takes effect. In _CategoryScrollViewState, you cannot do the following:
class _CategoryScrollViewState extends State<CategoryScrollView> {
int selectedCategory = widget.defaultSelection; // ERROR
#override
Widget build(BuildContext context) {
...
}
}
The line, int selectedCategory = widget.defaultSelection; will not work because defaultSelection it hasn't been initialized yet (mentioned in other answer). Therefore, the error is raised:
The instance member 'widget' can't be accessed in an initializer.
The solution is to assign selectedCategory to defaultSelection inside of the initState method, initializing it outside of the method:
class _CategoryScrollView extends State<CategoryScrollView> {
int selectedCategory;
void initState() {
selectedCategory = widget.defaultSelection;
super.initState();
}
A simple example, where it shows how we can resolve the above issue,
Example: Create an instance of class B, and pass an instance of class A in the parameter of it
WRONG(Compile time error of initializer):
final A _a = A();
final B _b = B(_a);
shows error: The instance member '_a' can't be accessed in an initializer.
Right:
final A _a = A();
late final B _b;
AppointmentRepository() {
_b = B(_a);
}
#100% working solution
:
Juts place var myTest = params.[comLevel];
below your Build method.
eg.
class LevelUp extends GetxController {
Map<String, String> params = Get.arguments;
Widget build(BuildContext context) {
var myTest = params.[comLevel];
}
}
For me it happened Because i was trying to access a Property of a class instance (Lets Say Class A ) And Use this property to initialize Another Class (Class B) , The Property Was Integer Number and Was Defined
However , Since i didn't Make an Object from "Class A" I can access those propertied Belong to it !
I tried to use this property inside the "Build" Method so that an object is "Created/Built" And it Worked !
I also got the similar error.
And I found the solution as follows.
My first code:
final BuildContext mycontext = GlobalContextClass.navigatorKey.currentContext;
final PsValueHolder psValueHolder = Provider.of<PsValueHolder>(mycontext, listen: false);
Next is the code where the error is fixed:
final PsValueHolder psValueHolder = Provider.of<PsValueHolder>(GlobalContextClass.navigatorKey.currentContext, listen: false);
Instead of defining 2 variables in a row, I placed the first variable directly in the place of the 2nd variable.
Another solution is making your variable, a GetX parameter.
int count_myProducts = cartItems.length; //The instance member 'cartItems' can't be accessed in an initializer. (Documentation)
int get count_myProducts => cartItems.length;
see this video at 27:34
GetX State Management tutorial with Flutter
https://www.youtube.com/watch?v=ZnevdXDH25Q&ab_channel=CodeX
Just carry
var myTest = params.[comLevel];
into Widget build{} below.
like this :
class LevelUp extends GetxController {
Map<String, String> params = Get.arguments;
Widget build(BuildContext context) {
var myTest = params.[comLevel];
}
}
Related
This is my Notifier:
class Counter extends Notifier<int> {
final int initial;
Counter(this.initial);
#override
int build() => initial;
}
I need to pass initial value to it, but I'm unable to do that using the family modifier anymore.
// Error
final counterProvider = NotifierProvider.family<Counter, int, int>((initial) {
// How to get the initial value to pass here?
return Counter(initial);
});
The syntax for using family/autoDispose using Notifier/AsyncNotifier is different. You're supposed to change the inherited type
So instead of:
final provider = NotifierProvider(MyNotifier.new);
class MyNotifier extends Notifier<Value> {
With family you should do:
final provider = NotifierProvider.family(MyNotifier.new);
class MyNotifier extends FamilyNotifier<Value, Param> {
And the same reasoning applies with autoDispose.
I am trying to store data in an object reference right now it's just a simple class but letter i am replacing it with a singleton class kindly explain why I am not able to initialize the object just above build method.
class MyStatefulWidget1State extends State<MyStatefulWidget1> {
final TextEditingController titleController = TextEditingController();
Data().value = "dscs"; **//IF i define here it will produce error**
#override
Widget build(BuildContext context) {
Data().value = "dscs"; **// bu if i define here it will work just fine**
return TextField(controller: titleController);
}
}
class Data {
String value;
}
In any type of class we can only create variable and method while you are trying to access objects member variable(value) that't why it is giving error.
While build method is also one type of method, so you can access any class or object member variable too. That's why it is working over there.
If you create simple object Data class in MyStatefulWidget1State state then then try to access it's member variable then also you will get same error.
Something like following.
Data c = Data();
c.value = 'f';
But we can do it in any method, so it will work in build method.
You can use initState() for this purpose.
#override
void initState() {
super.initState();
Data().value = "dscs";
}
I have a stateless widget and while writing the code I am using a non-final field in the stateless widget and the ide keeps giving me warning that all the fields in stateless widget should be final
But I don't understand why having a non-final field in stateless widget be a problem.
I think it should be perfectly fine to have non-final field because there could be a field that we don't want to modify later but this field can only be initialized inside the constructor function so, for that you need to use non-final field
example:
class Temp extends StatelessWidget {
final int a;
final int b;
int c;
temp({this.a, this.b}) {
this.c = this.a + this.b;
}
#override
Widget build(BuildContext context) {}
}
In the above widget, I can't make c as final because it is initialized inside the constructor function even though I have no plans to change the c variable in the future.
If having a non-final field in a Stateless widget is not a good Idea then How to handle the above situation.
Note: I cannot use the Constructor() : [initialization] {} because the initialization can involve the function or loops
StatelessWidget class A widget that does not require mutable state, so the class is marked as #immutable, Dart language do the best to fix your errors, so "final" keyword will just warn you about that but will not stop the compiling, you can use your code normally without final keyword if you are sure it will initialized one time and not change again at run-time ..
and this is the main reason to have 2 keywords (final, const) for define constants in Dart language
Both final and const prevent a variable from being reassigned.
const value must be known at compile-time, const birth = "2020/02/09". Can't be changed after initialized
final value must be known at run-time, final birth = getBirthFromDB(). Can't be changed after initialized
You can use initialization even for function invocation.
here is an example:-
class SumWidget extends StatelessWidget {
final int sum;
static getSum(List<int> items) {
int perm = 0;
for (var value in items) {
perm += value;
}
return perm;
}
SumWidget(List<int> roles) : this.sum = getSum(roles);
#override
Widget build(BuildContext context) {}
}
but function must be static because The instance member can't be accessed in an initializer.
I have an object that has static constant which I need to reach from its instance.
class ChatsScreen extends StatefulWidget {
var arguments;
static const name = ADatas.chatRoute;
ChatsScreen(this.arguments);
createState() => ChatsScreenState();
}
In above class' State object, I want to call static const name. Above class' State object's code:
class ChatsScreenState extends State<ChatsScreen> with RouteHelper{
String userName = "";
var textEditingController = TextEditingController();
#override
void initState() {
getRouteName(widget); //=> as I understand and see on the VSCode, its the ChatsScreen object.
super.initState();
}
}
I'm trying to implement an interface so I don't know the actually class name while writing the interface. And I thought that I can reach its static constant if I know its actual class. And I wrote something like this but it seems not to be possible. I guess I have a misunderstanding.
class RouteHelper{
String getRouteName(dynamic instance){
if(instance is StatefulWidget){
return instance.runtimeType.name; // => !!!
}
}
}
Note: I'm not trying to get the route name in actual. It's just a concept that i used in this question, so please don't refer better way to get the route name in flutter.
You can't do it like that, people have talked about this in this issue.
However you can kinda do it using class members and typing system.
abstract class Routed {
String getClassRoute();
}
class ChatsScreen extends StatefulWidget implements Routed {
var arguments;
static const name = "myexampleroutename";
ChatsScreen(this.arguments);
createState() => ChatsScreenState();
#override
String getClassRoute() {
return ChatsScreen.name;
}
}
class RouteHelper {
String getRouteName(Routed instance) {
return instance.getClassRoute();
}
}
I said you can't, but with dart:mirrors it is possible, however it is banned on Flutter packages. There is reflectable package that tries to fix that using code generation, but I am not aware of it's status/reliability.
I have a final and I am trying initializing that in the constructor. It is giving me error & If I don't make it final I get a warning.
This class (or a class which this class inherits from) is marked as '#immutable', but one or more of its instance fields are not final: GenderCard.genderSvg",
My Code:
GenderCard({#required this.genderType}) {
genderSvg = '/assets/' + 'genderType' + '.svg';
}
final String genderType;
final String genderSvg;
#override
Widget build(BuildContext context) {
final instance variables must be initialized in the initializer list. See the language guide.
Instance variables can be final but not const. Final instance
variables must be initialized before the constructor body starts — at
the variable declaration, by a constructor parameter, or in the
constructor’s initializer list.
Change your constructor to:
class GenderCard {
GenderCard({#required this.genderType})
: genderSvg = '/assets/$genderType.svg';
final String genderType;
final String genderSvg;
}