【发布时间】:2020-05-01 20:15:59
【问题描述】:
Flutter 会自动为可以弹出的路由提供后退按钮,但是如何在整个应用中更改后退按钮图标主题?
比如如何将正常材质的后退图标改为chevron?
【问题讨论】:
Flutter 会自动为可以弹出的路由提供后退按钮,但是如何在整个应用中更改后退按钮图标主题?
比如如何将正常材质的后退图标改为chevron?
【问题讨论】:
创建不带 Scafold 的页面并使用此方法在路线之间导航。
navigateToRoute(BuildContext context, Widget page,String title) {
Navigator.push(context, MaterialPageRoute(builder: (context) => Scaffold(
appBar: AppBar(
leading:Icon(Icons.chevron_left),
title: Text(title),
),
body: page,
)));
}
【讨论】:
在这种情况下,您必须创建一个自定义 BackButton。我建议您可以创建一个customAppBar 方法并在任何地方使用它。
查看下面的代码。
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: ScreenOne(),
);
}
}
class ScreenOne extends StatefulWidget {
@override
_ScreenOneState createState() => _ScreenOneState();
}
class _ScreenOneState extends State<ScreenOne> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: customAppBar(title: Text("Screen One")),
body: Center(
child: RaisedButton(onPressed: () {
Navigator.of(context).push(MaterialPageRoute(builder: (_) => ScreenTwo()));
}),
),
);
}
}
class ScreenTwo extends StatefulWidget {
@override
_ScreenTwoState createState() => _ScreenTwoState();
}
class _ScreenTwoState extends State<ScreenTwo> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: customAppBar(
customBackButton: true,
title: Text("Screen Two"),
),
);
}
}
AppBar customAppBar({
Widget title,
bool customBackButton = false,
}) {
return AppBar(
leading: customBackButton ? CustomBackButton() : null,
title: title,
);
}
class CustomBackButton extends StatelessWidget {
const CustomBackButton({Key key, this.color, this.onPressed}) : super(key: key);
final Color color;
final Function onPressed;
@override
Widget build(BuildContext context) {
assert(debugCheckHasMaterialLocalizations(context));
return IconButton(
icon: Icon(Icons.arrow_back_ios),
color: color,
tooltip: MaterialLocalizations.of(context).backButtonTooltip,
onPressed: () {
if (onPressed != null) {
onPressed();
} else {
Navigator.maybePop(context);
}
},
);
}
}
希望对你有帮助:)
【讨论】:
ThemeData() 中还有其他方法吗?
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
appBarTheme: AppBarTheme(
iconTheme: IconThemeData(
color: Colors.black,
),
),
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);[![Initially didn't put any color so it was white[![This is the image when I added appbartheme and changed color to black][1]][1]][1]
【讨论】:
IconThemeData()方法只自定义color、size和opacity但是我想改变图标