रंगों और टाइपोग्राफ़ी को ThemeData में केंद्रीकृत करें, ColorScheme.fromSeed से एक Material 3 पैलेट उत्पन्न करें, और बिना किसी मेहनत के एक डार्क मोड प्रदान करें।
इस पाठ को Kodokon में खोलेंविजेट-दर-विजेट स्टाइलिंग करना बंद कर देना एक पेशेवर मील का पत्थर है: ThemeData पूरे ऐप के लिए रंगों, टाइपोग्राफ़ी और आकृतियों को केंद्रीकृत करता है। Material 3 के साथ (Flutter 3.16 से डिफ़ॉल्ट रूप से सक्षम), सब कुछ ColorScheme से शुरू होता है: ColorScheme.fromSeed एक अकेले सीड रंग से एक संपूर्ण, सामंजस्यपूर्ण और सुलभ पैलेट प्राप्त करता है।
import 'package:flutter/material.dart';
void main() {
runApp(const ShopApp());
}
class ShopApp extends StatelessWidget {
const ShopApp({super.key});
@override
Widget build(BuildContext context) {
const seed = Colors.teal;
return MaterialApp(
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(
seedColor: seed,
),
),
darkTheme: ThemeData(
colorScheme: ColorScheme.fromSeed(
seedColor: seed,
brightness: Brightness.dark,
),
),
themeMode: ThemeMode.system,
home: Scaffold(
appBar: AppBar(title: const Text('Shop')),
body: const Center(child: Text('Welcome')),
),
);
}
}अपने विजेट के अंदर, कुछ भी नए सिरे से न बनाएँ: Theme.of(context) से परिवेशी थीम पढ़ें। colorScheme अर्थपूर्ण भूमिकाएँ (primary, onPrimary, primaryContainer, surface, इत्यादि) उजागर करता है और textTheme नामित शैलियाँ (titleMedium, bodyLarge, इत्यादि) उजागर करता है। इस तरह लिखा गया विजेट लाइट थीम के साथ-साथ डार्क थीम के अनुसार भी अपने आप ढल जाता है।
import 'package:flutter/material.dart';
class PriceTag extends StatelessWidget {
const PriceTag({super.key, required this.price});
final double price;
@override
Widget build(BuildContext context) {
final colors = Theme.of(context).colorScheme;
final text = Theme.of(context).textTheme;
return Container(
padding: const EdgeInsets.symmetric(
horizontal: 12,
vertical: 6,
),
decoration: BoxDecoration(
color: colors.primaryContainer,
borderRadius: BorderRadius.circular(8),
),
child: Text(
'$price €',
style: text.titleMedium?.copyWith(
color: colors.onPrimaryContainer,
),
),
);
}
}और आगे जाने के लिए, कंपोनेंट थीम को कॉन्फ़िगर करें: विजेट का हर परिवार (ऐप बार, बटन, इनपुट फ़ील्ड) ThemeData में एक समर्पित थीम स्वीकार करता है। आप अपने बटनों की पैडिंग या अपने शीर्षकों के केंद्रीकरण को एक बार परिभाषित करते हैं, और हर इंस्टेंस इसे बिना किसी अकेली लोकल स्टाइल के विरासत में पा लेता है।
import 'package:flutter/material.dart';
final ThemeData appTheme = ThemeData(
colorScheme: ColorScheme.fromSeed(
seedColor: Colors.teal,
),
appBarTheme: const AppBarTheme(
centerTitle: true,
elevation: 0,
),
filledButtonTheme: FilledButtonThemeData(
style: FilledButton.styleFrom(
padding: const EdgeInsets.symmetric(
horizontal: 24,
vertical: 12,
),
),
),
);