Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to collapse the ExpansionTile on button click? - Flutter

Tags:

flutter

dart

I'm opening up a form to enter the details and close it upon filling everything and submitting it, but only the trailing icon is getting changed, also I'm trying to set the changes in the onExpansionChanged but not reflecting in the UI.

Updated Code

Scaffold(
        backgroundColor: Colors.grey.shade200,
        appBar: AppBar(
          title: TextButton(
            child: Text(count.toString()),
            onPressed: () {
              Navigator.push(context,
                  MaterialPageRoute(builder: (_) => RegisterLetterBookedListScreen()));
            },
          ),
          backgroundColor: ColorConstants.kPrimaryColor,
          elevation: 0,
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            MotionToast.success(
              title: 'Amount to be Collected',
              titleStyle: TextStyle(fontWeight: FontWeight.bold),
              description: '\u{20B9} $amountToBeCollected',
              descriptionStyle: TextStyle(fontSize: 20, fontWeight: FontWeight.w500),
              layoutOrientation: ORIENTATION.LTR,
              animationType: ANIMATION.FROM_LEFT,
              width: 300,
            ).show(context);
          },
          child: Text(
            '\u{20B9} $amountToBeCollected',
            style: TextStyle(fontSize: 20),
          ),
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
        ),
        body: Padding(
          padding: const EdgeInsets.all(20.0),
          child: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                //Article Details
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    

                //Sender Details
                ExpansionTile(
                  key: GlobalKey(),
                  trailing: (senderExpansion == false)
                      ? Icon(
                          MdiIcons.toggleSwitchOffOutline,
                          size: 40,
                          color: Colors.black54,
                        )
                      : Icon(MdiIcons.toggleSwitchOutline, size: 40, color: Colors.red),
                  onExpansionChanged: (value) {
                      senderExpansion = value;
                  },
                  maintainState: true,
                  initiallyExpanded: senderExpansion,
                  title: Text(
                    'Sender Details',
                    style: TextStyle(
                        fontWeight: FontWeight.bold,
                        color: senderHeadingColor,
                        fontSize: 20,
                        letterSpacing: 1),
                  ),
                  children: [
                    Column(
                      children: [
                        CInputForm(
                          readOnly: false,
                          iconData: Icons.person,
                          labelText: 'Name *',
                          controller: senderNameController,
                          textType: TextInputType.text,
                          typeValue: 'Name',
                          focusNode: senderNameFocusNode,
                        ),
                        CInputForm(
                          readOnly: false,
                          iconData: MdiIcons.home,
                          labelText: 'Address *',
                          controller: senderAddressController,
                          textType: TextInputType.multiline,
                          typeValue: 'Address',
                          focusNode: senderAddressFocusNode,
                        ),
                        Card(
                          elevation: 0,
                          child: TypeAheadFormField(
                            textFieldConfiguration: TextFieldConfiguration(
                                style: TextStyle(color: Colors.blueGrey),
                                controller: senderPinCodeCityController,
                                autofocus: false,
                                decoration: InputDecoration(
                                    prefixIcon: Icon(
                                      Icons.location_on_outlined,
                                      color: Colors.blueGrey,
                                    ),
                                    fillColor: Colors.white,
                                    filled: true,
                                    enabledBorder: OutlineInputBorder(
                                      borderSide: BorderSide(color: Colors.white),
                                    ),
                                    labelText: 'Pincode/Office Name *',
                                    labelStyle: TextStyle(
                                        color: ColorConstants.kAmberAccentColor),
                                    border: OutlineInputBorder(
                                        borderSide: BorderSide(color: Colors.white)))),
                            onSuggestionSelected:
                                (Map<String, String> suggestion) async {
                              senderPinCodeCityController.text = suggestion['pinCode']!;
                              senderCityController.text = suggestion['city']!;
                              senderStateController.text = suggestion['state']!;
                            },
                            itemBuilder: (context, Map<String, String> suggestion) {
                              return ListTile(
                                title: Text(suggestion['officeName']! +
                                    ", " +
                                    suggestion['pinCode']!),
                              );
                            },
                            suggestionsCallback: (pattern) async {
                              return await FetchPin.getSuggestions(pattern);
                            },
                            validator: (value) {
                              if (value!.isEmpty) {
                                issPin = false;
                                isLoading = false;
                              }
                            },
                          ),
                        ),
                        Visibility(
                          visible: issPin == false ? senderPinCodeCityController.text.isEmpty ? true : false : false,
                          child: Align(
                              alignment: Alignment.topLeft,
                              child: Padding(
                                padding: const EdgeInsets.only(left: 17.0),
                                child: Text('Select a Pincode/Office name', style: TextStyle(fontSize: 10, color: ColorConstants.kPrimaryColor),),
                              )),
                        ),
                        Visibility(
                          visible:
                              senderPinCodeCityController.text.isEmpty ? false : true,
                          child: CInputForm(
                            readOnly: true,
                            iconData: Icons.location_city,
                            labelText: 'City',
                            controller: senderCityController,
                            textType: TextInputType.text,
                            typeValue: 'City',
                            focusNode: senderPinCodeFocusNode,
                          ),
                        ),
                        Visibility(
                          visible:
                          senderPinCodeCityController.text.isEmpty ? false : true,
                          child: CInputForm(
                            readOnly: true,
                            iconData: Icons.location_city,
                            labelText: 'State',
                            controller: senderStateController,
                            textType: TextInputType.text,
                            typeValue: 'City',
                            focusNode: senderPinCodeFocusNode,
                          ),
                        ),
                        CInputForm(
                          readOnly: false,
                          iconData: MdiIcons.cellphone,
                          labelText: 'Mobile Number',
                          controller: senderMobileNumberController,
                          textType: TextInputType.number,
                          typeValue: 'MobileNumber',
                          focusNode: senderMobileFocusNode,
                        ),
                        CInputForm(
                          readOnly: false,
                          iconData: MdiIcons.email,
                          labelText: 'Email',
                          controller: senderEmailController,
                          textType: TextInputType.emailAddress,
                          typeValue: 'Email',
                          focusNode: senderEmailFocusNode,
                        ),
                      ],
                    )
                  ],
                ),

                //Addressee Details
                ExpansionTile(
                  trailing: (addresseeExpansion == false)
                      ? Icon(
                          MdiIcons.toggleSwitchOffOutline,
                          size: 40,
                          color: Colors.black54,
                        )
                      : Icon(MdiIcons.toggleSwitchOutline, size: 40, color: Colors.red),
                  onExpansionChanged: (value) {
                      addresseeExpansion = value;
                  },
                  maintainState: true,
                  title: Text('Addressee Details',
                      style: TextStyle(
                          fontWeight: FontWeight.bold,
                          color: addresseeHeadingColor,
                          fontSize: 20,
                          letterSpacing: 1)),
                  children: [
                    Column(
                      children: [
                        CInputForm(
                          readOnly: false,
                          iconData: Icons.person,
                          labelText: 'Name *',
                          controller: addresseeNameController,
                          textType: TextInputType.text,
                          typeValue: 'Name',
                          focusNode: addresseeNameFocusNode,
                        ),
                        CInputForm(
                          readOnly: false,
                          iconData: MdiIcons.home,
                          labelText: 'Address *',
                          controller: addresseeAddressController,
                          textType: TextInputType.multiline,
                          typeValue: 'Address',
                          focusNode: addresseeAddressFocusNode,
                        ),
                        Card(
                          elevation: 0,
                          child: TypeAheadFormField(
                            textFieldConfiguration: TextFieldConfiguration(
                                style: TextStyle(color: Colors.blueGrey),
                                controller: addresseePinCodeCityController,
                                autofocus: false,
                                decoration: InputDecoration(
                                    prefixIcon: Icon(
                                      Icons.location_on_outlined,
                                      color: Colors.blueGrey,
                                    ),
                                    fillColor: Colors.white,
                                    filled: true,
                                    enabledBorder: OutlineInputBorder(
                                      borderSide: BorderSide(color: Colors.white),
                                    ),
                                    labelText: 'Pincode/Office Name *',
                                    labelStyle: TextStyle(
                                        color: ColorConstants.kAmberAccentColor),
                                    border: OutlineInputBorder(
                                        borderSide: BorderSide(color: Colors.white)))),
                            onSuggestionSelected:
                                (Map<String, String> suggestion) async {
                              addresseePinCodeCityController.text =
                                  suggestion['pinCode']!;
                              addresseeCityController.text = suggestion['city']!;
                              addresseeStateController.text = suggestion['state']!;
                            },
                            itemBuilder: (context, Map<String, String> suggestion) {
                              return ListTile(
                                title: Text(suggestion['officeName']! +
                                    ", " +
                                    suggestion['pinCode']!),
                              );
                            },
                            suggestionsCallback: (pattern) async {
                              return await FetchPin.getSuggestions(pattern);
                            },
                            validator: (value) {
                              if (value!.isEmpty) {
                                isLoading = false;
                                isaPin = false;

                              }
                            },
                          ),
                        ),
                        Visibility(
                          visible: isaPin == false ? addresseePinCodeCityController.text.isEmpty ? true : false : false,
                          child: Align(
                              alignment: Alignment.topLeft,
                              child: Padding(
                                padding: const EdgeInsets.only(left: 17.0),
                                child: Text('Select a Pincode/Office name', style: TextStyle(fontSize: 10, color: ColorConstants.kPrimaryColor),),
                              )),
                        ),
                        Visibility(
                          visible: addresseePinCodeCityController.text.isEmpty
                              ? false
                              : true,
                          child: CInputForm(
                            readOnly: true,
                            iconData: Icons.location_city,
                            labelText: 'City',
                            controller: addresseeCityController,
                            textType: TextInputType.text,
                            typeValue: 'City',
                            focusNode: addresseePinCodeFocusNode,
                          ),
                        ),
                        Visibility(
                          visible: addresseePinCodeCityController.text.isEmpty
                              ? false
                              : true,
                          child: CInputForm(
                            readOnly: true,
                            iconData: Icons.location_city,
                            labelText: 'State',
                            controller: addresseeStateController,
                            textType: TextInputType.text,
                            typeValue: 'State',
                            focusNode: addresseePinCodeFocusNode,
                          ),
                        ),
                        CInputForm(
                          readOnly: false,
                          iconData: MdiIcons.cellphone,
                          labelText: 'Mobile Number',
                          controller: addresseeMobileNumberController,
                          textType: TextInputType.number,
                          typeValue: 'MobileNumber',
                          focusNode: addresseeMobileFocusNode,
                        ),
                        CInputForm(
                          readOnly: false,
                          iconData: MdiIcons.email,
                          labelText: 'Email',
                          controller: addresseeEmailController,
                          textType: TextInputType.emailAddress,
                          typeValue: 'Email',
                          focusNode: addresseeEmailFocusNode,
                        ),
                      ],
                    ),
                  ],
                ),

                //Submit
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Center(
                    child: ElevatedButton(
                      style: ButtonStyle(
                          backgroundColor:
                              MaterialStateProperty.all<Color>(Colors.white),
                          shape: MaterialStateProperty.all<RoundedRectangleBorder>(
                              RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(10),
                                  side: BorderSide(color: Colors.blueGrey)))),
                      onPressed: () async {
                        setState(() {
                          senderExpansion = !senderExpansion;
                          addresseeExpansion = !addresseeExpansion;
                        });
                        final ifPresent = await RegisterLetterTable()
                            .select()
                            .ArticleNumber
                            .equals(articleNumberController.text)
                            .toMapList();
                        if (ifPresent.isNotEmpty) {
                          ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                            content: Text('Article already scanned'),
                            behavior: SnackBarBehavior.floating,
                          ));
                        } else {
                          if (articleNumberController.text.isEmpty) {
                            setState(() {
                              articleNumberFocusNode.requestFocus();
                            });
                          } else if (weightController.text.isEmpty) {
                            setState(() {
                              weightFocusNode.requestFocus();
                            });
                          } else if (insuranceCheck == true) {
                            if (insuranceController.text.isEmpty)
                              insuranceFocusNode.requestFocus();
                          } else if (valuePayableCheck == true) {
                            if (valuePayablePostController.text.isEmpty)
                              valuePayableFocusNode.requestFocus();
                          }

                          if (senderNameController.text.isEmpty ||
                              senderAddressController.text.isEmpty ||
                              senderPinCodeCityController.text.isEmpty) {
                            setState(() {
                              senderExpansion = true;
                            });
                            if (addresseeNameController.text.isEmpty ||
                                addresseeAddressController.text.isEmpty ||
                                addresseePinCodeCityController.text.isEmpty) {
                              setState(() {
                                addresseeExpansion = true;
                              });
                            } else
                              setState(() {
                                addresseeExpansion = false;
                              });
                          } else
                            senderExpansion = false;
                          if (addresseeNameController.text.isEmpty ||
                              addresseeAddressController.text.isEmpty ||
                              addresseePinCodeCityController.text.isEmpty) {
                            setState(() {
                              addresseeExpansion = true;
                            });
                          } else
                            setState(() {
                              addresseeExpansion = false;
                            });

                          if (formGlobalKey.currentState!.validate()) {
                            formGlobalKey.currentState!.save();

                            showDialog<void>(
                                context: context,
                                barrierDismissible: false,
                                builder: (BuildContext context) {
                                  return ConformationDialog(
                                      articleNumber: articleNumberController.text,
                                      weight: weightController.text,
                                      prepaidAmount: prepaidAmountController.text,
                                      acknowledgement: acknowledgementCheck,
                                      insurance: insuranceCheck == true
                                          ? insuranceController.text
                                          : '',
                                      valuePayablePost: valuePayableCheck == true
                                          ? valuePayablePostController.text
                                          : '',
                                      amountToBeCollected:
                                          amountToBeCollectedController.text,
                                      senderName: senderNameController.text,
                                      senderAddress: senderAddressController.text,
                                      senderPinCode: senderPinCodeCityController.text,
                                      senderCity: senderCityController.text,
                                      senderState: senderStateController.text,
                                      senderMobileNumber:
                                          senderMobileNumberController.text,
                                      senderEmail: senderEmailController.text,
                                      addresseeName: addresseeNameController.text,
                                      addresseeAddress: addresseeAddressController.text,
                                      addresseePinCode:
                                          addresseePinCodeCityController.text,
                                      addresseeCity: addresseeCityController.text,
                                      addresseeState: addresseeStateController.text,
                                      addresseeMobileNumber:
                                          addresseeMobileNumberController.text,
                                      addresseeEmail: addresseeEmailController.text,
                                      function: () {
                                        Navigator.of(context).pop();
                                        printFunction();
                                      });
                                });
                          }
                        }
                      },
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: new Text(
                          'SUBMIT',
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(color: ColorConstants.kAmberAccentColor),
                        ),
                      ),
                    ),
                  ),
                )
              ],
            ),
          ),
        ))
like image 774
NaanAvanAlla Avatar asked Sep 06 '25 02:09

NaanAvanAlla


2 Answers

checkout below code it may help you,

class TestExpanTile extends StatefulWidget {
  @override
  TestExpanTileState createState() => new TestExpanTileState();
}

class TestExpanTileState extends State<TestExpanTile> {

  String senderDet = 'Sender Details ';
  bool formOpenFlag = true;

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        appBar: new AppBar(
          title: const Text('ExpansionTile'),
        ),
        body: new ExpansionTile(
          key: GlobalKey(),
          initiallyExpanded: formOpenFlag,
          onExpansionChanged: (val) {
            formOpenFlag = val; // update here on change
          },
          title: new Text(this.senderDet),
          backgroundColor: Theme.of(context).accentColor.withOpacity(0.025),
          children: <Widget>[
            new ListTile(
              title: const Text('Your Filling Form goes here'),
              onTap: () {},
            ),
            RaisedButton(
              onPressed: () {
                setState(() {
                  formOpenFlag = !formOpenFlag;
                });
              },
              child: Text("Close Tile On Submit"),
            )
          ],
        ),
      ),
    );
  }
}

like image 96
Jai Techie Avatar answered Sep 09 '25 01:09

Jai Techie


I created a simple solution to this very problem. Hope this helps.

Solution: https://github.com/TreyThomas93/flutter-expansion-tile-demo

like image 37
Trey Thomas Avatar answered Sep 09 '25 01:09

Trey Thomas