当前位置:网站首页>Indexedstack in shutter
Indexedstack in shutter
2022-07-18 03:32:00 【A floating boat】
adopt Stack Components we can put some widget Stack on other widget above , Thus, the image combination function can be realized , It is also the most commonly used component in daily life . The components we are going to introduce today are Stack Close relatives of , be called IndexedStack, What's the function of it ? Let's see .
IndexedStack brief introduction
You can tell by the name ,IndexedStack It's for Stack Added a index The function of , Is that the case ? So let's see IndexedStack The definition of :
class IndexedStack extends Stack
Copy code You can see IndexedStack Inherited from Stack, It's actually Stack Subclasses of , So what I introduced before Stack Some functions IndexedStack All have , also IndexedStack It's right Stack The function of is enhanced .
Let's look at its constructor :
IndexedStack({
Key? key,
AlignmentGeometry alignment = AlignmentDirectional.topStart,
TextDirection? textDirection,
StackFit sizing = StackFit.loose,
this.index = 0,
List<Widget> children = const <Widget>[],
}) : super(key: key, alignment: alignment, textDirection: textDirection, fit: sizing, children: children);
You can see the sum Stack comparison ,IndexedStack One more. index Parameters , But this parameter is not passed in super In the constructor of , that index Where exactly is it used ?
Don't worry. ,IndexedStack The following two methods are also rewritten , Namely createRenderObject and updateRenderObject:
@override
RenderIndexedStack createRenderObject(BuildContext context) {
assert(_debugCheckHasDirectionality(context));
return RenderIndexedStack(
index: index,
alignment: alignment,
textDirection: textDirection ?? Directionality.maybeOf(context),
);
}
@override
void updateRenderObject(BuildContext context, RenderIndexedStack renderObject) {
assert(_debugCheckHasDirectionality(context));
renderObject
..index = index
..alignment = alignment
..textDirection = textDirection ?? Directionality.maybeOf(context);
}
and Stack comparison ,IndexedStack What is used in these two methods is RenderIndexedStack, and Stack It uses RenderStack.
So although IndexedStack Inherited from Stack, But there are essential differences between the two in performance .
about Stack Come on , One widget Put in another widget above , But many widget Can be displayed at the same time . And for IndexedStack Come on , It only shows the corresponding index Of widget.
RenderIndexedStack It's also inherited from RenderStack:
class RenderIndexedStack extends RenderStack
Let's see what it looks like paintStack Method :
@override
void paintStack(PaintingContext context, Offset offset) {
if (firstChild == null || index == null)
return;
final RenderBox child = _childAtIndex();
final StackParentData childParentData = child.parentData! as StackParentData;
context.paintChild(child, childParentData.offset + offset);
}
You can see in the paintStack In the method , Only and are drawn index Corresponding _childAtIndex This component , So if index If it doesn't match , It won't show .
IndexedStack The performance is a bit like our common tab.
IndexedStack Use
From above IndexedStack In the constructor of , We know IndexedStack Need to pass in a index Property and corresponding children.
In this case , We give IndexedStack Pass in a variable index attribute , and 4 individual child:
IndexedStack(
index: _counter,
children: [
widgetOne(),
widgetTwo(),
widgetThree(),
widgetFour(),
],
)
_counter Is defined in StatefulWidget The variables in the . You can call setState Method pair index Make changes , So as to realize dynamic switching child Purpose .
there child widget It's simple , We used different sizes of SizedBox,SizedBox Set different... In color To observe the switching effect :
Widget widgetOne() {
return SizedBox(
width: 100,
height: 100,
child: Container(
color: Colors.yellow,
),
);
}
Last , stay Scaffold Of floatingActionButton Call in _changeIndex Method realization index Changes , The final code is as follows :
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _changeIndex() {
setState(() {
_counter = (_counter+1) % 4;
print(_counter);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: IndexedStack(
index: _counter,
children: [
widgetOne(),
widgetTwo(),
widgetThree(),
widgetFour(),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _changeIndex,
tooltip: 'change index',
child: const Icon(Icons.arrow_back),
),
);
}
The effect of the program is as follows :

By clicking the button at the bottom right , We got different widget.
summary
IndexWidget and tab It's kind of similar , You can use it when you need it .
Flutter Use PageView and IndexedStack Structure the difference between switching pages at the bottom
At first I used IndexedStack Construct , But I found a problem , If you go in app When , Homepage module , Trading module , The personal center module will trigger the interface request , If the user token invalid , I will switch to the login page , But if you use IndexedStack, Will trigger 3 Request switching 3 Login page , I want to find IndexedStack The middle page will only be triggered when you click initState Method , But I didn't find . I haven't found anything similar yet iOS Methods in the life cycle . So use pageView Switch

So use PageView, Then use... In the page AutomaticKeepAliveClientMixin Mix in , Rewrite bool get wantKeepAlive => true; Can be realized

then

Implement the override method
Bottom Tab Several methods of switching and maintaining page state
One 、IndexedStack Keep the page state
IndexedStack and Stack equally , Are layer layout controls , You can place another control on top of one control
Controls , But the only difference is IndexedStack Only one of the child controls can be displayed at a time
Pieces of , adopt Index Property to set the displayed control .
IndexedStack The advantage of maintaining page state is simple configuration .IndexedStack Keep page shape
The disadvantage of state is that it is not convenient to control the state of each page separately .
IndexedStack usage :
Container(
width: double.infinity,
height: double.infinity,
child: new IndexedStack(
index: 0,
alignment: Alignment.center,
children: <Widget>[
Image.network("https://www.itying.com/images/flutter/list1.jpg",fit:
BoxFit.cover,),
Image.network("https://www.itying.com/images/flutter/list2.jpg",fit:
BoxFit.cover)
],
),
)
Combined bottom tab Switch
body:IndexedStack(
children: this._pageList,
index: _currentIndex,
),
Two 、 AutomaticKeepAliveClientMixin Keep the page state
AutomaticKeepAliveClientMixin combination tab Toggle keep page state IndexedStack In terms of configuration
Micro is a little complicated . It combines the bottom BottomNavigationBar The following configuration is required to maintain the page state .
import 'package:flutter/material.dart';
import 'Home.dart';
import 'Category.dart';
import 'Cart.dart';
import 'User.dart';
class Tabs extends StatefulWidget {
Tabs({Key key}) : super(key: key);
_TabsState createState() => _TabsState();
}
class _TabsState extends State<Tabs> {
int _currentIndex=1;
// Create page controller
var _pageController;
@override
void initState(){
// Page controller initialization
_pageController = new PageController(initialPage : _currentIndex);
super.initState();
}
List<Widget> _pageList=[
HomePage(),
CategoryPage(),
CartPage(),
UserPage()
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("jdshop"),
),
// Must use PageView Load different pages
body: PageView(
controller: _pageController,
children: this._pageList,
onPageChanged: (index){
_currentIndex = index;
},
),
bottomNavigationBar: BottomNavigationBar(
currentIndex:this._currentIndex ,
onTap: (index){
setState(() {
//this._currentIndex=index;
// Jump to page controller
_pageController.jumpToPage(this._currentIndex);
});
},
type:BottomNavigationBarType.fixed ,
fixedColor:Colors.red,
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
title: Text(" home page ")
),
BottomNavigationBarItem(
icon: Icon(Icons.category),
title: Text(" classification ")
),
BottomNavigationBarItem(
icon: Icon(Icons.shopping_cart),
title: Text(" The shopping cart ")
),
BottomNavigationBarItem(
icon: Icon(Icons.people),
title: Text(" my ")
)
],
),
);
}
}
Add the following code to the page that needs to be persisted :
class HomePage extends StatefulWidget {
HomePage({Key key}) : super(key: key);
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> with AutomaticKeepAliveClientMixin{
@override
bool get wantKeepAlive => true;
}边栏推荐
- 活动预告|Apache Doris x Apache SeaTunnel 联合 Meetup 开启报名!
- 想找个大券商开户?现在通过手机股票开户是安全的吗?
- Spark中RDD、DataFrame和DataSet的区别与联系
- std::unique_ptr作为形参时的使用问题
- Tencent celebrities share | Tencent alluxio (DOP) landing and Optimization Practice in the financial scene
- “小白嘴”白山药是哪个县的特色农产品? 蚂蚁新村7月15日答案
- 浅谈 Slack Channel 支持的一些提高工作效率的特性
- MySQL (III) router, MHA high availability
- DataArts Studio数据架构——基于模型驱动的智能自动化流水线建设案例
- Explication détaillée de la méthode d'interruption du fil
猜你喜欢

Detailed explanation of thread interrupt method

Robotframework advanced (I) integrated pychart and UI automation use case writing

Award winning research | openeuler developer experience research questionnaire

知乎高赞:数据中台——风起阿里,成于DaaS

Carte écologique numérique des ressources humaines en Chine - marché flexible de l'emploi

mysql(三)路由器、MHA高可用

Storage system lighting sorting

The difference between B tree and b+ tree

Flutter中的IndexedStack

Comparison of xssfworkbook, sxssfworkbook and easyexcel reading Excel files
随机推荐
[live review] openharmony knowledge empowerment phase 6 lesson 3 - control panel function implementation of openharmony smart home project
盖茨再捐200亿美元,谷歌云转投ARM,推特员工因马斯克遭CEO警告,今日更多大新闻在此...
聚簇索引和非聚簇索引
Data transmission: Practice of batch extraction of isomorphic and heterogeneous IP data sources
[detailed explanation] paging method: use of page helper
中国人力资源数字化生态图谱-灵活用工市场
Learning summary Note 6 (Gerui titant software - Jiuye practical training)
Use the kicad plug-in to visualize PCB welding
Flutter 中的 offstage
Accenture's 22 year technology outlook report: digital transformation will usher in the next decade
Listbox
数据传输:同构异IP数据源批量抽取实践
Digital ecological map of human resources in China - flexible employment market
DevSecOps研发安全实践——开发篇
Threshold psi code
After downloading pyqt5, I found that the designer could not be found Exe problem solution
The bull and bear cycle of the encryption market; Debate on the definition of NFT
Issue 99: flutter learning (2)
文件解析_Excel文件解析
Sony's metauniverse layout