sách gpt4 ai đã đi

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

In lại 作者:行者123 更新时间:2023-12-05 05:15:13 28 4
mua khóa gpt4 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.
@ghi đè
Xây dựng tiện ích (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;

@ghi đè
_MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State {
var toggleFlag = false;

@ghi đè
Xây dựng tiện ích (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() {
đặtState(() {
toggleFlag = !toggleFlag;
});
}
}

class CustomWidget extends StatefulWidget {
var color;

CustomWidget({this.color});

@ghi đè
State createState() {
return new MyState();
}
}

class MyState extends State {
@override //I don't want this to be called again and again
Xây dựng tiện ích (BuildContext context) {
return new Container(
height: 100.0,
width: 100.0,
color: widget.color,
);
}
}

1 Câu trả lời

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

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

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

2-解决方案:

sử dụng 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  like this

class _WidgetState extends State with AutomaticKeepAliveClientMixin {
@ghi đè
   bool get wantKeepAlive => true;
}

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

28 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com