Change Material Theme color scheme programmatically

It is possible to change the colour scheme in code, with a little ingenuity!

You can do it by dynamically updating the CSS. I’ve assembled an app to show you how you can do that, with code you can copy into your own apps. Here’s the clone link:

https://anvil.works/build#clone:6DIBMMLRAVNSXNBM=KCVZYQKMYH4VW62NABALWTKY

How it works:

  • The ColourChanger module contains some CSS - I got it by taking theme.css and picking every rule that had a %color substitution
  • The set_theme() function takes that CSS, and substitutes in values for colours such as Primary 500 . It then passes this assembled CSS to the setThemeCss() function, which is written in Javascript.
  • The setThemeCss() function, which lives in a <script> tag under Native Libraries, is a two-line JS function that inserts a new <style> tag into your page, containing the new colour-changing CSS your Python has assembled.
  • Form1 shows you how to use this - it’s really simple! Just assemble a dict with the theme colours you want, and call set_theme()
6 Likes