I removed the widget word from my flutter app and it just worked normally so why it's written if it doesn't have value.
// Flutter
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
**Widget** build(BuildContext context) {
return MaterialApp(
title: 'Welcome to Flutter',
home: Scaffold(
appBar: AppBar(
title: Text('Welcome to Flutter'),
),
body: Center(
child: Text('Hello world'),
),
),
);
}
}
CodePudding user response:
"build" is name of function and "Widget" is the data type you want it to return just like we use "String myString()=> " Some string"
..You are just making sure that returned data type is String. On that same way, you are returning Widget. If you don't specify the data type, dart will return it dynamically.
For example, Widget myWidget()=> somewidget //returns widget
and
myWidget()=> somewidget //returns dynamic
CodePudding user response:
Short answer: It makes things clear.
class StatelessWidget extends Widget
and Widget
is included as return type,
@protected
Widget build(BuildContext context);
StatelessWidget
force you to return widget from build even you remove widget
from it.
You can add return type so that method returns can be recognized by IntelliJ to notify us error while writing code.
The method build
needs to return Widget
to work properly,
You can check this two:
int a() {
return 1;
}
int b() {
return "b";
}
For b()
it will show :String
can't be retuned from the method b
because it has return type of int
.
But if you write without return type like
b() {
return "b";
}
This will not show any errors until you read it. You might also find errors suggestion while performing arithmetic operation here.
A simple things often can cause unwanted errors, like
c() {
return 3;
}
If you use it inside Text(c())
widget, while Text
widget expect string not int. It will cause runtime errors.
Instead of using dynamic return type, It is safer to include return type.
You can check guides and effective-dart