Flutter 如何以编程方式更改AppBar标题?
一旦构建了屏幕,那么在某种逻辑之后,我需要在不再次执行build()方法的情况下更改AppBar标题。如何执行此操作?您可以在StatefulWidget内调用setState()方法并更改AppBar的标题。这就是你可以做到的:Flutter 如何以编程方式更改AppBar标题?,flutter,Flutter,一旦构建了屏幕,那么在某种逻辑之后,我需要在不再次执行build()方法的情况下更改AppBar标题。如何执行此操作?您可以在StatefulWidget内调用setState()方法并更改AppBar的标题。这就是你可以做到的: class HomePage extends StatefulWidget { _HomePageState createState() => _HomePageState(); } class _HomePageState extends State&l
class HomePage extends StatefulWidget {
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
String appBarTitle = "Title1";
void changeTitle(){
setState(() {
appBarTitle = appBarTitle=="Title1"?"Title2":"Title1";
});
}
@override
Widget build(BuildContext context) {
return Container(
child: Scaffold(
appBar: AppBar(
title: Text(appBarTitle),
),
floatingActionButton: FloatingActionButton(
onPressed: changeTitle,
),
),
);
}
}
类主页扩展StatefulWidget{
_HomePageState createState()=>\u HomePageState();
}
类_HomePageState扩展状态{
字符串appBarTitle=“Title1”;
void changeTitle(){
设置状态(){
appBarTitle=appBarTitle==“Title1”?“Title2”:“Title1”;
});
}
@凌驾
小部件构建(构建上下文){
返回容器(
孩子:脚手架(
appBar:appBar(
标题:文本(appBarTitle),
),
浮动操作按钮:浮动操作按钮(
按:更改标题,
),
),
);
}
}
在您的状态类中写入
String title_string = "your_initial_title";
在appbar中写入属性:
title: Text(title_string)
现在,每当您要更改标题时,请编写:
setState((){
title_string = "your_new_title";
});
这对我来说很有效 由kotlin用户使用
(requireActivity() as MainActivity).supportActionBar?.title = "New title"
对于java,使用这个
(( MainActivity) requireActivity()).getSupportActionBar().setTitle("New title");
AppBar的标题是一个小部件(通常是Text()),因此如果你想更改任何小部件,你必须重新执行build()。@stuckdorflow你说你不想
setState()
,你用同样的逻辑接受答案。