0

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?

Icaroto
  • 142
  • 10

1 Answers1

0

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

MindStudio
  • 706
  • 1
  • 4
  • 13
  • By removing the Scaffold (or moving it back to the main.dart) I can see the color in the background! Thanks! On top of that I noticed that the next screen (StartScreen called after a few secs) have a black background, is that caused by the ```MaterialPageRoute```, any way to say to the next to also goes with the Main theme? – Icaroto Oct 02 '22 at 16:26
  • ah, I think I got it, I added a Scaffold on top of the return, like ```return Scaffold(body: StartScreen(file: null));``` and the color of the background changed :) – Icaroto Oct 02 '22 at 16:56