如何使用TabController

问题描述 投票:0回答:1

我刚刚学会了扑腾,我很困惑如何使用TabController,我已经按照官方网站上的描述,但出现了错误,我不知道如何解决它。

我只是想在更改标签时更改标题并从应用栏引出。

final List<ChangeTitleAndLeading> _data = [
  new ChangeTitleAndLeading(title: "Home", leading: Icon(Icons.home)),
  new ChangeTitleAndLeading(title: "Profile", leading: Icon(Icons.person)),
  new ChangeTitleAndLeading(title: "Friends", leading: Icon(Icons.people))
];

ChangeTitleAndLeading _handler;
TabController _controller;

@override
void initState() {
  super.initState();

  _checkEmailVerification();

  _controller = TabController(vsync: this, length: 3);
  _handler = _data[0];
  _controller.addListener(_handleSelected);
}

@override
void dispose() {
  _controller.dispose();
  super.dispose();
}

void _handleSelected() {
  setState(() {
    _handler = _data[_controller.index];
  });
}

return MaterialApp(
  theme: new ThemeData(
    primarySwatch: Colors.teal,
  ),
  home: new Scaffold(
    appBar: new AppBar(
      leading: Icon(Icons.home),
      title: new Text("Home"),
      bottom: new TabBar(
        controller: _controller,
        tabs: _tabs,
      ),
    ),

    body: TabBarView(
      controller: _controller,
      children: _pages,
    ),

    floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () {
          print('Current Index: ${_handler.title}');
        }
    ),

class ChangeTitleAndLeading {
  final String title;
  final Widget leading;

  ChangeTitleAndLeading({
    @required this.title,
    @required this.leading
  }) :
    assert(title != null),
    assert(leading != null);
}

错误日志:

Error Log:
I/flutter (19638): No TabController for TabBarView.
I/flutter (19638): When creating a TabBarView, you must either provide an explicit TabController using the "controller"
I/flutter (19638): property, or you must ensure that there is a DefaultTabController above the TabBarView.
I/flutter (19638): In this case, there was neither an explicit controller nor a default controller.
════════════════════════════════════════════════════════════════════════════════════════════════════

I / flutter(19638):抛出了另一个异常:没有TabBar的TabController。

当我改变这个:leading: Icon(Icons.home),leading: _handler.leading,和这个:title: new Text("Home"),title: new Text(_handler.title),总是返回错误_handler.leading_handler.title为null

Image

flutter tabbar flutter-appbar
1个回答
0
投票

问题是你缺少一个tabbarcontroller

你的代码应该是:

return MaterialApp(
  theme: new ThemeData(
    primarySwatch: Colors.teal,
  ),
  home:  DefaultTabController(
      length: 3,
child: new Scaffold(
    appBar: new AppBar(
      leading: Icon(Icons.home),
      title: new Text("Home"),
      bottom: new TabBar(
        controller: _controller,
        tabs: _tabs,
      ),
    ),

    body: TabBarView(
      controller: _controller,
      children: _pages,
    )...
© www.soinside.com 2019 - 2024. All rights reserved.