Search code examples
flutterdarttext-sizebold

How to restrict bold text and text size in specific page in Flutter


I follow this stack overflow link to restrict bold text globally on whole app. Now when i try to implement this to restrict bold text as well as to restrict big text size on specific screen then only one restriction works. Means if i put restrict bold text first and restrict big text size second then restrict bold text doesn't work and if i put restrict big text size first and restrict bold text second then restrict bold text works how to solve this issue? Below is the sample dart code till now i what i have tried.

main.dart

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(''),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Center(child: Text('Text')),
          const SizedBox(
            height: 50.0,
          ),
          Center(
            child: TextButton(
                onPressed: () {
                  Navigator.of(context).push(MaterialPageRoute(
                      builder: (context) => const NextPage()));
                },
                child: const Text('Move')),
          )
        ],
      ),
    );
  }
}

class NextPage extends StatefulWidget {
  const NextPage({Key? key}) : super(key: key);

  @override
  _NextPageState createState() => _NextPageState();
}

class _NextPageState extends State<NextPage> {
  @override
  Widget build(BuildContext context) {
    return MediaQuery(
      data: MediaQueryData.fromWindow(WidgetsBinding.instance!.window)
          .copyWith(boldText: false), // Restrict bold text
      child: MediaQuery(
        data: MediaQuery.of(context).copyWith(textScaleFactor: 1.5), // Restrict bigger text size
        child: Scaffold(
          appBar: AppBar(
            title: const Text(''),
          ),
          body: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: const [
              Center(child: Text('Text')),
            ],
          ),
        ),
      ),
    );
  }
}

Solution

  • you have two options to achieve your goal.

    1 - use only one MediaQuery and put all your settings in that like: .copyWith(boldText: false, textScaleFactor: 1.5)

    2 - wrap your inner MediaQuery in a Builder.