Declare AppBar in another dart file and instantiate it with an different file

Issue

It’s the 4th day of my Flutter. I used to use Unity.
Currently my project has 3 pages; Home, Profile, Settings

These pages are transitioned using Navigator.
The AppBar is declared in the Scaffold within each page, but the AppBar for all pages is the same.
So I have to write three of the same code. (always need to write and modify the same code as the number of pages increases in the future)

So I thought it looks good to declare AppBar as a variable and the page would just call it.
Like this:

//originappbar.dart
AppBar originAppBar(
    backgroundColor: .....
)

//home.dart
class ShowHome extends StatelessWidget {
  ShowHome({Key? key}) : super(key: key);
  static const String route = '/home';
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: originAppBar(), ....

 //profile.dart
 //Same as home.dart

In the above example, I’m trying to assign the originAppBar created by originappbar.dart to appbar: in home.dart or profile.dart.

But I can’t declare AppBar as a variable.
I’m confused because I thought I could make AppBar a variable.
What’s wrong with my code?

Thank you.

Solution

PreferredSizeWidget originAppBar = new AppBar(
 backgroundColor: .....
)

//home.dart
class ShowHome extends StatelessWidget {
  ShowHome({Key? key}) : super(key: key);
  static const String route = '/home';
  @override
  Widget build(BuildContext context) {
    return Scaffold(
    appBar: originAppBar, ....
//profile.dart
//Same as home.dart

Answered By – Abhishek singh

Answer Checked By – Clifford M. (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *