EN VI

textTheme not set to text style flutter?

2024-03-10 06:30:04
How to textTheme not set to text style flutter

Im trying to set textTheme on Text using style parameter of Text() like below:

Text('Hello Flutter',style: Theme.of(context).textTheme.bodyMedium)

but it is not working and this is the result: 1

but when i don't set style it will work: 2

The problem is, i want to set bodyMedium on my Text(style: ) but it did not work. This is the whole code:

Widget build(BuildContext context) {
    final TextStyle defaultTextStyle = TextStyle(fontFamily: 'IranYekan');
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: ThemeData(
        textTheme: TextTheme(
          bodyMedium: defaultTextStyle.copyWith(fontWeight: FontWeight.w900, fontSize: 50),
          bodySmall: defaultTextStyle.copyWith(fontSize: 40),
        ),
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home:  Scaffold(
        body: Center(
            child:  Text('Hello Flutter',style: Theme.of(context).textTheme.bodyMedium)),
        ),
      ),
    );
  }

What is the problem? how can i solve this?

Solution:

It may be due to the context not having the updated ThemeData when it’s being used. In Flutter, the context in the widget tree doesn’t immediately have access to the changes above it. When you use build(context), it provides the context that contains the updated ThemeData.

To ensure that the Text widget uses the updated theme, you can wrap it in a Builder widget, which provides a new BuildContext that has access to the updated theme. Here’s how you can modify your code:

home: Builder(builder: (context) {
 return Scaffold(
  body: Center(
   child: Text('Hello Flutter',
    style: Theme.of(context).textTheme.bodyMedium)),
   );
}),

or create a custom widget like:

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
          child: Text('Hello Flutter',
              style: Theme.of(context).textTheme.bodyMedium)),
    );
  }
}
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login