Below is a simple screen with three buttons with different colored themes what I want is when any of each button pressed detail screen should use that theme.
also, I don't what to change the theme of MaterialAppWidget because it's used in other places just this details screen needs to be themed according to which button it opened.
import 'package:flutter/material.dart';
main() => runApp(const App());
class App extends StatelessWidget {
const App({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) => MaterialApp(
home: const HomeScreen(),
theme: ThemeData(
primaryColor: Colors.orange,
colorScheme: ColorScheme.fromSwatch(primarySwatch: Colors.orange),
),
);
}
class HomeScreen extends StatelessWidget {
const HomeScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Center(
child: Wrap(
spacing: 20,
direction: Axis.vertical,
children: const [
ThemedButton(
materialColor: Colors.red,
),
ThemedButton(
materialColor: Colors.green,
),
ThemedButton(
materialColor: Colors.brown,
),
],
),
),
);
}
}
class ThemedButton extends StatelessWidget {
final MaterialColor materialColor;
const ThemedButton({
Key? key,
required this.materialColor,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Theme(
data: Theme.of(context).copyWith(
primaryColor: materialColor,
colorScheme: ColorScheme.fromSwatch(primarySwatch: materialColor),
),
child: ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const DetailScreen(),
),
);
},
child: const Text('Go to Detail Screen'),
),
);
}
}
class DetailScreen extends StatelessWidget {
const DetailScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
);
}
}
CodePudding user response:
Would something like this work for you?
class ThemedButton extends StatelessWidget {
final MaterialColor materialColor;
const ThemedButton({Key? key, required this.materialColor}) : super(key: key);
@override
Widget build(BuildContext context) {
return ElevatedButton(
style: ElevatedButton.styleFrom(
primary: materialColor
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Theme(
data: Theme.of(context).copyWith(
primaryColor: materialColor,
colorScheme: ColorScheme.fromSwatch(primarySwatch: materialColor),
),
child: const DetailScreen()
)
),
);
},
child: const Text('Go to Detail Screen'),
);
}
}
I'm wrapping the Elevated Button in a Builder Widget to use the new BuildContext theme to pass down.