Create AppBar in Flutter | Detailed Introduction
Flutter AppBar is a Material Design widget in Flutter that provides a top app bar. The AppBar is an integral part of the Flutter Material Design widget set and is used to provide a top app bar, which can be used to host action buttons, app title, and other widgets. In this tutorial, we will explore the basics of the Flutter AppBar widget, how to use it in your Flutter application, and how to customize its appearance.
Step 1: Import the necessary packages
Before we can start using the AppBar widget, we need to import the necessary packages. Open your Flutter project’s main.dart
file and add the following line of code at the top of the file:
import 'package:flutter/material.dart';
Step 2: Create a new widget
Now that we have imported the necessary packages, we can create a new widget that will display the AppBar. Create a new widget by defining a new class that extends the StatelessWidget
class:
class MyAppBar extends StatelessWidget {
@override
Widget build(BuildContext context) {
return AppBar(
title: Text("My AppBar"),
);
}
}
Step 3: Add the AppBar to your app
We now have a new widget that displays an AppBar, but we still need to add it to our app. To do this, we need to modify the build
method of our MyApp
widget to include the MyAppBar
widget:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: MyAppBar(),
body: Container(),
),
);
}
}
Step 4: Customize the AppBar
The AppBar provides several properties that can be used to customize its appearance. For example, you can change the background color of the AppBar, add a leading widget, or change the title text style. Here’s an example of a customized AppBar:
class MyAppBar extends StatelessWidget {
@override
Widget build(BuildContext context) {
return AppBar(
backgroundColor: Colors.red,
leading: Icon(Icons.menu),
title: Text(
"My AppBar",
style: TextStyle(
fontSize: 20.0,
color: Colors.white,
),
),
actions: [
IconButton(
icon: Icon(Icons.search),
onPressed: () {},
),
IconButton(
icon: Icon(Icons.more_vert),
onPressed: () {},
),
],
);
}
}
In this example, we’ve changed the background color of the AppBar to red, added a menu icon to the leading position, and changed the title text style to white and font size to 20.0. We’ve also added two action buttons to the AppBar.
Step 5: Run the app
Now that we’ve created and customized our AppBar, we can run our app to see the results. To do this, run the following command in the terminal:
flutter run