Flutter更新Appbar中的文本

2024-05-04

我需要帮助更新应用栏中的文本以匹配我当前所在的页面。

因此,如果我在“设置”页面中,那么我需要在 AppBar 文本中显示它。

我添加代码和屏幕截图是为了更好地解释我想要实现的目标。

主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

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

您可以更新中的文本AppBar小部件在MaterialAppWithTheme通过有一个方法来更新文本MaterialAppWithTheme并将其作为回调传递给MdDrawerState并在您更改抽屉项目时执行该操作。

所以在你的MaterialAppWithTheme小部件(您现在必须制作一个有状态小部件),您定义了以下方法:

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

那么你必须修改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();
  }
}

而在你的MdListTile's onTap,你可以这样称呼它:

   return MdListTile(
                onTap: () {
                  widget.updateAppBarTitle(navigationItems[counter].title);
                  //Other methods
                },
                isSelected: currentSelectedIndex == counter,
                title: navigationItems[counter].title,
                icon: navigationItems[counter].icon,
                animationController: _animationController,
              );
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Flutter更新Appbar中的文本 的相关文章

随机推荐