如何在Flutter中更改应用栏标题

AKA*_*WAR 6 appbar flutter

**change the appbar title dynamically**
Run Code Online (Sandbox Code Playgroud)

从数据库中获取appbar标题,然后将其设置为appbar。我也是第一次尝试setState。

我已经尝试过setState(),但仍然无法正常工作。如何根据服务器响应以及数据库值更改应用栏文本

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);
Run Code Online (Sandbox Code Playgroud)
if (user != null) {
  user.then((val) {
    if (val == null) {
      return;
    }
    print(TAG+ "  user data : " + val.emailId);
    setState(() {
      build(context);
      appBarTitle = val.emailId;
    });
  });
}
Run Code Online (Sandbox Code Playgroud)
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]),
    ),
  ),
);   } }
Run Code Online (Sandbox Code Playgroud)

Zro*_*roq 6

您还可以拆分代码,假设您的数据库获取将是异步的。

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) {
    ...
Run Code Online (Sandbox Code Playgroud)