Flutter text size

210 views Asked by At

I want to have button that will resize font size across my entire aplication. I want to change size of every text from 100% of size that I already have to 200%. Android accessibility already does that. Android have "fint size" changing it will resize every text in my application. I need a button that will do something similar.

https://support.google.com/accessibility/android/answer/11183305?hl=en

2

There are 2 answers

0
Autocrab On

You can wrap your application with MediaQuery

    MediaQuery(
      data: MediaQuery.of(context).copyWith(
        textScaleFactor: myTextScaleFactor, //1 - 100%, 1.5 - 150% ... etc
      ),
      child: Container(),
    ); 

Change textScaleFactor on button press and pass it to this widget.

0
Rahul On

You can override the default behaviour with following code.


import 'package:flutter/material.dart';

void main() {
  runApp(
    MaterialApp(
      theme: ThemeData.from(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.purple),
        useMaterial3: true,
      ),
      home: const Home(),
    ),
  );
}

class Home extends StatefulWidget {
  const Home({super.key});

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  double? _textScaleFactor;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _textScaleFactor ??= 1.0;
  }

  @override
  Widget build(BuildContext context) {
    return MediaQuery(
      data: MediaQuery.of(context)
          .copyWith(textScaler: TextScaler.linear(_textScaleFactor ?? 1.0)),
      child: Scaffold(
        appBar: AppBar(
          title: const Text('Text Scaling'),
          actions: [
            IconButton(
                onPressed: () {
                  setState(() {
                    _textScaleFactor = (_textScaleFactor ?? 1.0) + 0.1;
                  });
                },
                icon: const Icon(Icons.arrow_upward)),
            IconButton(
              onPressed: () {
                setState(() {
                  _textScaleFactor = (_textScaleFactor ?? 1.0) - 0.1;
                });
              },
              icon: const Icon(Icons.arrow_downward),
            )
          ],
        ),
        body: Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Builder(builder: (context) {
                return Text(
                    'Scaling factor: ${MediaQuery.of(context).textScaler}');
              }),
              const Text(
                'Hello World',
                style: TextStyle(fontSize: 20),
              ),
              ElevatedButton(onPressed: () {}, child: const Text('Button'))
            ],
          ),
        ),
      ),
    );
  }
}