在未显示为单独小部件的小部件内实现多个小部件

时间:2020-10-26 16:17:21

标签: flutter scaffold statefulwidget

我有一个多个StatefulWidget作为列表,并且我在StatefulWidget中进行导航,但是运行不正确,而是将控件附加到另一个中。

所有小部件代码的容器:

t2

附件页面代码:

import 'dart:collection';


class FormContainerPage extends StatefulWidget {
  final bool isInternal;
  final MainEntityListModel entity;
  static final List<AttachmentImage> imageList = List<AttachmentImage>();
  static final LinkedHashMap<String, dynamic> listData = new LinkedHashMap();

  FormContainerPage({this.isInternal, this.entity});

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

class _FormContainerPageState extends State<FormContainerPage>
    implements AlertDialogCallBack, LoaderCallBack {
  final Utility _utility = new Utility();
  List<Widget> _fragments = List<Widget>();
  int _currentIndex = 0;
  final List<int> _backStack = [0];
  Widget _backImage;
  Widget _nextImage;
  ProgressBar _sendingMsgProgressBar;
  bool _certifyCheckbox = false;

  @override
  void initState() {
    super.initState();
    _sendingMsgProgressBar = ProgressBar();
  }

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

  @override
  Widget build(BuildContext context) {

    return new BlocListener<FormContainerPageBloc, FormContainerPageState>(
      listener: (context, state) {
        if (state is FormContainerPageFailure) {
          Scaffold.of(context).showSnackBar(
            SnackBar(
              content: Text('${state.error}'),
              backgroundColor: Colors.red,
            ),
          );
        }
      },
      child: BlocBuilder<FormContainerPageBloc, FormContainerPageState>(
        builder: (context, state) {
          if (state is FormContainerFormLoaded) {
           _getListings(state.formDataList);
            return WillPopScope(
              onWillPop: () {
                return customPop(context);
              },
              child: Scaffold(
                appBar: PreferredSize(
                  preferredSize: Size.fromHeight(AppBar().preferredSize.height),
                  child: AppBar(
                    backgroundColor: Colors.white,
                    automaticallyImplyLeading: false,
                    centerTitle: true,
                    elevation: 2,
                    title: FutureBuilder(
                        future: null,
                        builder: (context, snapshot) {
                          _setImages(context);
                          return Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: <Widget>[
                              _backImage,
                              Text(
                                widget.entity.entityName,
                                style: TextStyle(
                                  fontFamily: _utility.langID == 1
                                      ? 'regularAR'
                                      : 'regular',
                                  color: Constant.companyColors[2],
                                  fontSize: 18,
                                ),
                              ),
                              _nextImage,
                            ],
                          );
                        }),
                  ),
                ),

                body: Column(
                  children: [
                    Expanded(
                        child: _fragments[_currentIndex],
                    ),
                  ],
                ),

                bottomSheet: CheckboxListTile(
                  title: Container(
                    constraints: new BoxConstraints(
                        maxWidth: MediaQuery.of(context).size.width - 60),
                    child: Text(
                      S.of(context).certifying_statement,
                      style: TextStyle(fontFamily: 'regular'),
                    ),
                  ),
                  controlAffinity: ListTileControlAffinity.leading,
                  onChanged: (bool value) {
                    setState(() {
                      if (value != null) {
                        _certifyCheckbox = value;
                      } else {
                        _certifyCheckbox = false;
                      }
                    });
                  },
                  tristate: true,
                  value: _certifyCheckbox,
                ),
              ),
            );
          } else {
            return _utility.getLoadingIndicator();
          }
        },
      ),
    );
  }

