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

时间:2018-08-13 12:51:40

标签: flutter

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

我尝试使用Stack Widget,并将其中一个重叠在顶部卡上的布尔值上。当按下按钮时,通过调用setstate可以反转此布尔值。问题是,一旦我按下按钮,新的卡就会重新构建一遍,然后显示出来,或者再次调用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 Dont want this to be called again and again
  Widget build(BuildContext context) {  
    return new Container(
      height: 100.0,  
      width: 100.0,
      color: widget.color,
    );
  }
}

2 个答案:

答案 0 :(得分:2)

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;
   }

答案 1 :(得分:0)

无状态小部件始终被认为是易腐烂的。如果要保留状态,请使用StatefulWidget和State子类。