How can I have my AppBar in a separate file in Flutter while still having the Widgets show?
This is another way of going about it. By doing this you can customize this appbar to the way you want. That way, if you continue with that style, you don't have to recreate it on every page. You create it once and call on it within any widget.
Class
import 'package:flutter/material.dart';class BaseAppBar extends StatelessWidget implements PreferredSizeWidget { final Color backgroundColor = Colors.red; final Text title; final AppBar appBar; final List<Widget> widgets; /// you can add more fields that meet your needs const BaseAppBar({Key key, this.title, this.appBar, this.widgets}) : super(key: key); @override Widget build(BuildContext context) { return AppBar( title: title, backgroundColor: backgroundColor, actions: widgets, ); } @override Size get preferredSize => new Size.fromHeight(appBar.preferredSize.height);}
Implementationwithin desired page
@override Widget build(BuildContext context) { return Scaffold( appBar: BaseAppBar( title: Text('title'), appBar: AppBar(), widgets: <Widget>[Icon(Icons.more_vert)], ), body: Container()); }
Let's have a widget.dart
like so:
import 'package:flutter/material.dart';class ReusableWidgets { static getAppBar(String title) { return AppBar( title: Text(title), ); }}
Let's keep using this class to get appbar
in all our screens like so:
import 'package:filter_chip/widgets.dart';import 'package:flutter/material.dart';void main() => runApp(MyApp());class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', home: Scaffold( appBar: new ReusableWidgets().getAppBar('Hello World'), body: Text( 'Flutter Demo Home Page'), ), ); }}
You can wrap AppBar into a function that return AppBar.
headerNav.dart
import 'package:flutter/material.dart';AppBar headerNav({String title}){ return AppBar( title: Text(title), );}
homePage.dart
import 'package:flutter/material.dart';import 'package:myapp/components/headerNav.dart';class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: headerNav(text:'Home Page'), body: Container( child: Text('Home'), ), ); }}