  _getListings(List<FormData> formDataList) async{
    int i = 0;
    for (i = 0; i < formDataList.length; i++) {
      FormData dataField = formDataList[i];
      if (dataField.isAttachmentTab) {
        _fragments.add(
          new AttachmentPage(formData: dataField),
        );
      } else {
        _fragments.add(new BlocProvider<DynamicPageBloc>(
          create: (context) => new DynamicPageBloc()
            ..add(new LoadForm(
                appEntityID: widget.entity.appEntityID, formData: dataField)),
          child: new DynamicPage(formData: dataField, entity: widget.entity),
        ));
      }
    }
  }

  void navigateTo(BuildContext context, int index, String type) {
    Widget _widget = _fragments[index];
    bool attachmentEmptyError = false;
    switch (type) {
      case "NEXT":
        {
          if (_currentIndex == _fragments.length - 1) {
            if (_widget is BlocProvider<DynamicPageBloc>) {
              String data = (_widget.child as DynamicPage)
                  .child
                  .checkData((_widget.child as DynamicPage).listings);
              if (data == "SUCCESS") {
                if (_certifyCheckbox) {
                  callServiceConfirmation(
                      context,
                      S.of(context).createEntity_confirmation_message,
                      S.of(context).createEntity_confirmation_title);
                } else {
                  _utility.showToast(context, S.of(context).certifying_error);
                }
              }
            }
          } else {
            if (_widget is AttachmentPage) {
              var child = _widget.child;
              String data = child.checkData();

              if (data == "SUCCESS") {
                attachmentEmptyError = false;
              } else {
                attachmentEmptyError = true;
              }

              if (attachmentEmptyError) {
                _utility.showToast(context, "Attachment empty");
              } else {
                _backStack.add(index);
                setState(() {
                  _currentIndex++;
                });
                _setImages(context);
              }
            } else if (_widget is BlocProvider<DynamicPageBloc>) {
              if (_widget is BlocProvider<DynamicPageBloc>) {
                String data = (_widget.child as DynamicPage)
                    .child
                    .checkData((_widget.child as DynamicPage).listings);
                if (data == "SUCCESS") {
                  _backStack.add(index);
                  setState(() {
                    _currentIndex++;
                  });
                  _setImages(context);
                }
              }
            }
          }
        }
        break;
      case "BACK":
        {
          if (_currentIndex == 0) {
            _utility.shoAlertDialog(
                context,
                "Quit theForm",
                "Are you sure you want to Quit " +
                    widget.entity.entityName +
                    " ?",
                this);
          } else {
            setState(() {
              _currentIndex--;
              _backStack.add(_currentIndex);
              _setImages(context);
            });
          }
        }
        break;
    }
  }

  void navigateBack(BuildContext context, int index) {
    setState(() {
      if (_currentIndex != 0) {
        _currentIndex = index;
      } else {
        _utility.shoAlertDialog(
            context,
            "Quit theForm",
            "Are you sure you want to Quit " + widget.entity.entityName + " ?",
            this);
      }
    });
  }

  Future<bool> customPop(BuildContext context) {
    if (_backStack.length > 1) {
      _backStack.removeAt(_backStack.length - 1);
      navigateBack(context, _backStack[_backStack.length - 1]);
      return Future.value(false);
    } else {
      return Future.value(true);
    }
  }

