Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to add an AppBar only once in flutter app and use it in all routes without duplicating the same AppBar code in those routes?

I'm trying to find a way to add an AppBar only once without having to duplicate the AppBar code on different routes. I have tried different approaches but I still cant get the results that I want.

This is the main.dart file.

import 'package:flutter/material.dart';
import 'package:com.example.simple_app/pages/page_one.dart';
import 'package:com.example.simple_app/pages/page_one.dart';

void main() => runApp(SimpleApp());

final routes = {
  '/': (BuildContext context) => new PageOne(),
  '/pageone': (BuildContext context) => new PageOne(),
  '/pagetwo': (BuildContext context) => new PageTwo(),
};

class SimpleApp extends StatefulWidget {
  @override
  _SimpleAppState createState() => _SimpleAppState();
}

class _SimpleApp extends State<SimpleApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Simple App',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blueGrey,
      ),
      initialRoute: '/',
      routes: routes,
    );
  }
}

Below is PageOne.dart file where I've hardcoded AppBar code.

import 'package:flutter/material.dart';

class PageOne extends StatefulWidget {
  PageOne({Key key}) : super(key: key);

  @override
  _PageOneState createState() => _PageOneState();
}

class _PageOneState extends State<PageOne> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Simple AppBar'),
      ),
    );
  }
}

Below is PageTwo.dart file where I've also put AppBar by writing the whole code, I'm duplicating AppBar code which is not cool.

import 'package:flutter/material.dart';

class PageOne extends StatefulWidget {
  PageOne({Key key}) : super(key: key);

  @override
  _PageTwoState createState() => _PageOneState();
}

class _PageTwoState extends State<PageOne> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Simple AppBar'),
      ),
    );
  }
}

I'm new to flutter but I hope you understand what I'm saying.

What I want is to be able to use AppBar in different routes without duplicating the code. For example when we go to web development, A website built in php you can simply include views. I want something similar here or better, Thank you.

like image 925
Muje Avatar asked Jan 26 '26 19:01

Muje


1 Answers

Use builder property in MaterialApp to build common container for every page

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: Theme.of(context).copyWith(highlightColor: Colors.amber),
      //TODO: Use `builder` to add top most container for all page
      builder: (context, child) {
        return Scaffold(
          appBar: AppBar(
            title: Text("Simple AppBar"),
          ),
          body: child, //this child is dynamically replaced with corresponding page when we navigate
        );
      },
      home: FirstPage(),
      debugShowCheckedModeBanner: false,
    );
  }
}

class FirstPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Text("This is First Page"),
        RaisedButton(
          child: Text("Goto Second Page"),
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => SecondPage(),
              ),
            );
          },
        ),
      ],
    );
  }
}

class SecondPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Text("This is First Page"),
        RaisedButton(
          child: Text("Go Back"),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
      ],
    );
  }
}
like image 124
Crazy Lazy Cat Avatar answered Jan 29 '26 08:01

Crazy Lazy Cat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!