gpt4 book ai didi

flutter - 显示/隐藏小部件而不重新创建它

转载 作者:行者123 更新时间:2023-12-05 05:15:13 28 4
gpt4 key购买 nike

假设我有 2 张卡片,屏幕上一次显示一张。我有一个按钮可以用其他卡片替换当前卡片。现在假设卡 1 上有一些数据,卡 2 上有一些数据,我不想破坏它们每个上的数据,或者我不想再次重建它们中的任何一个。

我尝试使用 Stack Widget 并在顶部卡片上使用 bool 值将一个组件重叠在其他组件之上。按下按钮时调用 setstate 可反转此 bool 值。问题是我一按下按钮,新卡就会重新重建然后显示,或者再次调用 initState,这是我不想要的。有什么解决办法吗?

编辑:示例代码:

import 'package:flutter/material.dart';

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

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

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

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

class _MyHomePageState extends State<MyHomePage> {
var toggleFlag = false;

@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: new Center(
child: toggleFlag
? CustomWidget(color: Colors.blue)
: CustomWidget(color: Colors.red),
),
floatingActionButton: new FloatingActionButton(
onPressed: _toggleCard,
tooltip: 'Increment',
child: new Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}

void _toggleCard() {
setState(() {
toggleFlag = !toggleFlag;
});
}
}

class CustomWidget extends StatefulWidget {
var color;

CustomWidget({this.color});

@override
State<StatefulWidget> createState() {
return new MyState();
}
}

class MyState extends State<CustomWidget> {
@override //I don't want this to be called again and again
Widget build(BuildContext context) {
return new Container(
height: 100.0,
width: 100.0,
color: widget.color,
);
}
}

最佳答案

1-解决方案:你有一组像这样的小部件

  final widgetList[widget1(), widget2()]
int currentIndex = 0;

IndexedStack (
   index: currentIndex,
   children: widgetList,
 ));

2-解决方案:

使用 Stack 小部件

  int currentIndex = 0;

Stack(
children: [
Offstage(
offstage: currentIndex != 0,
child: bodyList[0],
),
Offstage(
offstage: currentIndex != 1,
child: bodyList[1],
),
Offstage(
offstage: currentIndex != 2,
child: bodyList[2],
),
],
)

3-解决方案:您需要将其添加到您的有状态小部件状态

AutomaticKeepAliveClientMixin <Widgetname> like this

class _WidgetState extends State <Widgetname> with AutomaticKeepAliveClientMixin <Widgetname> {
@override
   bool get wantKeepAlive => true;
}

关于flutter - 显示/隐藏小部件而不重新创建它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51822842/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com