Home > Software design >  Keep global ThemeData across screens
Keep global ThemeData across screens

Time:10-03

Is it possible to set ThemeData globally so you don't have to on the next screens?

Currently after I use the Navigator.pushI have to make sure the new screen Widget have instructions like Theme.of(context).backgroundColor

Is there a way for the app screens/widgets to automatically pick whatever is set in the main.dart theme?

Eg, Here is my main.dart

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(backgroundColor: Colors.red, primaryColor: Colors.green),
      home: LoadingScreen(),
    );
  }
}

and this is the loadingscreen:

class _LoadingScreenState extends State<LoadingScreen> {
  @override
  void initState() {
    super.initState();
    getFiles();
  }

  void getFiles() async {
    await Future.delayed(Duration(seconds: 3));

    Navigator.push(context, MaterialPageRoute(builder: (context) {
      return StartScreen(file: null);
    }));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        color: Theme.of(context).backgroundColor,
        child: Center(
            child: Image.asset(
          height: 100.0,
        )),
      ),
    );
  }
}

Without a Theme.of(context).backgroundColor in the Container, the app will load a white page behind the image, instead of red as defined in the ThemeData.

Is that a way to avoid the extensive usage of Theme.of(context).backgroundColor everywhere?

CodePudding user response:

When you set the Scaffolds backgroundcolor in the ThemeData every Scaffold should use that color as a backgroundcolor. On your LoadingScreen the extra Container is unecessery since it would override the Scaffolds backgroundcolor.

Refer to this answer on how to set the backgroundcolor: https://stackoverflow.com/a/55581726/13406356

  • Related