Flutter 如何刷新导航器上的状态。弹出或推入颤振

Flutter 如何刷新导航器上的状态。弹出或推入颤振,flutter,flutter-layout,flutter-dependencies,flutter-test,state-management,Flutter,Flutter Layout,Flutter Dependencies,Flutter Test,State Management,这里我有两个页面,第一个页面叫做BSP\u注册\u术语页面,第二个页面叫做BSP\u服务\u页面。当我在该页面的BSP\u signup\u terms上时,我必须根据选中的复选框选择一些复选框,它将显示一些数据。但问题是,它会向我显示完整的数据,但当我从BSP\u注册页面返回到BSP\u注册条款时,我会更改复选框,然后当我再次按下下一步按钮时,它不会更改与先前结果相同的结果 这是输出页面的图像 在这张图片中,我已经附加了两个屏幕输出,当我只选中一个复选框时,它将在服务页面中呈现一些值,当我返回

这里我有两个页面,第一个页面叫做
BSP\u注册\u术语
页面,第二个页面叫做
BSP\u服务\u页面
。当我在该页面的
BSP\u signup\u terms
上时,我必须根据选中的复选框选择一些复选框,它将显示一些数据。但问题是,它会向我显示完整的数据,但当我从
BSP\u注册页面
返回到
BSP\u注册条款
时,我会更改复选框,然后当我再次按下下一步按钮时,它不会更改与先前结果相同的结果

这是输出页面的图像

在这张图片中,我已经附加了两个屏幕输出,当我只选中一个复选框时,它将在服务页面中呈现一些值,当我返回到条款和条件页面并选中一个复选框时,它将不更新服务页面

这是我尝试过的代码。


BSP注册条款页面

class BspLicensedSignupTermsPage extends StatefulWidget {
  static const String routeName = "/bspLicensedSignupTerms";
  final BspSignupCommonModel bspSignupCommonModel;

  BspLicensedSignupTermsPage({
    Key key,
    @required this.bspSignupCommonModel,
  }) : super(key: key);

  @override
  _BspLicensedSignupTermsPageState createState() =>
      _BspLicensedSignupTermsPageState();
}

