1

I am new to flutter and was studying with StatefulWidget but I couldn't clearly understand the following term

class MyApp extends StatefulWidget
{
  @override
  _myState createState() => _myState();
}  

I tried this

@override return _myState(); And its clear to me, but we user _myState before createState() method.

Delowar Hossain
  • 375
  • 1
  • 3
  • 19
  • Now that you edited your question, I'm confused what you are trying to ask here. What do you mean by "used _myState before createState() method"? – Swift Jan 16 '19 at 02:01
  • I wanted to make it more clear but rather I messed it up. Can you now take a look? – Delowar Hossain Jan 16 '19 at 02:04

1 Answers1

2

_myState here is actually a type, not a variable name.

This function here

@override
_myState createState() => _myState();

is equivalent to:

@override
_myState createState() {
    return new _myState();
}

where the class _myState is likely defined as so:

class _myState extends State<MyApp> {
    ...
}

In dart, you do not need to use new (optional) to instantiate an object.

However by naming convention class names should be in PascalCase, in this case _MyState instead of _myState which will help make it more readable, especially in your case here.

Swift
  • 3,250
  • 1
  • 19
  • 35
  • one more thing. As far I know, we have types **String, List, Int** etc. But I don't get a clear picture about it **_myState** type – Delowar Hossain Jan 16 '19 at 02:05
  • 1
    `_myState createState()` basically means the method `createState()` return a `_myState` type which is defined as a class. Why is it a problem if we "used _myState before createState() method" like you said? – Swift Jan 16 '19 at 02:10
  • My question is can we declare any **type** apart from a pre-defined type like **String, Int, List, Bool**. – Delowar Hossain Jan 16 '19 at 02:25
  • You are essentially creating a new type by defining the `_myState` class here. Afterwards you can use the class itself as a type: `_myState newState = new _myState();` – Swift Jan 16 '19 at 02:28
  • is there any difference between my newly created type and pre-defined data types? – Delowar Hossain Jan 16 '19 at 02:29
  • 2
    Well types are just types. Even primitive data types like String and int are just classes that are defined in the dart libraries. – Swift Jan 16 '19 at 02:32
  • 1
    (note that `int` and `bool` start with lower case letters) – Richard Heap Jan 16 '19 at 02:34