在选项卡之间切换 initstate() 多次调用

Par*_*eri 5 dart flutter flutter-layout

在选项卡之间切换 initstate() 被多次调用。

我的标签栏中有 4 个标签 A、B、C 和 D。

情况(1)如果我像从选项卡 A 切换到选项卡 B 一样,它工作正常。

情况 (2) 但如果我要转到选项卡 A 到 C,则选项卡“B”的 initstate() 会调用两次

案例(1)结果

扑动:A

颤振:B

案例(2)的结果

扑动:A

颤振:B

颤振:C

颤振:B

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin{

  TabController _controller;

  void initState() {
    super.initState();
    _controller = TabController(length: 4, vsync: this);
    _controller.addListener(_handleSelected);
  }

  bool alarm = false;

// Function for handle tap event of tab
  void _handleSelected() async {
  }


  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 4,
      child: Scaffold(
        appBar: AppBar(
          bottom: TabBar(
            controller: _controller,
            tabs: [
              Tab(text: "A"),
              Tab(text: "B"),
              Tab(text: "C"),
              Tab(text: "D"),
            ],
          ),
          actions: [
            Switch(
              value: alarm,
              onChanged: (value) {
              },
              activeTrackColor: Color(0xffff6b6b),
              activeColor: Color(0xffff0000),
            ),
          ],
        ),
        body: TabBarView(
          controller: _controller,
          children: [
            A(),
            B(),
            C(),
            D(),
          ],
        ),
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

Dev*_*ara 5

可以使用IndexedStackwidget来解决此类问题。

使用_MyHomePageState一个变量来管理所选页面的索引;

class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin{

int _selectedPage;

/////
Your code 
/////

}
Run Code Online (Sandbox Code Playgroud)

在脚手架工具的主体中IndexedStack

body: IndexedStack(
          index:_selectedPage,
          children: [
            A(),
            B(),
            C(),
            D(),
          ],
        ),
Run Code Online (Sandbox Code Playgroud)

现在在_handleSelected ()方法句柄中从控制器获取最新的页面索引并使用 setState 更新选项卡栏

void _handleSelected () async {
 int index = _controller.page ;// get index from controller (I am not sure about exact parameter name for selected index) ;
setState((){
_selectedPage = index;
});
}
Run Code Online (Sandbox Code Playgroud)