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

问题描述 投票:3回答:3
**change the appbar title dynamically**

从数据库获取appbar标题,然后我必须设置为appbar。我也是新手,也尝试了setState。

我已经尝试过setState()但仍然没有工作。如何根据服务器响应和数据库值更改appbar文本

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]),
    ),
  ),
);   } }
flutter appbar
3个回答
3
投票

您也可以拆分代码,假设您的数据库提取是异步的。

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) {
    ...

2
投票

你不应该在构建函数中做所有事情。每次调用setState时都会重新绘制构建函数,因此每次重绘时都会启动String appBarTitle = "eClerx Parking";

您需要覆盖initState()并将此逻辑放在那里

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;
    });
  });

另外,使用setState()函数包装appBarTitle = val.emailId;

编辑:您没有等待dababase Future<User> user = db.getUser();的结果,因此用户将始终为null并且从未调用setState。

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


0
投票

更改

appBarTitle = val.emailId

setState(() {
  appBarTitle = val.emailId;
});
© www.soinside.com 2019 - 2024. All rights reserved.