  void callServiceConfirmation(BuildContext context, String title, String msg) {
    showDialog(
        context: context,
        builder: (mContext) {
          return Dialog(
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(20.0)),
            child: Wrap(
              children: [
                Column(
                  children: [
                    Container(
                      height: 20,
                    ),
                    Text(
                      title,
                      textAlign: TextAlign.center,
                      style: TextStyle(
                          fontFamily:
                              _utility.langID == 1 ? 'regularAR' : 'regular',
                          color: Colors.black,
                          fontWeight: FontWeight.bold,
                          fontSize: 18.0),
                    ),
                    Container(
                      height: 20,
                    ),
                    Text(
                      msg,
                      style: TextStyle(
                          fontFamily:
                              _utility.langID == 1 ? 'regularAR' : 'regular',
                          color: Colors.grey[600],
                          fontWeight: FontWeight.bold,
                          fontSize: 16.0),
                    ),
                    Container(
                      height: 10,
                    ),
                    Divider(
                      color: Colors.grey,
                      thickness: 1.0,
                    ),
                    Padding(
                      padding: const EdgeInsets.only(
                          top: 0, right: 16.0, bottom: 0, left: 16.0),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: [
                          FlatButton(
                            onPressed: () {
                              Navigator.pop(context);
                            },
                            child: Text(
                              S.of(context).cancel,
                              style: TextStyle(
                                  fontFamily: _utility.langID == 1
                                      ? 'regularAR'
                                      : 'regular',
                                  color: Constant.companyColors[012],
                                  fontWeight: FontWeight.bold),
                            ),
                            color: Colors.transparent,
                          ),
                          Container(
                            width: 10,
                          ),
                          FlatButton(
                            onPressed: () {
                              Navigator.pop(context);
                              if (widget.entity.entityTitle == "OWNERS") {
                                BlocProvider.of<FormContainerPageBloc>(context)
                                  ..add(CallService(
                                    entity: widget.entity,
                                    loaderCallBack: this,
                                    context: context,
                                  ));
                              } else {
                                BlocProvider.of<FormContainerPageBloc>(context)
                                  ..add(CallService(
                                      entity: widget.entity,
                                      loaderCallBack: this,
                                      context: context));
                              }
                            },
                            child: Text(
                              S.of(context).ok,
                              style: TextStyle(
                                  fontFamily: _utility.langID == 1
                                      ? 'regularAR'
                                      : 'regular',
                                  color: Constant.companyColors[013],
                                  fontWeight: FontWeight.bold),
                            ),
                            color: Colors.transparent,
                          ),
                        ],
                      ),
                    )
                  ],
                ),
              ],
            ),
          );
        });
  }

  void _setImages(BuildContext context) {
    Icon _backIcon = Icon(Icons.keyboard_arrow_left,
        size: 30, color: Constant.companyColors[02]);
    Icon _nextIcon = Icon(Icons.keyboard_arrow_right,
        size: 30, color: Constant.companyColors[02]);
    Icon _closeIcon =
        Icon(Icons.close, size: 25, color: Constant.companyColors[02]);
    Icon _doneIcon =
        Icon(Icons.check, size: 30, color: Constant.companyColors[02]);

    if (_currentIndex == 0) {
      _backImage = FlatButton(
        child: _closeIcon,
        onPressed: () {
          navigateTo(context, _currentIndex, "BACK");
        },
      );
      _nextImage = FlatButton(
        child: _nextIcon,
        onPressed: () {
          navigateTo(context, _currentIndex, "NEXT");
        },
      );
    } else if (_currentIndex == _fragments.length - 1) {
      _backImage = FlatButton(
        child: _backIcon,
        onPressed: () {
          navigateTo(context, _currentIndex, "BACK");
        },
      );
      _nextImage = FlatButton(
        child: _doneIcon,
        onPressed: () {
          navigateTo(context, _currentIndex, "NEXT");
        },
      );
    } else {
      _backImage = FlatButton(
        child: _backIcon,
        onPressed: () {
          navigateTo(context, _currentIndex, "BACK");
        },
      );
      _nextImage = FlatButton(
        child: _nextIcon,
        onPressed: () {
          navigateTo(context, _currentIndex, "NEXT");
        },
      );
    }
  }

  @override
  void onDialogCancel(BuildContext context) {
    Navigator.pop(context);
  }

  @override
  void onDialogConfirm(BuildContext context) {
    Navigator.pop(context);
    Navigator.pop(context);
    FormContainerPage.listData.clear();
    FormContainerPage.imageList.clear();
  }

  @override
  void showSendingProgressBar() {
    _sendingMsgProgressBar.show(context);
  }

  @override
  void hideSendingProgressBar() {
    _sendingMsgProgressBar.hide();
  }

  @override
  void showMessage(String msg) {
    _utility.showToast(context, msg);
  }

  @override
  void registrationFailed(String responseMessage) {
    showMessage(responseMessage);
  }

  @override
  void registrationSuccess(String responseMessage) {
    Navigator.pop(context, _fragments);
  }
}

