I am trying to add a background image which is always there no matter which route is active. I the example below is inspired by this answer but the background will only be visible for the route "/". I was hoping to not have to set the background image for each route. Any suggestions?
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: const BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/images/camping-background.png"),
fit: BoxFit.cover),
),
routes: <String, WidgetBuilder>{
'/login': (BuildContext context) => const Login(),
'/register': (BuildContext context) => const Register(),
'/home': (BuildContext context) => const Home(),
},
);
}
2
Answers
Updated answer
For the sake of a background image, you can simply wrap your MaterialApp in the DecoratedBox. This is preferable to the other approach (outlined further below) because that abuses
builder
which is intended for other purposes:As
MaterialApp
solely configures non-rendered widgets and theDecoratedBox
doesn’t rely on any of them, it can simply serve as parent widget to the rest of the app achieving the desired effect.Previous answer
You may use the
builder
field onMaterialApp
to provide a TransitionBuilder function that defines a common wrapper for all routes:It takes a
BuildContext
as well as the currently rendered route aschild
as arguments and returns a Widget that is then displayed as the route.Also since it seemed like there was some confusion with regards to the usage of
home
androutes
, here is a snipped from theMaterialApp
docs:While you could use
home
androutes
together, I personally thing it’s more clear what’s going on with routes using onlyroutes
in addition toinitialRoute
to indicate which is first (unless it is indeed/
which is the default).Copy & Paste it on dartpad to see the results
Complete with scaffold app bar & no background image sample
Check it on Gist: Complete code here