When a instance function being declare Static, does that mean that it can't return a new instance of another object?
Aren't the purpose of the Static keyword is to save the memory, does that mean when i call the static member, it had to return for me the EXACT object ?
class Provider extends InheritedWidget {
final bloc = Bloc();
bool updateShouldNotify(_) => true;
Provider({Key key, Widget child}) : super(key: key, child: child);
static Bloc of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<Provider>().bloc;
}
}
class SignUp extends StatelessWidget {
#override
Widget build(BuildContext context) {
// This is not the same object
final bloc = Provider.of<Bloc>(context);
}
class Login extends StatelessWidget {
#override
Widget build(BuildContext context) {
// This is not the same object
final bloc = Provider.of<Bloc>(context);
}
Once function is declared static, that means it is no longer "instance" function, but rather class function.
Declaring function static means that you no longer have access to instance (i.e. this). This is just function aliased by the class it is declared in.
Static function can return anything, including new instances of classes, where it is declared.
Static function will not help you to save memory.
My assumption though (I might be wrong) is that static function is a little bit easier for compiler to compile as it does not take part in polymorphism.
Everything from Alex above is correct.
I just want to point the most important differences you should no:
It is not related to any object, and so it can be called directly from the class.
In Java and maybe other languages polymorphic rules no longer work as expected. For this many people do use the Singleton-Pattern, which itself is based on a static function.
Further reading:
https://en.wikipedia.org/wiki/Static_(keyword)
https://en.wikipedia.org/wiki/Singleton_pattern
https://www.javatpoint.com/static-keyword-in-java
https://www.geeksforgeeks.org/static-methods-vs-instance-methods-java/
In general you should try doing some own research before asking questions here, and so make questions less random ;)
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];
}
}
I'm new to using Flutter and I am currently struggling to understand how to use the Provider package for the following task, or if it is even the correct implementation in the first place.
I have a widget that uses another widget within itself to update a time value.
In the parent widget I have the following:
class _AddTimesScreenState extends State<AddTimesScreen> {
List<TimeOfDay> times = [];
#override
Widget build(BuildContext context) {
return Scaffold(
body: Provider<List<TimeOfDay>>.value(
value: times,
child: SetTimes()
In the 2nd widget, which is used to update the times list by using a time picker I have:
class _SetTimesState extends State<SetTimes> {
#override
Widget build(BuildContext context) {
final times = Provider.of<List<TimeOfDay>>(context);
Essentially my goal is to be able to update the times list in the 2nd widget so it can then be used in the first widget. I have methods to add TimeOfDay objects to the list, but when the code is run the list in the first widget does not appear to be updated.
Am I using Provider in a way that it's intended, or have I completely misunderstood its application?
Thanks
In the TimeOfDay class make sure you are extending it with Change Notifier.
How does provider know it has to rebuild?
When the class (TimeOfDay in your case) extends ChangeNotifier, you are provided with a method called notifylisteners() , this triggers a rebuild to all the widgets consuming the provider. So you should call this in the function that is changing the objects data in your class TimeOfDay.
So make sure you are:
extending ChangeNotifier in your class/model.
calling notifylisteners when data is changed.
Example :
class MyClass extends ChangeNotifier{
int a = 0;
addSomething(){
//Here we are changing data
a = a + 1;
notifylisteners();
}
}
let me know if this solves your error.
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 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;
}