获取DefaultTabController的当前选项卡

时间:2018-09-25 16:09:00

标签: flutter

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

@Provider
public class MyWrapperExceptionMapper implements ExceptionMapper<MyWrapperException> {
    @Context
    private Providers providers;

    public Response toResponse(MyWrapperException e) {
        Throwable t = e.getCause();
        ExceptionMapper mapper = providers.getExceptionMapper(t.getClass());
        if( mapper != null ) {
            return mapper.toResponse(t);
        }
        else {
            // custom handling...
        }
    }
}

2 个答案:

答案 0 :(得分:4)

如果将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}');
              },
            ),
          );
        }),
      ),
    );
  }

答案 1 :(得分:1)

您还可以使用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,
        ),
      )
    ),
  );
}