Reputation: 26427
As far as I understand I'm supposed to access my style constants in flutter via Theme.of(). In Android I would have stored them in dimens.xml
. None of the entries in ThemeData look to me like they are about padding amounts and it also seems impossible to add new ones. Where should I store the my constants for padding amounts?
Upvotes: 8
Views: 4490
Reputation: 605
If you want to access sizing using Theme.of(context)
You can create a theme extension. It ends up being more boiler plate code than storing them as constants, but it reduces the need to import random constants into your code and it enables all the features that come with using themes.
Here's an example theme extension
class AppSizes extends ThemeExtension<AppSizes> {
static const defaultSizes = AppSizes(16);
final double padding;
const AppSizes(this.padding);
@override
AppSizes copyWith({
double? padding,
}) {
return AppSizes(padding ?? this.padding);
}
@override
ThemeExtension<AppSizes> lerp(covariant ThemeExtension<AppSizes>? other, double t) {
if (other is! AppSizes) {
return this;
}
return AppSizes(lerpDouble(padding, other.padding, t)!);
}
}
From there you'll need to include the extension in your MaterialApp
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
useMaterial3: true,
colorScheme: lightColorScheme,
extensions: [AppSizes.defaultSizes], // here
),
darkTheme: ThemeData(
useMaterial3: true,
colorScheme: darkColorScheme,
extensions: [AppSizes.defaultSizes], // here
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
And then you can access them like this
Theme.of(context).extension<AppSizes>()!.padding
Upvotes: 3
Reputation: 661
I made a util function to keep paddings etc consistent
const kDefaultSpacingFactor = 8;
// this function will simple take a value and multiply with the constant scaling
// factor, to keep paddings etc consistent
double spacingFactor(double multiplier) {
return multiplier * kDefaultSpacingFactor;
}
Upvotes: 3
Reputation: 363
Create a contants.dart file and store the default padding there
const kDefaultPadding = EdgeInsets.all(16);
Upvotes: 4