【问题标题】:Flutter: How to modularize Bottom Navigation BarFlutter:如何模块化底部导航栏
【发布时间】:2020-11-13 13:08:22
【问题描述】:

我一直在浏览有关底部导航栏的多个教程。每个教程都将底部导航栏放在主flutter文件中,我不喜欢。我正在尝试模块化应用程序并将底部导航栏放在第二个文件中,其中包含 getter 和 setter 以更改和监视当前视图,但这对我不起作用。我尝试在导航栏访问的应用程序文件中创建 setter 和 getter 来处理这样的导航:

class _AppState extends State<App> {
  int _selectedPage = 0;
  final _pages = [HomePage(), EventsPage(), ThrivePage(), AnnouncementsPage()];

  int get currentPage => this._selectedPage;

  set currentPage(int thePage) {
    this._selectedPage = thePage;
  }

底部导航小部件文件可以访问它,但 App 类没有实际变量,因此我无法访问类 getter 和 setter。

我对 OOP 很陌生,所以可能有一种我不熟悉的方法。任何帮助表示赞赏。

【问题讨论】:

  • 你想要什么样的布局?解释清楚。
  • 我想要一个在应用中有一个底部导航栏的布局。当我按下一个图标时,应用页面会发生变化,底部导航栏也会发生变化以突出显示您在特定视图上。

标签: flutter oop dart state


【解决方案1】:

这可能不是您现在想听到的,但您可以创建一个自定义选项卡并使用网页浏览作为您的视图,然后使用网页浏览控制器在屏幕之间切换,现在自定义导航可以是您只需链接它们的任何文件正确。 我想我可能会写一篇文章来真正解释我所说的

【讨论】:

  • 请做。一篇文章会很棒! ;)
【解决方案2】:

您可以使用ValueNotifier 在不同的小部件之间传递值。使您的底部导航类在构造函数中采用 ValueNotifier 并向其添加侦听器。

class MyBottomNavigationBar extends StatefulWidget {
  final ValueNotifier<int> currentPageNotifier;


  MyBottomNavigationBar(this.currentPageNotifier);

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

class _MyBottomNavigationBarState extends State<MyBottomNavigationBar> {

  @override
  void initState() {
    super.initState();
    widget.currentPageNotifier.addListener(() {
      print(widget.currentPageNotifier.value);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

_AppState 将 ValueNotifier 传递给 MyBottomNavigationBar 实例,然后您可以使用该 ValueNotifier 将页面索引值传递给 MyBottomNavigationBar

class _AppState extends State<App> {
  ValueNotifier<int> _currentPageNotifier = ValueNotifier(0);
  int _selectedPage = 0;

  int get currentPage => this._selectedPage;

  set currentPage(int thePage) {
    this._selectedPage = thePage;
    this._currentPageNotifier.value = thePage;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Text(
          'You have pushed the button this many times:',
        ),
      ),
      bottomNavigationBar: MyBottomNavigationBar(_currentPageNotifier),// This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

【讨论】:

  • 我试过这个,但它解决了一半的问题。我还尝试将底部导航栏的索引发送回 _AppState 类,以便当我按下底部导航栏图标时实际页面会发生变化
  • 我认为你也可以使用相同的changenotifier发送底部导航器的索引并从_AppState监听。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-06
  • 2023-02-25
  • 2020-02-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多