颤动-只有在点击其他元素时,UI更改才会生效 [英] flutter - UI change ONLY Take Effect if tap another element

查看:74
本文介绍了颤动-只有在点击其他元素时,UI更改才会生效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面的屏幕上,该屏幕显示前前一个/上一个当前月的用户点的历史记录。 有两个指示符,分别是 Text1 Text2

I have below screen, this screen show history of user's point for previous/last and current month. The point has 2 indicators, they are Text1 and Text2.


  1. 默认数据将显示当前月。

  2. 如果我点击上个月按钮,它将更改UI以显示

  3. 如果我点击显示/隐藏文本1 ,则它首先会隐藏的所有外观文字1 。如果再次点击,则所有 Text1 都会再次出现。

  4. 用于显示/隐藏文本2 与第(3)点相同。

  1. default data will show current month.
  2. if i tap last month button, it will change UI to show last month data.
  3. if i tap Show/Hide Text 1, first it will hide All appearance of Text1. and if i tap again, then all of Text1 will appear again.
  4. for Show/Hide Text2 same as point (3).



问题:



如果我点击显示/隐藏按钮来显示 Text1 Text2 只有在我点击上个月当月按钮(显示/隐藏Text1或Text2的元素)。因此显示/隐藏按钮的更改效果不会立即生效,我需要点击另一个元素才能生效。

The Problem :

if i tap show/hide button for Text1 or Text2 it will take effect only after i tap last month or current month button (show/hide the element of Text1 or Text2). so the change effect of show/hide button not instantly, i need to tap another element to take effect.

class MainHistoryScreen extends StatefulWidget {
  @override
  _MainHistoryScreenState createState() {
    return new _MainHistoryScreenState();
  } 
}

class _MainHistoryScreenState extends State<MainHistoryScreen> {

  MainHistoryBloc MainHistoryBloc;
  int selectedValue = 1;

  //you don't have to declare false as bool is initialised false by default
  bool showText1 = false;
  bool showText2 = false;
  bool showText3 = false;

  @override
    void initState() {
      super.initState();
      MainHistoryBloc = MainHistoryBloc();
      MainHistoryBloc.getContents(context);
  }

  @override
    void dispose() {
      super.dispose();
      MainHistoryBloc.dispose();
    }

  getNumberFormat(String str) {
    final f = new NumberFormat("#.###");
    return str.replaceAll(f.symbols.GROUP_SEP, '');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Pigment.fromString(UIData.primaryColor),
        elevation: 0,
        centerTitle: true,
        title: Text(translations.text("main_history").toUpperCase()),
        leading: Row(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            Expanded(
              child: InkWell(
                child: SizedBox(child: Image.asset("assets/images/arrow-back.png"), height: 10, width: 1,),
                onTap: () => Navigator.of(context).pop(),
              )
            ),  
          ],
        ),
      ),
      body: ListView(
        primary: true,
        scrollDirection: Axis.vertical,
        children: <Widget>[
          Container(
            height: MediaQuery.of(context).size.height * 0.30,
            padding: EdgeInsets.all(16.0),
            width: MediaQuery.of(context).size.width,
            decoration: new BoxDecoration(
              image: new DecorationImage(
                image: new AssetImage("assets/images/account/background.png"),
                fit: BoxFit.cover,
              ),
            ),
            child: Center(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  SizedBox(
                    child: CircleAvatar(
                      backgroundImage: NetworkImage(UIData.defaultUserIconUrl),
                    ),
                    height: 75,
                    width: 75,
                  ),
                  SizedBox(height: 20,),
                  StreamBuilder(
                    stream: MainHistoryBloc.userStream,
                    builder: (BuildContext ctx,AsyncSnapshot<User> snapshot){
                      if(!snapshot.hasData) {
                        return Text(translations.text("member_since") + ": -", style: TextStyle(color: Colors.white));
                      }
                      return Text(translations.text("member_since") + ": " + new DateFormat("d MMMM y").format(DateTime.parse(snapshot.data.created_at.toString())), style: TextStyle(color: Colors.white));
                    }
                  )
                ]
              ),
            ),
          ),
          Padding(
            padding: EdgeInsets.all(8),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Divider(height: 2, color: Pigment.fromString(UIData.primaryColor),),
                SizedBox(height: 10,),
                StreamBuilder(
                  stream: MainHistoryBloc.totalmainHistoryStream,
                  builder: (BuildContext ctx, AsyncSnapshot<UserDetail> snapshot){
                    var point = snapshot.hasData ? this.getNumberFormat(snapshot.data.point.toString()) : "0";
                    var main = snapshot.hasData ? this.getNumberFormat(snapshot.data.main.toString()) : "0";
                    var sadaqah = snapshot.hasData ? this.getNumberFormat(snapshot.data.sadaqah.toString()) : "0";
                    return Container(
                      child: Row(
                        children: <Widget>[
                          Expanded(
                            child: mainMenuWidget(
                              image: "assets/images/main/star.png", 
                              title: translations.text("total_points"), 
                              subtitle: point,
                              onTap: () {

                                //Show/Hide Text1
                                showText1 = !showText1;
                                print ("Text 1 = "+showText1.toString());
                              }
                            )
                          ),
                          Expanded(
                            child: mainMenuWidget(
                              image: "assets/images/home/my-main.png",
                              title: translations.text("total_main"),
                              subtitle: main,
                              onTap: () {

                                //Show/Hide Text2
                                showText2 = !showText2;
                              }
                            )
                          ),
                          Expanded(
                            child: mainMenuWidget(
                              image: "assets/images/home/more-sadaqah.png",
                              title: translations.text("total_sadaqah"),
                              subtitle: sadaqah,
                              onTap: () {

                                //Show/Hide Text 3  
                                showText3 = !showText3;
                              },
                            )
                          )
                        ],
                      )
                    );
                  }
                ),
                SizedBox(height: 10,),
                Divider(height: 2, color: Pigment.fromString(UIData.primaryColor),),
                Padding(
                  padding: EdgeInsets.only(left: 26, top: 12, bottom: 12),
                  child: Text(translations.text("histories"), textAlign: TextAlign.left, style: TextStyle(fontSize: 16),),
                ),
                Divider(height: 2, color: Pigment.fromString(UIData.primaryColor),),
                SizedBox(
                  width: 1000,
                  child: Padding(
                    padding: EdgeInsets.all(8),
                    child: StreamBuilder(
                      stream: MainHistoryBloc.tabSelectedValueStream,
                      builder: (context, snapshot) {
                        return CupertinoSegmentedControl<int>(
                          selectedColor: Pigment.fromString(UIData.primaryColor),
                          borderColor: Pigment.fromString(UIData.primaryColor),
                          children:  <int, Widget>{
                            0: Text(translations.text("last_month").toString()),
                            1: Text(translations.text("this_month").toString()),
                          },
                          onValueChanged: (int newValue) {
                            MainHistoryBloc.onChangeTab(newValue);
                          },
                          groupValue: snapshot.data,
                        );
                      }
                    ),
                  )
                ),
              ],
            )
          ),
          historiesWidget(),
        ],
      )
    );
  }

  Widget historiesWidget() {
    return StreamBuilder(
      stream: MainHistoryBloc.mainHistoriesStream,
      builder: (BuildContext ctx, AsyncSnapshot<List<mainHistory>> snapshot) {
        if (snapshot.hasError) return new Text('Error: ${snapshot.error}');
        if (!snapshot.hasData) return Center(child: ActivityIndicatorWidget());
        if (snapshot.data.length <= 0) return Center(child: Text(translations.text("empty_data")));

        return ListView.builder(
          shrinkWrap: true,
          itemCount: snapshot.data.length,
          primary: false,
          physics: const NeverScrollableScrollPhysics(),
          itemBuilder: (ctx, i) {
            return ActivityHistoryCardWidget(mainHistory: snapshot.data[i],
                showText1: showText1,
                showText2: showText2,
                showText3: showText3,
            );
          }
        );
      }
    );
  }
}

下面是显示数据的列表卡小部件。 / p>

ActivityHistoryWidget.dart:



Below are list card widget to show the data.

class ActivitHistoryCardWidget extends StatefulWidget {

  DActivitHistory dActivitHistory;
  bool showText1;
  bool showText2;
  bool showText3;

  ActivitHistoryCardWidget({this.dActivitHistory, this.showText1, this.showText2, this.showText3});

  @override
  _ActivitHistoryCardWidget createState() {
    return new _ActivitHistoryCardWidget(dActivitHistory: dActivitHistory);
  }


}

class _ActivitHistoryCardWidget extends State<ActivitHistoryCardWidget> {

  DActivitHistory dActivitHistory;
  bool showText1;
  bool showText2;
  bool showText3;

  _ActivitHistoryCardWidget({this.dActivitHistory, this.showText1, this.showText2, this.showText3});

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Container(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Container(
                width: 100,
                alignment: Alignment.topCenter,
                child: Text(new DateFormat("d").format(DateTime.parse(dActivitHistory.dActivitDate)),  
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    fontSize: 50,
                  )
                ),
              ),
              Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  SizedBox(height: 10,),
                  Text(new DateFormat("EEEE").format(DateTime.parse(dActivitHistory.dActivitDate)),
                    style: TextStyle(
                      fontSize: 14
                    ),
                  ),
                  SizedBox(height: 5,),
                  Text(new DateFormat("MMMM y").format(DateTime.parse(dActivitHistory.dActivitDate)),
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w600
                    ),
                  ),


                  //Point Widget
                  widget.showText1 ? Container() : this.PointHistory(context),

                  //Activit Widget
                  widget.showText2 ? Container() : this.ActivitHistory(context),

                  //Give Widget
                  widget.showText3 ? Container() : this.GiveHistory(context),

                  SizedBox(height: 10,),
                ],
              )
            ],
          ),
        ),
        Divider(height: 2, color: Pigment.fromString(UIData.primaryColor),),
      ],
    );
  }


  Widget PointHistory(context) {
    return Column(
      children: <Widget>[
        SizedBox(height: 10,),
        Row(
          children: <Widget>[
            SizedBox(child: Image.asset("assets/images/Activit/star.png"),height: 20, width: 20,),
            SizedBox(width: 10,),
            Text(getNumberFormat(dActivitHistory.counter.toString()),
              style: TextStyle(
                  fontSize: 16,
                  color: Pigment.fromString(UIData.primaryColor)
              ),
            ),
          ],
        ),
      ],
    );
  }

  Widget ActivitHistory(context) {
    return Column(
      children: <Widget>[
        SizedBox(height: 10,),
        Row(
          children: <Widget>[
            SizedBox(child: Image.asset("assets/images/home/my-Activit.png"),height: 20, width: 20,),
            SizedBox(width: 10,),
            Text(getNumberFormat(dActivitHistory.dActivitTotal.toString()),
              style: TextStyle(
                  fontSize: 16,
                  color: Pigment.fromString(UIData.primaryColor)
              ),
            ),
          ],
        ),

      ],
    );
  }

  Widget GiveHistory(context) {
    return Column(
      children: <Widget>[
        SizedBox(height: 10,),
        Row(
          children: <Widget>[
            SizedBox(child: Image.asset("assets/images/home/more-Give.png"),height: 20, width: 20,),
            SizedBox(width: 10,),
            Text('Di Salurkan Sejumlah Rp '+getNumberFormat(dActivitHistory.GiveTotal.toString()+' ke Lembaga '+getFoundationName(dActivitHistory.foundationDonateId.toString()) ),
              style: TextStyle(
                  fontSize: 16,
                  color: Pigment.fromString(UIData.primaryColor)
              ),
            ),
          ],
        ),
      ],
    );
  }

  getFoundationName(String str)
  {
    String returnName = '';
    switch (str) {
      case '1':
        returnName = 'A';
        break;
      case '2':
        returnName = 'B';
        break;
      case '3':
        returnName = 'C';
        break;
      case '4':
        returnName = 'D';
        break;
      case '5':
        returnName = 'E';
        break;
    }
    return returnName;
  }

  getNumberFormat(String str) {
    final f = new NumberFormat("#.###");
    return str.replaceAll(f.symbols.GROUP_SEP, '');
  }
}

任何想法?

预先感谢...

推荐答案

您需要使用 setState()方法来更改状态。例如:

You need to use setState() method to change the state. For example:

Expanded(
    child: mainMenuWidget(
        image: "assets/images/home/more-sadaqah.png",
        title: translations.text("total_sadaqah"),
        subtitle: sadaqah,
        onTap: () {
            setState(() {
                showText3 = true;
            });
        },
    )
)

它将在您已经使用条件状态进行更改时更新ui。

It will update the ui as you already use conditional state to change it.

//Give Widget
widget.showText3 ? Container() : this.GiveHistory(context),

但这仅在您更改状态时才有效一堂课我看到您有2个单独的班级,您需要更多高级状态管理。因此,您可以维护其他类的状态。尝试使用提供程序

But that only works if you change the state in one class. I see you have 2 separate class, you need more advance state management. So you can maintain the state from different class. Try using provider.

这篇关于颤动-只有在点击其他元素时,UI更改才会生效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