如何使用TabController

18

我刚学习Flutter,对于如何使用TabController感到困惑。我按照官方网站上描述的步骤进行了操作,但是出现了一个错误,我不知道该如何解决。

我只想在切换选项卡时更改AppBar的标题和Leading。

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

错误日志:

错误日志: I/flutter (19638): TabBarView没有TabController。 I/flutter (19638): 当创建TabBarView时,必须使用“控制器”属性提供显式的TabController,或者您必须确保在TabBarView上方存在一个DefaultTabController。 I/flutter (19638): 在这种情况下,既没有显式控制器也没有默认控制器。 ════════════════════════════════════════════════════════════════════════════════════════════════════

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

当我将以下代码更改为: leading: _handler.leading,title: new Text(_handler.title), 总是会返回错误 _handler.leading_handler.title 为空

图像


最好将您的代码以文本格式添加。 - Mazin Ibrahim
好的,我会添加它。 - anangfaturrohman
完成,请帮忙。 - anangfaturrohman
2个回答

18

尝试这个解决方案:

不要忘记继承

TickerProviderStateMixin

输入图像描述

class HomePage extends StatefulWidget {
  const HomePage();

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

class _HomePageState extends State<HomePage> with TickerProviderStateMixin {
  late TabController tabController;
  @override
  void initState() {
    super.initState();
    tabController = TabController(
      initialIndex: 0,
      length: 2,
      vsync: this,
    );
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);

    return Scaffold(
      appBar: AppBar(
        title: Row(
          children: [
            Image.asset(
              'assets/images/png/logo.png',
              height: 60,
              width: 60,
            ),
            Spacer(),
            Container(
              width: 400,
              child: TabBar(
                labelColor: Color.fromRGBO(4, 2, 46, 1),
                labelStyle: theme.textTheme.headline1,
                indicatorColor: Color.fromRGBO(4, 2, 46, 1),
                unselectedLabelColor: Colors.grey,
                controller: tabController,
                tabs: [
                  Text('الفاتورة'),
                  Text('دليفري'),
                ],
              ),
            ),
          ],
        ),
      ),
      body: Container(
        child: TabBarView(
          controller: tabController,
          children: [
            Container(
              color: Colors.red,
            ),
            Container(
              color: Colors.orange,
            ),
          ],
        ),
      ),
    );
  }

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

1
这个应该可以运行,但是在新的Flutter版本中,“controller: tabController”会抛出“无效的常量值”的错误。我仍在寻找解决方案。 - Dpedrinha
请发送给我截图。 - Mahmoud Salah Eldin
@Dpedrinha 如果你在AppBar中将TabBar创建为常量(constant),那么你会得到一个错误,即“无效的const错误”。 - Sisir

13
问题在于您缺少一个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,
      )...

谢谢,现在AppBar的leading: _handler.leading仍然存在the getter leading was called on null错误。 - anangfaturrohman
你尝试过初始化变量吗?在initstate之前会调用Build。 - DevTard
好的,我会尝试,谢谢你的帮助。 - anangfaturrohman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接