class _BspLicensedSignupTermsPageState
    extends State<BspLicensedSignupTermsPage> {
  @override
  void initState() {
    super.initState();
  }

  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  bool _isWalkIn = false;
  bool _isHome = false;
  bool _isOnDemand = false;



  Widget _buildselectcheckbox() {
    return Text(
      AppConstantsValue.appConst['bsplicensedsignupterms']['selectcheck']
          ['translation'],
    );
  }

  // Walkin
  _onCustomerWalkin(value) {
    setState(() {
      _isWalkIn = value;
    });
  }

  Widget _buildCustomerWalkIn() {
    return TudoConditionWidget(
      text: AppConstantsValue.appConst['bsplicensedsignupterms']
          ['CustomerWalkIn']['translation'],
      onChanged: (value) {
        print(value);
        _onCustomerWalkin(value);
      },
      validate: false,
    );
  }


  // Home
  _onCustomerInHome(value) {
    setState(() {
      _isHome = value;
    });
  }

  Widget _buildCustomerInHome() {
    return TudoConditionWidget(
      text: AppConstantsValue.appConst['bsplicensedsignupterms']
          ['CustomerInHome']['translation'],
      onChanged: (value) {
        _onCustomerInHome(value);
      },
      validate: false,
    );
  }

  Widget _buildCustomerInHomeHelp() {
    return Text(
      AppConstantsValue.appConst['bsplicensedsignupterms']['businesscheckhelp']
          ['translation'],
    );
  }

  // On Demand

  _onCustomerOnDemand(value) {
    setState(() {
      _isOnDemand = value;
    });
  }

  Widget _buildBusinessOnDemand() {
    return TudoConditionWidget(
      text: AppConstantsValue.appConst['bsplicensedsignupterms']
          ['BusinessOnDemand']['translation'],
      onChanged: (value) {
        _onCustomerOnDemand(value);
      },
      validate: false,
    );
  }

  Widget _buildBusinessOnDemandHelp() {
    return Text(AppConstantsValue.appConst['bsplicensedsignupterms']
        ['businessprovidehelp']['translation']);
  }

  @override
  Widget build(BuildContext context) {
    final appBar = AppBar(
      title: Text("Bsp Licensed Signup Terms and Condition"),
      leading: IconButton(
        icon: Icon(Icons.arrow_back_ios),
        onPressed: () {
          NavigationHelper.navigatetoBack(context);
        },
      ),
      centerTitle: true,
    );

    final bottomNavigationBar = Container(
      height: 56,
      //margin: EdgeInsets.symmetric(vertical: 24, horizontal: 12),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
          new FlatButton.icon(
            icon: Icon(Icons.close),
            label: Text('Clear'),
            color: Colors.redAccent,
            textColor: Colors.black,
            padding: EdgeInsets.symmetric(vertical: 10, horizontal: 30),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(7),
            ),
            onPressed: () {
              _formKey.currentState.reset();
            },
          ),
          new FlatButton.icon(
            icon: Icon(FontAwesomeIcons.arrowCircleRight),
            label: Text('Next'),
            color: colorStyles["primary"],
            textColor: Colors.white,
            padding: EdgeInsets.symmetric(vertical: 10, horizontal: 30),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(7),
            ),
            onPressed: () {
              if (_formKey.currentState.validate()) {
                if (_isHome == false &&
                    _isOnDemand == false &&
                    _isWalkIn == false) {
                  showDialog(
                      barrierDismissible: false,
                      context: context,
                      builder: (context) => ShowErrorDialog(
                            title: Text('Select Service'),
                            content: Text(
                              'Please select atleast one service type to proceed next',
                            ),
                          ));
                } else {
                  BspSignupCommonModel model = widget.bspSignupCommonModel;
                  model.isWalkin = _isWalkIn;
                  model.isHome = _isHome;
                  model.isOnDemand = _isOnDemand;
                  print(model.toJson());
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) =>
                          BspServicePage(bspSignupCommonModel: model),
                    ),
                  );
                }
              }
            },
          ),
        ],
      ),
    );
    return new Scaffold(
      appBar: appBar,
      bottomNavigationBar: bottomNavigationBar,
      body: Container(
        height: double.infinity,
        width: double.infinity,
        child: Stack(
          children: <Widget>[

            SingleChildScrollView(
              child: SafeArea(

                child: Form(
                  autovalidate: true,
                  key: _formKey,
                  child: Scrollbar(
                    child: SingleChildScrollView(
                      dragStartBehavior: DragStartBehavior.down,
                      padding: const EdgeInsets.symmetric(horizontal: 10.0),
                      child: new Container(
                        decoration: BoxDecoration(
                            borderRadius: new BorderRadius.circular(25)),
                        child: new Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            _buildselectcheckbox(),
                            _buildCustomerWalkIn(),
                            _buildCustomerInHome(),
                            _buildCustomerInHomeHelp(),
                            _buildBusinessOnDemand(),
                            _buildBusinessOnDemandHelp(),
                          ],
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
class BspServicePage extends StatefulWidget {
  static const String routeName = "/bspService";
  final BspSignupCommonModel bspSignupCommonModel;

  BspServicePage({
    Key key,
    @required this.bspSignupCommonModel,
  }) : super(key: key);

  @override
  _BspServicePageState createState() => _BspServicePageState();
}

class _BspServicePageState extends State<BspServicePage> {
  List<int> servicesIds = [];
  Map<String, bool> selection = {};
  List<BspServices.Service> selectedServices = [];
  SearchBarController _controller = new SearchBarController();
  String _searchText = '';
  bool refreshservices = true;

  @override
  void initState() {
    super.initState();
  }

  void _showErrorDialog(String message) {
    showDialog(
      barrierDismissible: false,
      context: context,
      builder: (context) => ShowErrorDialog(
        title: Text('An Error Occurred!'),
        content: Text(message),
      ),
    );
  }

  void refresh() {
    setState(() {
      refreshservices = !refreshservices;
    });
  }

  @override
  Widget build(BuildContext context) {
    var _bspServiceBloc = new BspServiceBloc();
    final appBar = SearchBar(
      controller: _controller,
      onQueryChanged: (String query) {
        print('Search Query $query');
        setState(() {
          _searchText = query;
        });
      },
      defaultBar: AppBar(
        centerTitle: true,
        leading: IconButton(
            icon: Icon(Icons.arrow_back_ios),
            onPressed: () {
              refresh();
              NavigationHelper.navigatetoBack(context);
            }),
        title: Text('Select Services'),
      ),
    );

    final bottomNavigationBar = Container(
      height: 56,
      // margin: EdgeInsets.symmetric(vertical: 24, horizontal: 12),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
          new FlatButton.icon(
            icon: Icon(Icons.close),
            label: Text('Clear'),
            color: Colors.redAccent,
            textColor: Colors.black,
            padding: EdgeInsets.symmetric(vertical: 10, horizontal: 30),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(7),
            ),
            onPressed: () {
              print('reseting the state');
              setState(() {
                selection = {};
                servicesIds = [];
              });
            },
          ),
          new FlatButton.icon(
            icon: Icon(FontAwesomeIcons.arrowCircleRight),
            label: Text('Next'),
            color: colorStyles["primary"],
            textColor: Colors.white,
            padding: EdgeInsets.symmetric(vertical: 10, horizontal: 30),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(7),
            ),
            onPressed: () {
              BspSignupCommonModel model = widget.bspSignupCommonModel;
              model.servicesIds = servicesIds;
              model.services = selectedServices;
              print('servicesIds at the next button');
              print(servicesIds);
              print(model.toJson());
              if (servicesIds.length == 0) {
                _showErrorDialog(
                    'You need to select at least one service to proceed next!');
              } else {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => BusinessProfilePage(
                      bspSignupCommonModel: model,
                    ),
                  ),
                );
              }
            },
          ),
        ],
      ),
    );
    return new Scaffold(
      appBar: appBar,
      bottomNavigationBar: bottomNavigationBar,
      body: new BspServiceScreen(
        bspServiceBloc: _bspServiceBloc,
        bspSignupCommonModel: widget.bspSignupCommonModel,
        servicesIds: servicesIds,
        selection: selection,
        searchQuery: _searchText,
        selectedServices: selectedServices,
        refresh: refresh,
      ),
    );
  }
}
类BspLicensedSignupTermsPage扩展StatefulWidget{
静态常量字符串routeName=“/bspLicensedSignupTerms”;
最终BspSignupCommonModel BspSignupCommonModel;
BspLicensedSignupTermsPage({
关键点,
@需要此.bspSignupCommonModel,
}):super(key:key);
@凌驾
_BspLicensedSignupTermsPageState createState()=>
_BspLicensedSignupTermsPageState();
}
类BspLicensedSignupTermsPageState
扩展状态{
@凌驾
void initState(){
super.initState();
}
最终的GlobalKey _formKey=GlobalKey();
bool_isWalkIn=false;
bool_isHome=false;
bool _isOnDemand=false;
小部件_buildselectcheckbox(){
返回文本(
AppConstantsValue.appConst['bsplicensedsignupterms']['selectcheck']
[“翻译”],
);
}
//步行
_onCustomerWalkin(值){
设置状态(){
_isWalkIn=值;
});
}
Widget_buildCustomerWalkIn(){
返回TudoConditionWidget(
text:AppConstantsValue.appConst['bsplicensedsignupterms']
['CustomerWalkIn']['translation'],
一旦更改:(值){
印刷品(价值);
_onCustomerWalkin(值);
},
验证:false,
);
}
//家
_onCustomerInHome(值){
设置状态(){
_isHome=价值;
});
}
小部件_buildCustomerHome(){
返回TudoConditionWidget(
text:AppConstantsValue.appConst['bsplicensedsignupterms']
['CustomerHome']['translation'],
一旦更改:(值){
_onCustomerInHome(值);
},
验证:false,
);
}
小部件_buildCustomerHomeHelp(){
返回文本(
AppConstantsValue.appConst['bsplicensedsignupterms']['businesscheckhelp']
[“翻译”],
);
}
//随需应变
_onCustomerOnDemand(值){
设置状态(){
_isOnDemand=值;
});
}
小部件_buildBusinessOnDemand(){
返回TudoConditionWidget(
text:AppConstantsValue.appConst['bsplicensedsignupterms']
['BusinessOnDemand']['translation'],
一旦更改:(值){
_onCustomerOnDemand(值);
},
验证:false,
);
}
小部件_buildBusinessOnDemandHelp(){
返回文本(AppConstantsValue.appConst['bsplicensedsignupterms']
['businessprovidehelp']['translation']);
}
@凌驾
小部件构建(构建上下文){
最终appBar=appBar(
标题:文本(“Bsp许可注册条款和条件”),
领先:IconButton(
图标:图标(图标、箭头、背面),
已按下:(){
NavigationHelper.navigatetoBack(上下文);
},
),
标题:对,
);
最终底部导航栏=容器(
身高:56,
//边缘:边缘组。对称(垂直:24,水平:12),
孩子:排(
mainAxisAlignment:mainAxisAlignment.space,
儿童:[
新FlatButton.icon(
图标:图标(Icons.close),
标签:文本(“清除”),
颜色:Colors.redAccent,
textColor:Colors.black,
填充:边缘组。对称(垂直:10,水平:30),
形状:圆形矩形边框(
边界半径:边界半径。圆形(7),
),
已按下:(){
_formKey.currentState.reset();
},
),
新FlatButton.icon(
图标:图标(FontAwesomeIcons.arrowCirclerRight),
标签:文本(“下一页”),
颜色:颜色样式[“主”],
textColor:Colors.white,
填充:边缘组。对称(垂直:10,水平:30),
形状:圆形矩形边框(
边界半径:边界半径。圆形(7),
),
已按下:(){
if(_formKey.currentState.validate()){
如果(_isHome==false&&
_isOnDemand==false&&
_isWalkIn==false){
显示对话框(
禁止:错误,
上下文:上下文,
生成器:(上下文)=>对话框(
标题:文本(“选择服务”),
内容:文本(
'请至少选择一种服务类型以继续下一步',
),
));
}否则{
BspSignupCommonModel=widget.BspSignupCommonModel;
model.isWalkin=\u isWalkin;
model.isHome=\u isHome;
model.isOnDemand=\u isOnDemand;
打印(model.toJson());
导航器。推(
上下文
材料路线(
生成器:(上下文)=>
BspServicePage(bspSignupCommonModel:model),
),
);
}
}
},
),
],
),
);
ret
class BspServiceScreen extends StatefulWidget {
  final BspServiceBloc _bspServiceBloc;
  final String searchQuery;
  final List<int> servicesIds;
  final Map<String, bool> selection;
  final BspSignupCommonModel bspSignupCommonModel;
  final List<BspServices.Service> selectedServices;
  final Function refresh;

  const BspServiceScreen({
    Key key,
    @required BspServiceBloc bspServiceBloc,
    @required this.bspSignupCommonModel,
    @required this.servicesIds,
    @required this.selection,
    @required this.selectedServices,
    @required this.refresh,
    this.searchQuery,
  })  : _bspServiceBloc = bspServiceBloc,
        super(key: key);

  @override
  BspServiceScreenState createState() {
    return new BspServiceScreenState(_bspServiceBloc);
  }
}

class BspServiceScreenState extends State<BspServiceScreen> {
  final BspServiceBloc _bspServiceBloc;

  BspServiceScreenState(this._bspServiceBloc);
  // Map<String, bool> _selection = {};

  @override
  void initState() {
    super.initState();
    bool isHome = widget.bspSignupCommonModel.isHome;
    bool isWalkIn = widget.bspSignupCommonModel.isWalkin;
    bool isOnDemand = widget.bspSignupCommonModel.isOnDemand;
    this._bspServiceBloc.dispatch(LoadBspServiceEvent(
          countryId: 1,
          isHome: isHome,
          isOnDemand: isOnDemand,
          isWalkin: isWalkIn,
        ));
  }

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

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<BspServiceBloc, BspServiceState>(
      bloc: widget._bspServiceBloc,
      builder: (
        BuildContext context,
        BspServiceState currentState,
      ) {
        if (currentState is UnBspServiceState) {
          return Center(child: CircularProgressIndicator());
        }
        if (currentState is ErrorBspServiceState) {
          return new Container(
            child: new Center(
              child: new Text(currentState.errorMessage ?? 'Error'),
            ),
          );
        }
        if (currentState is InBspServiceState) {
          // print(
          //     'in bsp service state, ${currentState.bspServices.servicesByCountry.length}');
          if (currentState.bspServices.servicesByCountry.length == 0) {
            return Container(
              child: Center(
                child: Text("No Services available for this combination"),
              ),
            );
          } else {
            return new Container(
              child:
                  _renderServices(currentState.bspServices.servicesByCountry),
            );
          }
        }
        return Container();
      },
    );
  }

  List<ServicesByCountry> finalList = new List();

  ListView _renderServices(List<ServicesByCountry> lovCountryServices) {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (widget.searchQuery != '') {
        finalList.clear();
        lovCountryServices.forEach((ServicesByCountry data) {
          if (data.name
              .toLowerCase()
              .contains(widget.searchQuery.toLowerCase())) {
            setState(() {
              finalList.add(data);
            });
          } else {
            data.services.forEach((ServiceList.Service services) {
              if (services.name
                  .toLowerCase()
                  .contains(widget.searchQuery.toLowerCase())) {
                setState(() {
                  finalList.add(data);
                });
              }
            });
          }
        });
      } else {
        setState(() {
          finalList.clear();
          finalList.addAll(lovCountryServices);
        });
      }
    });
    return ListView.builder(
      shrinkWrap: true,
      padding: const EdgeInsets.all(8.0),
      itemCount: finalList.length,
      itemBuilder: (BuildContext context, int index) {
        ServicesByCountry item = finalList[index];
        List itemsList = item.services;
        return ExpansionTile(
          title: Text(item.name),
          children: List.generate(itemsList.length, (i) {
            widget.selection[itemsList[i].name] =
                widget.selection[itemsList[i].name] ?? itemsList[i].isSelected;
            return CheckboxListTile(
              title: Text(itemsList[i].name),
              value: widget.selection[itemsList[i].name],
              onChanged: (val) {
                setState(() {
                  widget.selection[itemsList[i].name] = val;
                  if (val) {
                    widget.servicesIds.add(itemsList[i].id);

                    List<BspServices.Service> services =
                        widget.selectedServices.where((service) {
                      return service.mainCategory == item.name;
                    }).toList();

                    SubCategory subService = new SubCategory(
                      id: itemsList[i].id,
                      name: itemsList[i].name,
                    );

                    List<SubCategory> subCategories = [];
                    if (services.length == 0) {
                      subCategories.add(subService);
                      widget.selectedServices.add(
                        new BspServices.Service(
                          mainCategory: item.name,
                          mainCategoryId: item.id,
                          subCategory: subCategories,
                        ),
                      );
                    } else {
                      print('services in else');
                      print(services[0].subCategory);
                      subCategories = services[0].subCategory;
                      subCategories.add(subService);
                    }
                  } else {
                    widget.servicesIds.removeWhere((service) {
                      return service == itemsList[i].id;
                    });

                    List<BspServices.Service> services =
                        widget.selectedServices.where((service) {
                      return service.mainCategory == item.name;
                    }).toList();

                    services[0].subCategory.removeWhere((subService) {
                      return subService.id == itemsList[i].id;
                    });
                  }
                });
                print('widget.servicesIds after set state');
                print(widget.servicesIds);
              },
            );
          }),
        );
      },
    );
  }
}
Navigator.push(context, MaterialPageRoute(builder: (context) => Page2())).then((value) {
  setState(() {
    // refresh state
  });
});
void redirectToNextScreen() async {
    final Route route = MaterialPageRoute(
        builder: (context) => BspServicePage(bspSignupCommonModel: model));
    final result = await Navigator.push(mContext, route);
    try {
      if (result != null) {
        if (result) {
          //Return callback here.
        }
      }
    } catch (e) {
      print(e.toString());
    }
  }
Navigator.pop(mContext, true); //true means refresh back page and false means not refresh.