Menu
CoddyTech
flag Ar iconالعربيةdown icon

ألوان Theme.of(context)

جزء من قسم تصميم يتكيف مع الشاشة في رحلة Flutter على Coddy. الدرس 22 من 30.

تلتقط الأزرار السمة تلقائيًا. أما الحاويات الخاصة بك فلا تفعل ذلك: يظل Container الذي يستخدم Colors.teal.shade100 بهذا اللون مهما كانت السمة.

لتلوين عناصر الواجهة الخاصة بك من السمة، اقرأها باستخدام Theme.of(context):

final colors = Theme.of(context).colorScheme;

Container(
  color: colors.primaryContainer,
  child: Text('Hi', style: TextStyle(color: colors.onPrimaryContainer)),
)

تأتي منظومة الألوان في أزواج. primaryContainer هو لون تعبئة هادئ، وonPrimaryContainer هو لون النص على تلك التعبئة، وقد اختير ليكون سهل القراءة. وينطبق الأمر نفسه على primary وonPrimary، وsurface وonSurface.

يبحث Theme.of(context) عن السمة الموجودة أعلى عنصر الواجهة الذي يستدعيه. تُضبط السمة بواسطة MaterialApp، لذا يجب أن يكون context ضمن عنصر يقع أسفله، مثل build الخاص بـ HomeScreen. أما في build الخاص بـ MyApp نفسه، والذي يقع أعلى MaterialApp، فلن يجد سوى اللون الأرجواني الافتراضي في Flutter.

challenge icon

التحدي

سهل

لوّن الشريط باستخدام السمة، لكي يتبع أي لون أساسي تختاره:

  • في بداية build الخاصة بـ HomeScreen: final colors = Theme.of(context).colorScheme;
  • لون الشريط: colors.primaryContainer
  • لون نصه: colors.onPrimaryContainer

جرّب بنفسك

import 'package:flutter/material.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.teal),
      ),
      home: const HomeScreen(),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Bookshelf')),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            Container(
              width: double.infinity,
              padding: const EdgeInsets.all(24),
              decoration: BoxDecoration(
                color: Colors.teal.shade100,
                borderRadius: BorderRadius.circular(16),
              ),
              child: Text(
                'You read 12 books this year',
                style: TextStyle(fontSize: 20, color: Colors.teal.shade900),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
quiz iconاختبر نفسك

يتضمن هذا الدرس اختبارًا قصيرًا. ابدأ الدرس للإجابة عليه وتتبّع تقدمك.

جميع دروس تصميم يتكيف مع الشاشة

تدرّب بنفسك: مترجم Flutter عبر الإنترنت