How to change the app bar title in flutter

You shouldn't do everything in the build function. The build function is redrawing everytime you call setState, so you are initiating String appBarTitle = "eClerx Parking"; every time it redraws.

You need to override the initState() and place this logic in there

var db = new DatabaseHelper();
    Future<User> user = db.getUser();
    String appBarTitle = "eClerx Parking";
    var appBarTitleText = new Text(appBarTitle);


if (user != null) {
  user.then((val) {
    if (val == null) {
      return;
    }
    print("user data : " + val.emailId);
    //DO THIS TO UPDATE THE STATE AND FORCE A REDRAW
    setState(() {
      appBarTitle = val.emailId;
    });
  });

Also, wrap appBarTitle = val.emailId; with setState() function

EDIT: You are not awaiting the result from the dababase Future<User> user = db.getUser(); so the user will always be null and setState never called.

Try Future<User> user = await db.getUser();


You could also split your code, assuming that your database fetch will be asynchronous.

class HomeScreenState extends State<HomeScreen> {
     var appBarTitleText = new Text("eClerx Parking");

     Future getUser() async {
        var user = await db.getUser();

        if (user != null) {
           user.then((val) {
              if (val == null) {
                return;
              }
              print("user data : " + val.emailId);

              setState(() {
                appBarTitleText = Text(val.emailId);
             });
           });
        }
    }


    @override
       void initState() {
       super.initState();
       getUser();
    }

    @override
    Widget build(BuildContext context) {
    ...

Tags:

Appbar

Flutter