Some parts of my app use a different color scheme, but the color change is not applied to the date picker widget.
Is it another theme bug? How to fix it?
import 'package:flutter/material.dart';
main() {
runApp(
MaterialApp(
theme: ThemeData(
colorScheme: ColorScheme.light(
primary: Colors.red,
secondary: Colors.red,
),
// https://stackoverflow.com/a/72808301
toggleableActiveColor: Colors.red,
),
home: _TestTheme1(),
),
);
}
class _TestTheme1 extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Red?')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
_TestWidgets(),
FloatingActionButton(
child: Icon(Icons.arrow_forward),
onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (context) {
return _TestTheme2();
}));
},
),
],
),
),
);
}
}
class _TestTheme2 extends StatelessWidget {
@override
Widget build(BuildContext context) {
var theme = ThemeData(
colorScheme: ColorScheme.light(
primary: Colors.green,
secondary: Colors.green,
),
// https://stackoverflow.com/a/72808301
toggleableActiveColor: Colors.green,
);
var child = Scaffold(
appBar: AppBar(title: Text('Green?')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
_TestWidgets(),
ElevatedButton(
child: Text('Pick date'),
onPressed: () {
var now = DateTime.now();
// BUG: Should be green, not red!
showDatePicker(
context: context,
initialDate: now,
firstDate: DateTime(now.year - 1, now.month, now.day),
lastDate: DateTime(now.year 1, now.month, now.day),
);
},
),
],
),
),
);
return Theme(data: theme, child: child);
// return MaterialApp(theme: theme, home: child);
}
}
class _TestWidgets extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Column(
children: [
Checkbox(value: true, onChanged: (value) {}),
Switch(value: true, onChanged: (value) {}),
],
);
}
}
CodePudding user response:
The fix is to add a Builder
so that showDatePicker
gets the right themed context.
In _TestTheme2
just replace Scaffold(...)
with Builder(builder: (context) => Scaffold(...))
and voilà.
CodePudding user response:
Move the Theme(data: theme, child: child);
to the builder
property of showDatPicker
.
Something like below
showDatePicker(
context: context,
initialDate: now,
firstDate: DateTime(now.year - 1, now.month, now.day),
lastDate: DateTime(now.year 1, now.month, now.day),
builder: (context, child) {
return Theme(data: theme, child: child);
},
);