Flutter First "Hello World" App
Posted on
< Previous Next >
1. Create a new Flutter project: To create a new Flutter project, you can use either the command line or an IDE like Android Studio or VS Code. For example, using the command line, you can type "flutter create hello_world" to create a new project named "hello_world".
2. Modify the main.dart file: This file is the entry point to your app, and contains the main function. In this function, you'll create a new MaterialApp widget, which is the root widget of your app. You can use the home property of this widget to define the content of your app.
Here's an example of what the main.dart file might look like:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: Text('Hello, World!'),
),
),
);
}
}
Run the app
With your app code written, you can now run it on a device or emulator.
You can use the "flutter run" command to launch your app on a connected device or emulator.
When you run your app, you should see a centered text widget displaying "Hello, World!" on the screen.
Let's go through the code in detail:
import 'package:flutter/material.dart';: This line imports the Flutter Material library, which provides a set of widgets and styles that follow Material Design guidelines.
void main() => runApp(MyApp());: The main function is the entry point of your Flutter app. It creates an instance of the MyApp widget and passes it to the runApp function, which launches the app.
class MyApp extends StatelessWidget: The MyApp class defines the behavior and appearance of your app. By extending StatelessWidget, it tells Flutter that this widget will never change dynamically.
@override Widget build(BuildContext context): The build method returns the widget tree that represents the user interface of your app.
MaterialApp: This is the root widget of your Flutter app. It provides the default behavior and appearance for the app, such as the theme and the initial route.
Scaffold: This is a basic layout that provides a default app bar, a body, and a floating action button.
Center: This is a widget that centers its child within itself.
Text('Hello, World!'): This is a widget that displays text on the screen.
And that's it! With just a few lines of code, you've created a simple Flutter app that displays "Hello, World!" on the screen.
Output:
