0

So I am completely new to flutter, and want create an app.

I found that you can define a theme for the entire app, so I want to give it a go.

Unfortunately though I don't seem to have any real control of it. For example I can't seem to change the color of "Hello world". It just ends up gray.

If I change it in the style to something hardcoded ex Colors.amber then it works, but I would prefer to set it via the theme, which I assume is possible?

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(
          seedColor: Colors.white10,
          brightness: Brightness.dark,
        ),

        textTheme: TextTheme(
          titleLarge: GoogleFonts.inter(fontSize: 30, color: Colors.orange),
        ),
      ),
      home: Scaffold(
        body: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 32),
          child: Column(
            children: [
              Text(
                "Hello world",
                style: Theme.of(context).textTheme.titleLarge!,
              ),
            ],
          ),
        ),
      ),
    );
  }

So that is what I have now. What am I not understanding about the colors? why isn't the text orange?

4
  • 1
    Theme.of(context) actually gets from parent context, currently it is within the same context level, 1. you can move the MaterialApp(ThemeData on parent, or wrap with a Builder widget which will provide separate context . home: Builder( builder: (BuildContext context) => Scaffold( Commented Sep 21 at 13:53
  • ah, you are right. finally makes some sense :) Commented Sep 21 at 13:57
  • @Md.YeasinSheikh Can you post an answer, so we can bring closure here in a way that the system also recognizes? Commented Sep 21 at 14:29
  • ok will try that but I was thinking to encourage new comers while I may not be active as past. Commented Sep 23 at 14:22

1 Answer 1

0

When you use "MaterialApp", the "theme" is defined there.

If you try to access "Theme.of(context)" too early (like directly in the "home" widget), the context doesn't yet have access to the new theme.

To solve this, use a Builder widget:

home: Builder(
  builder: (context) {
    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 32),
        child: Column(
          children: [
            Text(
              "Hello world",
              style: Theme.of(context).textTheme.titleLarge!,
            ),
          ],
        ),
      ),
    );
  },
),
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.