Pat*_*ick 5 themes routes dart material-ui flutter
我的应用程序有不同的部分,我希望它们有不同的主题颜色,包括导航中的所有子路线。
但如果我使用主题,它不会应用于子路线中的小部件。我还尝试使用嵌套的 MaterialApps,但这不起作用,因为我无法弹回到根菜单。我不想将颜色参数传递给所有屏幕。我应该怎么办?
这是一个测试代码:
import 'package:flutter/material.dart';
main() {
runApp(MaterialApp(home: _Test()));
}
class _Test extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ElevatedButton(
child: Text('Red section'),
onPressed: () {
Navigator.push(context, MaterialPageRoute(
builder: (context) {
return Theme(
data: ThemeData(colorScheme: ColorScheme.light(primary: Colors.red)),
child: _TestSubRoute(),
);
},
));
},
),
const SizedBox(height: 16),
ElevatedButton(
child: Text('Green section'),
onPressed: () {
Navigator.push(context, MaterialPageRoute(
builder: (context) {
return Theme(
data: ThemeData(colorScheme: ColorScheme.light(primary: Colors.green)),
child: _TestSubRoute(),
);
},
));
},
),
],
),
),
);
}
}
class _TestSubRoute extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Theme.of(context).colorScheme.primary.withOpacity(0.2),
appBar: AppBar(
title: Text('Should keep the same color through the navigation...'),
actions: [
IconButton(
icon: Icon(Icons.help),
onPressed: () {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text('Hello'),
actions: [
TextButton(
child: Text('OK'),
onPressed: () => Navigator.pop(context),
),
],
);
},
);
},
),
],
),
body: Center(
child: ElevatedButton(
child: Text('Push...'),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => _TestSubRoute()),
);
},
),
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
这是我最终找到的解决方案。每个部分都位于具有自己的 ThemeData 的 MaterialApp 中。要返回根屏幕,我使用 BackButton
Navigator.of(context, rootNavigator: true).pop()
与其他解决方案相反,这并不强制更改所有子屏幕,而仅更改每个部分的第一个屏幕。
| 归档时间: |
|
| 查看次数: |
3343 次 |
| 最近记录: |