**change the appbar title dynamically**
Getting appbar title from the database and then I have to set to appbar. I am new to flutter tried setState as well.
I have tried setState() as but still not working. how can i change the appbar text based on server response as well as database value
import 'dart:async'; import 'package:flutter/material.dart'; import 'package:parking_app/data/database_helper.dart'; import'package:parking_app/models/user.dart'; class HomeScreen extends StatefulWidget { @override State<StatefulWidget> createState() { return new HomeScreenState(); } } class HomeScreenState extends State<HomeScreen> { @override Widget build(BuildContext context) { 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(TAG+ " user data : " + val.emailId); setState(() { build(context); appBarTitle = val.emailId; }); }); }
return new MaterialApp( home: new Scaffold( appBar: new AppBar( title: appBarTitleText, actions: <Widget>[ // action button new IconButton( icon: new Icon(Icons.settings_power), onPressed: () { _logout(); }, ), // action button ], ), body: new Padding( padding: const EdgeInsets.all(16.0), child: new ChoiceCard(choice: choices[0]), ), ), ); } }
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) {
...