在Flutter中动态更改AppBar标题

时间:2020-09-29 19:28:45

标签: flutter dart

我在另一个类中有一个可重复使用的AppBar小部件。必须通过API响应设置应用栏标题。设置appBar标题后,所有屏幕的标题都应该相同。

AppBar.dart

import 'package:flutter/material.dart';

class CustomAppBar extends StatefulWidget implements PreferredSizeWidget {
  CustomAppBar({Key key})
      : preferredSize = Size.fromHeight(kToolbarHeight),
        super(key: key);

  @override
  final Size preferredSize; // default is 56.0

  @override
  _CustomAppBarState createState() => _CustomAppBarState();
}

class _CustomAppBarState extends State<CustomAppBar> {
  @override
  Widget build(BuildContext context) {
    return AppBar(
      title: Text('Emotely'),
      flexibleSpace: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            colors: [themeColor, themeColorLight],
          ),
        ),
      ),
    );
  }
}

MainScreen.dart

//api response

    upload(String base64Image) {
        var body = jsonEncode({"image": base64Image});
        http
            .post(api, headers: {"Content-Type": "application/json"}, body: body)
            .then((result) {
          print(result.body);
          setStatus(result.statusCode == 200 ? result.body : errMessage);
        })

@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CustomAppBar(), //Need to change the AppBar Title here
      body: Container(
        padding: EdgeInsets.all(30.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[]

1 个答案:

答案 0 :(得分:0)

您可以将最终变量添加到自定义应用栏

class CustomAppBar extends StatefulWidget implements PreferredSizeWidget {

  CustomAppBar(String title) {
    this.preferredSize = Size.fromHeight(kToolbarHeight);
    this.title = title; // <-- add This
  }

  @override
  final Size preferredSize; // default is 56.0
  final String title // <-- Add this 

  @override
  _CustomAppBarState createState() => _CustomAppBarState();
}

现在在_CustomAppBarState内使用widget.title。 例如:

 Widget build(BuildContext context) {
 return AppBar(
  title: Text(widget.title), // <-- add this
 .....
 .....

现在在您的主要状态完整小部件类中声明一个String变量:

String myAppBarTitle = ""; // <-- Add this

@override
Widget build(BuildContext context) {
return Scaffold(
  appBar: CustomAppBar(myAppBarTitle), // <-- Add this
  .....
  .....
  ) 
};

只要想更改标题,只需使用setState:

setState(() {
  myAppBarTitle = "some new title";
});

我也建议将自定义应用栏更改为状态较少小部件,因为据我所知,您并未更改应用栏的状态。