Menu
CoddyTech

Màu sắc Theme.of(context)

Thuộc phần Bố cục phù hợp với mọi màn hình trong hành trình Flutter của Coddy. Bài học 22 trên 30.

Các nút tự lấy màu theo giao diện. Các hộp do bạn tạo thì không: Container có Colors.teal.shade100 vẫn giữ nguyên màu đó bất kể giao diện là gì.

Để tô màu cho các widget do bạn tạo theo giao diện, hãy đọc màu bằng Theme.of(context):

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

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

Bảng màu có các cặp màu. primaryContainer là màu nền dịu, còn onPrimaryContainer là màu chữ trên nền đó, được chọn để dễ đọc. Tương tự với primary và onPrimary, surface và onSurface.

Theme.of(context) tìm giao diện phía trên widget đưa ra yêu cầu. MaterialApp thiết lập giao diện, vì vậy context phải nằm bên dưới nó, chẳng hạn như trong build của HomeScreen. Trong build riêng của MyApp, nằm phía trên MaterialApp, nó chỉ tìm thấy màu tím mặc định của Flutter.

challenge icon

Thử thách

Dễ

Tô màu biểu ngữ theo chủ đề để biểu ngữ thay đổi theo mọi seed bạn chọn:

  • ở đầu build của HomeScreen: final colors = Theme.of(context).colorScheme;
  • màu của biểu ngữ: colors.primaryContainer
  • màu chữ của biểu ngữ: colors.onPrimaryContainer

Tự làm thử

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 iconTự kiểm tra

Bài học này có một bài trắc nghiệm ngắn. Bắt đầu bài học để trả lời và theo dõi tiến độ.

Tất cả bài học trong Bố cục phù hợp với mọi màn hình

Tự luyện tập: Trình biên dịch Flutter online