Flutter: How to theme material widgets in Cupertino theme?

Issue

I have a Flutter app which uses Material theme for Android and Cupertino theme for iOS. But I use Card widget, which is a Material widget, in both themes. Now I have the following code in main.dart

Widget build(BuildContext context) => PlatformProvider(
      builder: (BuildContext context) => PlatformApp(
            cupertino: (_, __) => CupertinoAppData(
                theme: CupertinoThemeData(brightness: Brightness.light, ...)),
            material: (_, __) => MaterialAppData(
                theme: ThemeData(
                  brightness: Brightness.light,
                  primarySwatch: Colors.deepPurple,
                  cardTheme: CardTheme(
                    color: Colors.grey,
                    ...
                  )
                  ...
                ),),
......

As you can see, the Card widget is themed using cardTheme in the Material ThemeData, but there is no corresponding cardTheme in CupertinoThemeData. So on iOS the Cards only use their default theme.

So how do I theme Material widgets like Card in Cupertino theme?

Solution

Faced the same issue I tried to play with MaterialBasedCupertinoThemeData https://api.flutter.dev/flutter/material/MaterialBasedCupertinoThemeData-class.html but it doesn’t respect the dark theme properly. Eventually, I’ve found a solution how to combine MaterialTheme with CupertinoTheme at the same time and apply dark/light theming correctly:

@override
Widget build(BuildContext context) {
  final Brightness platformBrightness = WidgetsBinding.instance!.window.platformBrightness;
  return Theme(
    data: ThemeData(brightness: platformBrightness),
    child: CupertinoApp(
      theme: CupertinoThemeData(
        brightness: platformBrightness,
      ),
    ),
  );
}

Answered By – myxrome

Answer Checked By – David Marino (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.