Flutter uses the background color for the body but the onSurface for the text

175 Views Asked by At

i am new to flutter and i created an app with a Scaffold containing an appBar, a body and a drawer. I created my own ColorScheme with custom colors.

Now in the widget that i use as body for my Scaffold, flutter automatically uses the 'background'-color of my scheme as backgroundCOlor, which is fine. But for the Textcomponents inside that widget it uses the onSurface color as text color. Shouldn't it use the onBackground color?

edit: i created a simple example to show my confusion. Yes i know i can set the color of Text component individually, but i don't see why that should be necessary. I want to understand why flutter uses the 'onSurface' color on the 'background' color:

import 'package:flutter/material.dart';

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

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

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: const ColorScheme(
          primary: Colors.black,
          onPrimary: Colors.white,
          secondary: Colors.black,
          onSecondary: Colors.white,
          tertiary: Colors.black,
          onTertiary: Colors.white,
          background: Colors.blue,
          onBackground: Colors.red,
          surface: Colors.green,
          onSurface: Colors.yellow,
          brightness: Brightness.dark,
          error: Colors.transparent,
          onError: Colors.red,//
        ),
        useMaterial3: true,
      ),
      home: MyHomePage(),
    );
  }
}


class MyHomePage extends StatefulWidget {
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(title: Text('My Title'),),
      body: SafeArea(
        child: Center (
          child: Text('Some example text'),
        ),
      ),
    );
  }
}

in this example flutter automatically uses the followings colors: AppBar: backgroundColor: scheme.surface(green), textColor: scheme.onSurface(yellow) body(Center): backgroundColor:scheme.background(blue), textColor:scheme.onSurface(yellow)

1

There are 1 best solutions below

3
WizardKing On

onSurface is designed to provide high contrast against surface (background) color.

It make sures that text is readable, even with different background color.

You can change text color based onBackground

return Center(
 child: Column(
   children: [
     Text(
       'Some Text:',
       style: TextStyle(color: Theme.of(context).colorScheme.onBackground),
     ),
   ],
 ),
);