When I’m using TabBar,TabBarView,

Premise: When I click every few tabs

Question:

1. The initState of the corresponding page is not directly invoked. The initState of the left Tab is executed twice before being executed

For example: daily list, weekly list, monthly list

Click Month list –> Day list initState–> Day list Dispose –> Day list initState–> Day list dispose–> Month list initState

2. InitState calls the interface and causes an error:

InitState –> call API –> call API dispose–> call API dispose–> call data setState in initState

Expectation: Which TAB to click only performs initState for the corresponding page

Note: clicking in sequence will not be a problem, but clicking at intervals will appear

Simulation code:

import 'package:flutter/material.dart'; void main() { runApp(MyApp()); }class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, visualDensity: VisualDensity.adaptivePlatformDensity, ), home:Homde() ); }}class Homde extends StatefulWidget { @override _HomdeState createState() => _HomdeState(); }class _HomdeState extends State<Homde> with SingleTickerProviderStateMixin, AutomaticKeepAliveClientMixin { TabController _tabController; Final List < String > rankTypes = [" List ", "Zhou Bang", "month List", "new List", "original List", "male", "female to"]. @override bool get wantKeepAlive => true; @override void initState() { super.initState(); _tabController = TabController(initialIndex: 0, length: rankTypes.length, vsync: this); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( bottom: TabBar( isScrollable: true, controller: _tabController, tabs: rankTypes.map((item) { return Tab(text: item); }).toList() ), ), body: TabBarView( controller: _tabController, children: rankTypes.map((item) { return Item(name: item,); }).toList() ), ); }}class Item extends StatefulWidget { final String name; const Item({Key key, this.name}) : super(key: key); @override _ItemState createState() => _ItemState(); }class _ItemState extends State<Item> with AutomaticKeepAliveClientMixin { @override bool get wantKeepAlive => true; String apiData = "a"; @override void initState() { super.initState(); debugPrint(widget.name); Future.delayed(const Duration(milliseconds: 3000),(){setState(() {apiData = "b"; debugPrint(widget.name + "setState"); }); }); } @override Widget build(BuildContext context) { super.build(context); return Center( child: Text(widget.name), ); }}Copy the code