Reputation: 3767
Once the screen is built then somehow after some logic I need to change the AppBar title without executing build() method again. How to do this?
Upvotes: 4
Views: 5164
Reputation: 5968
You can call setState() method inside StatefulWidget and change the title of AppBar. This is how you can do it:
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,
),
),
);
}
}
Upvotes: 7
Reputation: 3094
This works for me
Use it by kotlin user
(requireActivity() as MainActivity).supportActionBar?.title = "New title"
And for java use this one
(( MainActivity) requireActivity()).getSupportActionBar().setTitle("New title");
Upvotes: -4
Reputation: 3892
in your State class write
String title_string = "your_initial_title";
In your appbar write the property:
title: Text(title_string)
Now whenever you want to change the title write:
setState((){
title_string = "your_new_title";
});
Upvotes: 2