和最后一个DynamicPage代码:

class AttachmentPage extends StatefulWidget {
  final FormData formData;

  _AttachmentPageState child;

  @override
  _AttachmentPageState createState() {
    child = new _AttachmentPageState();
    return child;
  }

  AttachmentPage({this.formData});
}

class _AttachmentPageState extends State<AttachmentPage> {
  final _picker = ImagePicker();
  AttachmentsAdapter _adapter;
  List<AttachmentImage> _imageList = new List<AttachmentImage>();

  void onItemClick(int index, AttachmentImage obj) {
    _showAlertDialog(index);
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
        future: _getListings(),
        initialData: [],
        builder: (context, snapshot) {
          return Scaffold(
              body: Column(
            children: [
              Container(
                alignment: Alignment.center,
                padding: EdgeInsets.all(20.0),
                child: TabTitle(
                  tabTitle: widget.formData.tabTitle,
                ),
              ),
              Expanded(
                child: _adapter.getView(),
              ),
            ],
          ));
        });
  }




  _getListings() {
    for (int i = 0; i < widget.formData.tabConfig.length; i++) {
      TabConfig tabConfig = widget.formData.tabConfig[i];
      AttachmentImage attachmentImage = AttachmentImage(
          widget: Container(
            width: double.infinity,
            decoration: BoxDecoration(
                color: Constant.companyColors[50],
                borderRadius: BorderRadius.all(Radius.circular(20))),
            margin: EdgeInsets.all(8),
            child: Column(children: <Widget>[
              FlatButton(
                onPressed: () {
                  _showAlertDialog(i);
                },
                color: Colors.transparent,
                child: Container(
                    child: Column(
                  children: <Widget>[
                    Image(image: AssetImage('assets/images/upload4.png')),
                    Text(
                      "Upload your image here",
                      style: TextStyle(
                          color: Constant.companyColors[60],
                          fontFamily: 'regular',
                          fontSize: 16.0),
                    ),
                  ],
                )),
              ),
            ]),
          ),
          file: new File(""),
          config: tabConfig,
          type: tabConfig.type);
      if (FormContainerPage.imageList.isNotEmpty) {
        bool exist = false;
        for (var item in FormContainerPage.imageList) {
          if (item.config.type == tabConfig.type) {
            exist = true;
          }
        }
        if (!exist) {
          FormContainerPage.imageList.add(attachmentImage);
        }
      } else {
        FormContainerPage.imageList.add(attachmentImage);
      }
      if (_imageList!=null) {
        if(_imageList.isNotEmpty) {
          bool exist = false;
          for (var item in _imageList) {
            if (item.config.type == tabConfig.type) {
              exist = true;
            }
          }
          if (!exist) {
            _imageList.add(attachmentImage);
          }
        }else{
          _imageList.add(attachmentImage);
        }
      } else {
        _imageList.add(attachmentImage);
      }
    }
    _adapter = new AttachmentsAdapter(context, _imageList, onItemClick);
  }

  _showAlertDialog(int index) {
    
  }

  Future getImageCamera(int index) async {
    
  }

  Future getImageGallery(int index) async {
   
  }

  String checkData() {
    String returnResult = "SUCCESS";
    for (var item in _imageList) {
      if (item.config.required) {
        if (item.file.path.isEmpty) {
          returnResult = "EMPTY";
        } else {
          returnResult = "SUCCESS";
        }
      } else {
        returnResult = "EMPTY";
      }
    }
    return returnResult;
  }
}

当我从第一个附件页面转到下一个附件页面时,结果是包含四个图像的列表,知道每个图像仅包含两张图片

0 个答案:

没有答案