简体   繁体   中英

How to make condition in Flutter

There is two files that have similar code, it is add and update area feature, that I decide to make it only one, with using condition.

You can see that two features have similar widgets, only different in texts.

在此处输入图像描述

Add Area Feature

在此处输入图像描述

Update Area Feature

在此处输入图像描述

In my case, when user want to adding area, the UI will display add area feature. When user want to updating area, the UI will display update area feature, but it only from one codebase.

Is it possible to make that kind of condition?

Here I copy paste the whole codes of add area feature. I don't have to copy paste update area because it has the similar codes.

class AddAreaItem extends StatefulWidget {
  const AddAreaItem({super.key, this.isUpdate = false});
  final bool isUpdate;

  @override
  State<AddAreaItem> createState() => _AddAreaItemState();
}

class _AddAreaItemState extends State<AddAreaItem> {
  //--------- selectedCategory_1 variable
  String selectedCategoryArea = '';

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 366,
      width: 514,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          SizedBox(
            height: 25,
          ),
          SizedBox(
            width: 434,
            height: 42,
            child: Wrap(
              alignment: WrapAlignment.spaceBetween,
              children: [
                Text(
                  widget.isUpdate ? 'Add Area' : 'Update Area',
                  style: heading2(
                    color: ColorName.blackPrimary,
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(top: 10),
                  child: InkWell(
                    child: SvgPicture.asset(
                      Assets.icons.closeIcon.path,
                      width: 16,
                      height: 16,
                    ),
                    onTap: () => {
                      Navigator.pop(context),
                    },
                  ),
                )
              ],
            ),
          ),

          //----------- TextField Code Area dan Category
          SizedBox(
            width: 435,
            child: Wrap(
              alignment: WrapAlignment.spaceAround,
              children: [
                Wrap(
                  direction: Axis.vertical,
                  children: [
                    Text(
                      'Area Code',
                      style: body1(
                        color: ColorName.blackPrimary,
                      ),
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    SizedBox(
                      width: 126,
                      height: 60,
                      child: TextField(
                        style: body1(color: ColorName.blackPrimary),
                        cursorColor: ColorName.blackPrimary,
                        decoration: InputDecoration(
                          hintText: 'Area Code',
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10),
                          ),
                          focusedBorder: const OutlineInputBorder(
                            borderRadius: BorderRadius.all(Radius.circular(10)),
                            borderSide: BorderSide(
                              color: ColorName.grey,
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
                Wrap(
                  direction: Axis.vertical,
                  children: [
                    Text(
                      'Category Area',
                      style: body1(
                        color: ColorName.blackPrimary,
                      ),
                    ),
                    const SizedBox(
                      height: 10,
                    ),
                    Container(
                      width: 288,
                      height: 56,
                      decoration: ShapeDecoration(
                        shape: RoundedRectangleBorder(
                          side: BorderSide(
                              style: BorderStyle.solid, color: ColorName.grey),
                          borderRadius: BorderRadius.all(
                            Radius.circular(10),
                          ),
                        ),
                      ),
                      child: DropdownButton<String>(
                        icon: Padding(
                          padding: const EdgeInsets.only(right: 10, top: 8),
                          child: SvgPicture.asset(
                            Assets.icons.dropdownIcon.path,
                            fit: BoxFit.scaleDown,
                          ),
                        ),
                        style: body1(color: ColorName.blackPrimary),
                        items: <String>[
                          'Block',
                          'Fining Line',
                        ].map((String value) {
                          return DropdownMenuItem(
                            value: value,
                            child: Text(value),
                          );
                        }).toList(),
                        hint: Padding(
                          padding: const EdgeInsets.only(top: 8, left: 10),
                          child: Text(
                              style: body1(color: ColorName.grey),
                              selectedCategoryArea.isEmpty
                                  ? 'Category Area'
                                  : selectedCategoryArea),
                        ),
                        borderRadius: BorderRadius.circular(10),
                        underline: const SizedBox(),
                        isExpanded: true,
                        onChanged: (value) {
                          if (value != null) {
                            setState(() {
                              selectedCategoryArea = value;
                            });
                          }
                        },
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),

          //----------- Tombol Add Area dan Cancel
          SizedBox(
            width: 425,
            child: Wrap(
              alignment: WrapAlignment.spaceBetween,
              children: [
                SizedBox(
                  width: 183,
                  height: 60,
                  child: OutlinedButton(
                    style: ButtonStyle(
                      shape: MaterialStateProperty.all(
                        RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(10),
                        ),
                      ),
                      side: MaterialStateProperty.all(
                        const BorderSide(
                          color: ColorName.darkBlue,
                        ),
                      ),
                    ),
                    child: Text(
                      'Cancel',
                      style: subtitle1(
                        color: ColorName.darkBlue,
                      ),
                    ),
                    onPressed: () {
                      Navigator.pop(context);
                    },
                  ),
                ),

                //------------- Tombol add area
                SizedBox(
                  width: 183,
                  height: 60,
                  child: OutlinedButton(
                    style: ButtonStyle(
                      backgroundColor: MaterialStateProperty.all(
                        ColorName.darkBlue,
                      ),
                      shape: MaterialStateProperty.all(
                        RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(10),
                        ),
                      ),
                      side: MaterialStateProperty.all(
                        const BorderSide(
                          color: ColorName.darkBlue,
                        ),
                      ),
                    ),
                    child: Text(
                      widget.isUpdate ? 'Add Area' : 'Update Area',
                      style: subtitle1(
                        color: ColorName.white,
                      ),
                    ),
                    onPressed: () {
                      if (widget.isUpdate) {
                        AddAreaSuccess().showCustomDialog(context);
                      } else {
                        UpdateAreaSuccess().showCustomDialog(context);
                      }
                    },
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(
            height: 25,
          ),
        ],
      ),
    );
  }
}

Firstly you need to define from where you know that the screen is updating screen or adding screen. I mean like

class AddAreaItem extends StatefulWidget {
  final bool isUpdate;
  const AddAreaItem({super.key, this.isUpdate=false});//IT MEANS THAT isUpdate is FALSE by default, but you can define it while creating AddAreaItem
  ...
}

Then in your widgets you can do like this:

Text(
  widget.isUpdate?'Update Area':'Add Area',
  //if it is inside Stateless widget then you use isUpdate? instead of widget.isUpdate
  style: subtitle1(
  color: ColorName.white,
  ),
),

Inside functions like onPressed you can just use like this:

onPressed: (){
   if(widget.isUpdating){
     AddAreaSuccess().showCustomDialog(context);
   }else{...}
}

You can pass those two values in the properties when rendering this widget. Then check if the properties are null then you are trying to add new data. But if those contains the value then its updating the data.

Something like this

class AreaWidget extends StatefulWidget {
  const AreaWidget({super.key, this.areaCode, this.areaName});
  final int? areaCode;
  final String? areaName;

  @override
  State<AreaWidget> createState() => _AreaWidgetState();
}

class _AreaWidgetState extends State<AreaWidget> {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Text(widget.areaCode == null ? "Add Area" : "Upate Area"),
    );
  }
}

You can then check value and make the changes according to the value. Even inside the function as well to call the specific add or update related code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM