简体   繁体   English

Flutter 更新 Appbar 中的文本

[英]Flutter update the text in Appbar

I need help with updating the Text in the Appbar to match the page that I'm currently am at.我需要帮助更新 Appbar 中的文本以匹配我当前所在的页面。

So if I'm in the Settings Page then I need to display that in the AppBar text.所以如果我在设置页面中,那么我需要在 AppBar 文本中显示它。

I'm adding my code and screenshot to better explain what I want to achieve.我正在添加我的代码和屏幕截图以更好地解释我想要实现的目标。

第一张图片

第二张图片

Main.dart Main.dart

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // This will change the statusbar text color.
    FlutterStatusbarcolor.setStatusBarWhiteForeground(false);

    return ChangeNotifierProvider<ThemeChanger>(
      create: (_) => ThemeChanger(CustomThemes.lightTheme.copyWith(
          textTheme:
              CustomThemes.textTheme(CustomThemes.lightTheme.textTheme))),
      child: MaterialAppWithTheme(),
    );
  }
}

class MaterialAppWithTheme extends StatefulWidget {
  @override
  _MaterialAppWithTheme createState() => _MaterialAppWithTheme();
}

class _MaterialAppWithTheme extends State<MaterialAppWithTheme> {

  var appTitle = 'Material Design';

  @override
  Widget build(BuildContext context) {
    final theme = Provider.of<ThemeChanger>(context);

    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: appTitle,
      theme: theme.getTheme(),
      home: Scaffold(
        appBar: AppBar(
          title: Text(
            appTitle,
            style: TextStyle(color: CustomColors().novaWhite),
          ),
        ),
        body: BlocProvider<MdNavBloc>(
          create: (context) => MdNavBloc(),
          child: Stack(
            children: <Widget>[
              BlocBuilder<MdNavBloc, NavigationStates>(
                builder: (context, state) {
                  if (state is DashboardState) {
                    return DashBoardPage();
                  } else if (state is ExpensesState) {
                    return ExpensesPage();
                  } else if (state is NotificationsState) {
                    return NotificationsPage();
                  } else if (state is ErrorsState) {
                    return ErrorsPage();
                  } else if (state is SettingsState) {
                    return SettingsPage();
                  } else {
                    return DashBoardPage();
                  }
                },
              ),
              MdDrawer(title: appTitle, updateAppBarTitle: _updateAppBarTitle,),
            ],
          ),
        ),
      ),
    );
  }

  void _updateAppBarTitle(String newTitle) {
    setState(() {
      appTitle = newTitle;
    });
  }
}

MdDrawer.dart MdDrawer.dart

class MdDrawer extends StatefulWidget {
  final String title;
  final Function(String) updateAppBarTitle;

  MdDrawer({Key key, this.title, @required this.updateAppBarTitle}) : super(key: key);

  @override
  MdDrawerState createState() {
    return new MdDrawerState();
  }
}

class MdDrawerState extends State<MdDrawer>
    with SingleTickerProviderStateMixin {
  bool isCollapsed = true;
  AnimationController _animationController;
  Animation<double> widthAnimation;
  int currentSelectedIndex = 0;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      vsync: this,
      duration: Duration(milliseconds: 300),
    );
    widthAnimation = Tween<double>(
      begin: Constants.minWidth,
      end: Constants.maxWidth,
    ).animate(_animationController);
  }

  @override
  Widget build(BuildContext context) {
    final MdNavBloc bloc = BlocProvider.of<MdNavBloc>(context);

    return AnimatedBuilder(
      animation: _animationController,
      builder: (context, widget) => getWidget(bloc, context, widget),
    );
  }

  Widget getWidget(MdNavBloc bloc, context, widget) {
    return Material(
      //elevation: 80.0,
      child: Container(
        width: widthAnimation.value,
        //color: drawerBackgroundColor,
        color: Theme.of(context).backgroundColor,
        child: Column(
          children: <Widget>[
            Container(
              margin: EdgeInsets.symmetric(
                vertical: Constants.containerMargin,
              ),
              child: MdListTile(
                title: 'Jaser Jsk',
                icon: Icons.person,
                animationController: _animationController,
              ),
            ),

            Divider(color: Colors.grey, height: 20.0),

            SizedBox(
              height: 8.0,
            ),
            Expanded(
              child: ListView.separated(
                separatorBuilder: (context, counter) {
                  return Divider(height: 12.0);
                },
                itemBuilder: (context, counter) {
                  return MdListTile(
                    onTap: () {

                      widget.updateAppBarTitle(navigationItems[counter].title);

                      setState(() {
                        bloc.add(navigationItems[counter].navigationEvent);
                        currentSelectedIndex = counter;

                        isCollapsed = !isCollapsed;
                        _animationController.reverse();
                      });
                    },
                    isSelected: currentSelectedIndex == counter,
                    title: navigationItems[counter].title,
                    icon: navigationItems[counter].icon,
                    animationController: _animationController,
                  );
                },
                itemCount: navigationItems.length,
              ),
            ),
            InkWell(
              onTap: () {
                setState(() {
                  isCollapsed = !isCollapsed;
                  isCollapsed
                      ? _animationController.reverse()
                      : _animationController.forward();
                });
              },
              child: AnimatedIcon(
                icon: AnimatedIcons.menu_close,
                progress: _animationController,
                color: Theme.of(context).accentColor,
                size: 40.0,
              ),
            ),
            SizedBox(
              height: 20.0,
            ),
          ],
        ),
      ),
    );
  }
}

You can update the text in the AppBar widget in the MaterialAppWithTheme by having a method that updates the text in the MaterialAppWithTheme and passing that as a callback to the MdDrawerState and executing that when you change the drawer item.您可以更新文本AppBar在widget MaterialAppWithTheme由具有在更新文本的方法MaterialAppWithTheme ,并将其作为一个回调到MdDrawerState和执行,当你改变抽屉项目。

So in your MaterialAppWithTheme widget (which you have to make a Stateful widget now), you have the method below defined:因此,在您的MaterialAppWithTheme小部件(您现在必须制作一个有状态小部件)中,您定义了以下方法:

void _updateAppBarTitle(String newTitle) {
    setState((){
        appTitle = newTitle;
    });
}

Then you have to modify MdDrawer like below to accept a Function object as a parameter:然后你必须像下面一样修改MdDrawer以接受一个 Function 对象作为参数:

class MdDrawer extends StatefulWidget {
  final String title;
  final Function(String) updateAppBarTitle;

  MdDrawer({Key key, this.title, @required this.updateAppBarTitle}) : super(key: key);

  @override
  MdDrawerState createState() {
    return new MdDrawerState();
  }
}

And in your MdListTile 's onTap , you can just call it like so:在你的MdListTileonTap ,你可以这样称呼它:

   return MdListTile(
                onTap: () {
                  widget.updateAppBarTitle(navigationItems[counter].title);
                  //Other methods
                },
                isSelected: currentSelectedIndex == counter,
                title: navigationItems[counter].title,
                icon: navigationItems[counter].icon,
                animationController: _animationController,
              );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM