【问题标题】:Flutter TabBarView and BottomNavigationBar pages are not refreshing with SetStateFlutter TabBarView 和 BottomNavigationBar 页面未使用 SetState 刷新
【发布时间】:2020-12-05 15:07:17
【问题描述】:

我有以下 Flutter BottomNavigationBar,我有 3 个子页面小部件。一旦用户写了评论并按下提交按钮,我就会调用 void _clear() 来重置文本字段小部件中的值。此方法在内部并从 WriteReview 小部件调用但不起作用,屏幕未刷新。它本身的数据正在重置,但 UI 尚未刷新。我尝试使用和不使用 setState(){ _clear()};但没有结果。

我对 TabBarView 有类似的问题。我期望结果是刷新选定的小部件页面。

我认为在我缺少的 TabBarView 和 BottomNavigationBar 中处理小部件的方式有所不同。

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class HomeView extends StatefulWidget {
  @override
  _HomeViewState createState() => _HomeViewState();
}

class _HomeViewState extends State<HomeView> {
  final String _writeReviewLabel = 'Write review';
  final String _searchLabel = 'Search';
  final String _accountLabel = 'Account';

  var _currentIndex = 0;

  final List<Widget> _bottomBarItems = [
    WriteReviewView(),
    SearchView(),
    UserAccountView()
  ];

  @override
  Widget build(BuildContext context) {
    final accentColor = Theme.of(context).accentColor;
    final primaryColor = Theme.of(context).primaryColor;
    return BaseView<HomePresenter>(
      createPresenter: () => HomePresenter(),
      onInitialize: (presenter) {
        _currentIndex = ModalRoute.of(context).settings.arguments;
      },
      builder: (context, child, presenter) => Scaffold(
          bottomNavigationBar: BottomNavigationBar(
            backgroundColor: primaryColor,
            selectedItemColor: accentColor,
            unselectedItemColor: Colors.white,
            elevation: 0,
            currentIndex: _currentIndex,
            onTap: (index) {
              onTabTapped(index, presenter);
            },
            items: [
              BottomNavigationBarItem(
                activeIcon: Icon(Icons.rate_review),
                icon: Icon(Icons.rate_review),
                title: Text(_writeReviewLabel),
              ),
              BottomNavigationBarItem(
                activeIcon: Icon(Icons.search),
                icon: Icon(Icons.search),
                title: Text(_searchLabel),
              ),
              BottomNavigationBarItem(
                  activeIcon: Icon(Icons.person),
                  icon: Icon(Icons.person),
                  title: Text(_accountLabel)),
            ],
          ),
          body: _bottomBarItems[_currentIndex]),
    );
  }

  void onTabTapped(int index, HomePresenter presenter) {
    if (index == _currentIndex) {
      return;
    }

    if (presenter.isAuthenticated) {
      setState(() {
        _currentIndex = index;
      });
    } else {
      presenter.pushNamed(context, Routes.login, arguments: () {
        if (presenter.isAuthenticated) {
          Future.delayed(const Duration(microseconds: 500), () {
            setState(() {
              _currentIndex = index;
            });
          });
        }
      });
    }
  }
}

撰写评论视图

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'base/BaseView.dart';

class WriteReviewView extends StatefulWidget {
  @override
  _WriteReviewViewState createState() => _WriteReviewViewState();
}

class _WriteReviewViewState extends State<WriteReviewView> {
  final String _locationLabel = 'Location';
  final String _reviewLabel = 'Review';

  @override
  Widget build(BuildContext context) {
    return BaseView<WriteReviewPresenter>(
        createPresenter: () => WriteReviewPresenter(),
        onInitialize: (presenter) {
          presenter.init();
        },
        builder: (context, child, presenter) => Container(
              color: Theme.of(context).backgroundColor,
              child: _body(presenter),
            ));
  }

  Widget _body(WriteReviewPresenter presenter) {
    final height = MediaQuery.of(context).size.height;
    return LayoutBuilder(builder: (context, constraint) {
      return SingleChildScrollView(
        child: ConstrainedBox(
          constraints: BoxConstraints(minHeight: constraint.maxHeight),
          child: IntrinsicHeight(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                Card(
                  margin: EdgeInsets.fromLTRB(4.0, 4.0, 4.0, 8.0),
                  child: Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 8.0),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                      children: <Widget>[
                        Padding(
                          padding: EdgeInsets.only(top: 10, bottom: 20),
                          child: Row(
                            children: [
                              Icon(Icons.location_on,
                                  color: Theme.of(context).cursorColor),
                              SectionTitle(_locationLabel),
                            ],
                          ),
                        ),
                        ChooseAddressButton(presenter.addressContainer.address, () {
                          presenter.navigateNewAddress(context);
                        }),
                        SizedBoxes.medium,
                      ],
                    ),
                  ),
                ),
                Card(
                  margin: EdgeInsets.fromLTRB(4.0, 4.0, 4.0, 8.0),
                  child: Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 8.0),
                    child: Column(
                      children: [
                        Padding(
                          padding: EdgeInsets.only(top: 10),
                          child: Row(
                            children: [
                              Icon(Icons.star, color: Theme.of(context).indicatorColor),
                              SectionTitle(_reviewLabel),
                            ],
                          ),
                        ),
                        SizedBoxes.medium,
                        CustomTextFormField(
                            data: presenter.reviewContainer.review,
                            showMinimum: true,
                            characterLimit: 50,
                            maxLines: 4,
                            height: 100),
                        ModifyRatingBar(50.0, presenter.reviewContainer.rating, false),
                        Padding(
                            padding: EdgeInsets.symmetric(vertical: 5),
                            child: Divider(indent: 40, endIndent: 40)),
                      ],
                    ),
                  ),
                ),
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: 10),
                  child: Card(
                    color: Theme.of(context).accentColor,
                    child: FlatButton(
                      onPressed: () {
                        _submit(context, presenter);
                      },
                      child: Text('Submit',style:TextStyle(fontWeight: FontWeight.bold,fontSize: 18,color: Colors.white)),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      );
    });
  }

  void _submit(BuildContext context, WriteReviewPresenter presenter) async {
    LoadingPopup.show(context);

    final status = await presenter.submit(context);

    LoadingPopup.hide(context);

    if (status == ReviewStatus.successful) {
      PostCompletePopup.show(context);
      setState(() {
        presenter.clear();
      });
    } else {
      presenter.showError(context, status);
    }
  }
}

【问题讨论】:

    标签: flutter setstate tabbar bottomnavigationview


    【解决方案1】:

    setState() 只刷新调用它的小部件,以及它下面的所有小部件。

    当从WriteReview 小部件调用setState() 时,它不会更新HomeView 小部件。尝试使用某种回调将setState()call 移动到HomeView 小部件。

    【讨论】:

    • 那么,WriteReview 是作为 BottomNavigationBarItem 元素的 HomeView 的一部分这一事实,是否赋予了主视图更新其子 UI 的责任?与项目的其余部分相比,这不是反直觉吗?在所有其他情况下,设置状态正在按预期更新调用小部件。我想了解为什么在 TabBarView 和 BottomBarNavigation 页面子项上 setstate 不起作用,这是这些控制器的特殊规则?
    • 我可能理解错了。你能分享在 writereview 小部件中不起作用的代码吗?
    • 我更新了我的初始帖子,最后_submit 方法是有问题的方法,调用“presenter.clear()”只是将字符串设置为空并将评分栏值设置为0。我添加了调试日志和值实际上发生了变化,尽管 UI 没有反映这种变化。我试图将它包装在一个 setstate 中,但 UI 仍然没有更新。我在 TabBarView 的另一个视图中遇到了完全相同的问题,子小部件在设置状态和更改后不会更新
    猜你喜欢
    • 2020-08-08
    • 2021-03-02
    • 2022-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-27
    • 2018-06-11
    相关资源
    最近更新 更多