获取DefaultTabController的当前选项卡

dak*_*ojo 6 flutter

在我的工厂的onPressed中,我想知道DefaultTabController中当前选择的选项卡的索引。我该怎么做呢?

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'pari',
      debugShowCheckedModeBanner: false,
      theme: widget._themeData,
      home: DefaultTabController(
        length: widget._tabs.length,
        child: Scaffold(
          appBar: AppBar(
            title: Text('pari'),
            bottom: TabBar(
              isScrollable: true,
              tabs: widget._tabs,
            ),
          ),
          body: _buildBody(),
          floatingActionButton: FloatingActionButton(
              onPressed: addWagerTap,
          ),
        )
      ),
    );
  }
Run Code Online (Sandbox Code Playgroud)

Alb*_*bal 7

如果您将自己包装在的Scaffold内部,则Builder可以DefaultTabController在适当的范围内访问context。然后,您可以使用检索标签索引DefaultTabController.of(context).index

  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'pari',
      debugShowCheckedModeBanner: false,
      theme: widget._themeData,
      home: DefaultTabController(
        length: 4,
        child: Builder(builder: (BuildContext context) {
          return Scaffold(
            appBar: AppBar(
              title: Text('pari'),
              bottom: TabBar(
                  isScrollable: true,
                  tabs: [Text('0'), Text('1'), Text('2'), Text('3')]),
            ),
            body: _buildBody(),
            floatingActionButton: FloatingActionButton(
              onPressed: () {
                print(
                    'Current Index: ${DefaultTabController.of(context).index}');
              },
            ),
          );
        }),
      ),
    );
  }
Run Code Online (Sandbox Code Playgroud)

  • 当我需要以编程方式更改选项卡索引时,它对我有用,如下所示 `onPressed: () { DefaultTabController.of(context).index =2; }),` (2认同)

小智 7

您还可以使用 DefaultTabController 的 onTap 属性获取选项卡的索引。

Widget build(BuildContext context) {
  return new MaterialApp(
    title: 'pari',
    debugShowCheckedModeBanner: false,
    theme: widget._themeData,
    home: DefaultTabController(
      length: widget._tabs.length,
      child: Scaffold(
        appBar: AppBar(
          title: Text('pari'),
          bottom: TabBar(
            isScrollable: true,
            onTap: (int index) {
               print('index is $index');
             }
            tabs: widget._tabs,
          ),
        ),
        body: _buildBody(),
        floatingActionButton: FloatingActionButton(
            onPressed: addWagerTap,
        ),
      )
    ),
  );
}



Run Code Online (Sandbox Code Playgroud)

  • 当用户通过滑动更改选项卡时这不起作用 (19认同)