how to handle multiple dynamic checkbox in datatable in flutter?

-3

i'm building an app in which data like docket number, booking date, etc. coming from the api in the data table. so how can i handle the dynamic checkbox here and by clicking on the checkbox that row got selected and after that i want to post that row or multiple row data to the api.

class _ChallanEntry13State extends State<ChallanEntry1> {
  TextEditingController _number = new TextEditingController();
  TextEditingController _message = new TextEditingController();
  Map<String, dynamic> _categories = {
    "responseCode": "1",
    "responseText": "List categories.",
    "responseBody": [
      {"category_id": "5"},
    ],
  };
  void _onCategorySelected(bool selected, category_id) {
    if (selected == true) {
      setState(() {
        _selecteCategorys.add(category_id);
      });
    } else {
      setState(() {
        _selecteCategorys.remove(category_id);
      });
    }
  }
  var finaldate;
  var finaldate1;
  var responseResult;
  bool enable=false;
  List _selecteCategorys = List();

  List<String> Docket_no = [];
  List<String> Booking_date = [];
  List<String> booking_mode = [];
  List<String> originbranch = [];
  List<String> destinationbranch = [];
  List<String> consigner_name = [];
  List<String> consignee_name = [];
  List<String> pending_package = [];
  List<String> pending_weight = [];
  List<String> pending_freight = [];
  var table;
  void callDatePicker() async {
    var order = await getDate();
    setState(() {
      finaldate = order;
    });
  }

  void callDatePicker1() async {
    var order = await getDate();
    setState(() {
      finaldate1 = order;
    });
  }

  Future<DateTime> getDate() {
    return showDatePicker(
      context: context,
      initialDate: DateTime.now(),
      firstDate: DateTime(2018),
      lastDate: DateTime.now(),
      builder: (BuildContext context, Widget child) {
        return Theme(
          data: ThemeData.light(),
          child: child,
        );
      },
    );
  }

  Future<void> postSearch(body) async {
    var response = await http.post(
      URLs.manifest_serach,
      body: body,
    );

    setState(() {
      try {
        var convertJsonData = json.decode(response.body);
        if (convertJsonData['status'] == "1") {
          responseResult = convertJsonData['data'];
          table = "ok";
          print(table);
          for (int i = 0; i < responseResult.length; i++) {
            Docket_no.add(responseResult[i]['Docket_no']);
            Booking_date.add(responseResult[i]['Booking_date']);
            booking_mode.add(responseResult[i]['booking_mode']);
            originbranch.add(responseResult[i]['originbranch']);
            destinationbranch.add(responseResult[i]['destinationbranch']);
            consigner_name.add(responseResult[i]['consigner_name']);
            consignee_name.add(responseResult[i]['consignee_name']);
            pending_package.add(responseResult[i]['pending_package']);
            pending_weight.add(responseResult[i]['pending_weight']);
            pending_freight.add(responseResult[i]['pending_freight']);
            print('Docket_no are ${Docket_no}');
            print('Booking_date are ${Booking_date}');
            print('booking_mode are ${booking_mode}');
            print('originbranch are ${originbranch}');
            print('destinationbranch are ${destinationbranch}');
            print('consigner_name are ${consigner_name}');
            print('consignee_name are ${consignee_name}');
            print('pending_package are ${pending_package}');
            print('pending_weight are ${pending_weight}');
            print('pending_freight are ${pending_freight}');
          }
        } else if (convertJsonData['status'] == "0"){
          Fluttertoast.showToast(
            msg: 'Docket Number Not Found',
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.BOTTOM,
          );
        }
        else{
          Fluttertoast.showToast(
            msg: 'Failed',
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.BOTTOM,
          );
        }
      }
      catch (e) {
        Fluttertoast.showToast(
          msg: e.toString(),
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.BOTTOM,
        );
      }
    });
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          'AIOSS',
          style: TextStyle(color: Colors.white, fontSize: 16),
        ),
        actions: <Widget>[
          Padding(
              padding: EdgeInsets.only(right: 20.0),
              child: GestureDetector(
                onTap: () {
                  whatsapp();
                },
                child: Icon(
                  Icons.chat,
                  size: 26.0,
                ),
              )),
          Padding(
              padding: EdgeInsets.only(right: 20.0),
              child: GestureDetector(
                onTap: () {
                  Utils.openPhoneCall(phoneNumber: '+4912388128311');
                },
                child: Icon(
                  Icons.call,
                ),
              )),
        ],
        elevation: 0,
        backgroundColor: Colors.cyan,
      ),
      body: SingleChildScrollView(
        child: Container(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                height: 50,
                color: Colors.grey.shade300,
                child: Row(
                  children: [
                    Padding(
                      padding: const EdgeInsets.only(left: 8.0),
                      child: GestureDetector(
                        onTap: () {
                          Navigator.of(context).pop();
                        },
                        child: Icon(
                          Icons.arrow_back_outlined,
                          color: Colors.black,
                          size: 30.0,
                        ),
                      ),
                    ),
                    Spacer(),
                    GestureDetector(
                      onTap: (){
                        Navigator.push(context, MaterialPageRoute(builder: (context) => CheckBoxInListview()));
                      },
                      child: Text(
                        'Challan Entry'.toUpperCase(),
                        style: TextStyle(
                            color: Colors.black,
                            fontSize: 16,
                            fontWeight: FontWeight.bold),
                      ),
                    ),
                    Spacer(),
                  ],
                ),
              ),
              Container(
                height: MediaQuery.of(context).size.height/20,
                decoration: BoxDecoration(
                  boxShadow: [
                    BoxShadow(color: Colors.black38, blurRadius: 15.0)
                  ],
                  color: Color(0xff6593bf),
                  // gradient: LinearGradient(colors: <Color>[
                  //   Colors.cyan,
                  //   Color(0xff194796)
                  // ])
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text('Docket List to generate Menifest Entry :-' ,style: TextStyle(
                        fontSize: 16.0,
                        fontWeight: FontWeight.bold,
                        color: Colors.white70)),
                  ],
                ),
              ),
              Container(
                  margin: const EdgeInsets.fromLTRB(15.0, 15.0, 15.0, 10.0),
                  child: Text(' From Date:',
                      style: TextStyle(
                          fontSize: 16.0,
                          fontWeight: FontWeight.bold,
                          color: Colors.black))),
              GestureDetector(
                onTap: () => callDatePicker(),
                child: Container(
                  margin: const EdgeInsets.all(10.0),
                  decoration: BoxDecoration(
                      border: Border.all(color: Colors.grey, width: 1),
                      borderRadius: BorderRadius.circular(5),
                      color: Colors.grey[200]),
                  child: finaldate == null
                      ? Row(
                    children: [
                      Padding(
                        padding: const EdgeInsets.all(10.0),
                        child: Text(
                          "Click to Select a Date",
                          textScaleFactor: 1.0,
                        ),
                      ),
                    ],
                  )
                      : Row(
                    children: [
                      Padding(
                        padding: const EdgeInsets.all(10.0),
                        child: Text(
                          "$finaldate".split(' ')[0],
                          textScaleFactor: 1.0,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              Container(
                  margin: const EdgeInsets.fromLTRB(15.0, 15.0, 15.0, 10.0),
                  child: Text(' TO Date:',
                      style: TextStyle(
                          fontSize: 16.0,
                          fontWeight: FontWeight.bold,
                          color: Colors.black))),
              GestureDetector(
                onTap: () => callDatePicker1(),
                child: Container(
                  margin: const EdgeInsets.all(10.0),
                  decoration: BoxDecoration(
                      border: Border.all(color: Colors.grey, width: 1),
                      borderRadius: BorderRadius.circular(5),
                      color: Colors.grey[200]),
                  child: finaldate1 == null
                      ? Row(
                    children: [
                      Padding(
                        padding: const EdgeInsets.all(10.0),
                        child: Text(
                          "Click to Select a Date",
                          textScaleFactor: 1.0,
                        ),
                      ),
                    ],
                  )
                      : Row(
                    children: [
                      Padding(
                        padding: const EdgeInsets.all(10.0),
                        child: Text(
                          "$finaldate1".split(' ')[0],
                          textScaleFactor: 1.0,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              SizedBox(height:  MediaQuery.of(context).size.height/30,),
              Center(
                child: RaisedButton.icon(
                  onPressed: () {
                    var body = {
                      'companyCode': "${widget.CompanyCode}",
                      'booking_date1': '$finaldate',
                      'booking_date2': '$finaldate1',
                      'current_branch' : '${widget.Branch}',
                      'destination' : widget.destination != null ? '${widget.destination}' : '${widget.destination2}',
                      'destination_type' : widget.destination_index == 0 ? '${widget.destination_type1}' : '${widget.destination_type2}'
                    };
                    postSearch(body);
                  },
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.all(Radius.circular(10.0))),
                  label: Text(
                    'SEARCH',
                    style: TextStyle(color: Colors.white),
                  ),
                  icon: Icon(
                    Icons.search,
                    color: Colors.white,
                  ),
                  textColor: Colors.white,
                  splashColor: Colors.cyan.shade300,
                  color: Colors.cyan,
                ),
              ),
              table != null ? Container(margin:EdgeInsets.only(top: 10),child: _getBodyWidget()): Text(""),
            ],
          ),
        ),
      ),
      drawer: NaviDrawer(),
    );
  }

  void whatsapp() {
    showGeneralDialog(
        context: context,
        pageBuilder: (context, anim1, anim2) {},
        barrierDismissible: true,
        barrierColor: Colors.black.withOpacity(0.4),
        barrierLabel: '',
        transitionBuilder: (context, anim1, anim2, child) {
          return Transform.rotate(
            angle: math.radians(anim1.value * 360),
            child: Opacity(
              opacity: anim1.value,
              child: AlertDialog(
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.all(Radius.circular(32.0))),
                contentPadding: EdgeInsets.only(top: 0.0),
                content: Container(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      Container(
                        decoration: BoxDecoration(
                          color: Colors.grey.shade300,
                          borderRadius: BorderRadius.only(
                              topLeft: Radius.circular(32.0),
                              topRight: Radius.circular(32.0)),
                        ),
                        padding: EdgeInsets.only(top: 20.0, bottom: 20.0),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          mainAxisSize: MainAxisSize.min,
                          children: <Widget>[
                            Text(
                              "Enter the Below Details",
                              style: TextStyle(fontSize: 24.0),
                            ),
                          ],
                        ),
                      ),
                      Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          SizedBox(
                            height: MediaQuery.of(context).size.height / 30,
                          ),
                          Container(
                            margin: EdgeInsets.only(left: 10, right: 10),
                            child: TextFormField(
                                keyboardType: TextInputType.number,
                                controller: _number,
                                decoration: InputDecoration(
                                  labelText: 'Whatsapp Number',
                                  filled: true,
                                  fillColor: Colors.cyanAccent.shade100,
                                  enabledBorder: OutlineInputBorder(
                                    borderRadius:
                                    BorderRadius.all(Radius.circular(10.0)),
                                    borderSide: BorderSide(color: Colors.grey),
                                  ),
                                  focusedBorder: OutlineInputBorder(
                                    borderRadius:
                                    BorderRadius.all(Radius.circular(10.0)),
                                    borderSide: BorderSide(color: Colors.grey),
                                  ),
                                  prefixIcon: Icon(Icons.call),
                                  suffixIcon: GestureDetector(
                                      onTap: () {
                                        _number.clear();
                                      },
                                      child: Icon(Icons.clear)),
                                ),
                                onSaved: (String value) {
                                  // This optional block of code can be used to run
                                  // code when the user saves the form.
                                },
                                validator: (String value) {
                                  if (value.isEmpty) {
                                    return 'Please enter Whatsapp Number';
                                  } else
                                    return null;
                                }),
                          ),
                          SizedBox(
                            height: MediaQuery.of(context).size.height / 30,
                          ),
                          Container(
                            margin: EdgeInsets.only(left: 10, right: 10),
                            child: TextFormField(
                                controller: _message,
                                decoration: InputDecoration(
                                  labelText: 'Message',
                                  filled: true,
                                  fillColor: Colors.cyanAccent.shade100,
                                  enabledBorder: OutlineInputBorder(
                                    borderRadius:
                                    BorderRadius.all(Radius.circular(10.0)),
                                    borderSide: BorderSide(color: Colors.grey),
                                  ),
                                  focusedBorder: OutlineInputBorder(
                                    borderRadius:
                                    BorderRadius.all(Radius.circular(10.0)),
                                    borderSide: BorderSide(color: Colors.grey),
                                  ),
                                  prefixIcon: Icon(Icons.message),
                                  suffixIcon: GestureDetector(
                                      onTap: () {
                                        _message.clear();
                                      },
                                      child: Icon(
                                        Icons.clear,
                                      )),
                                ),
                                onSaved: (String value) {
                                  // This optional block of code can be used to run
                                  // code when the user saves the form.
                                },
                                validator: (String value) {
                                  if (value.isEmpty) {
                                    return 'Please enter Message';
                                  } else
                                    return null;
                                }),
                          ),
                          SizedBox(
                            height: MediaQuery.of(context).size.height / 20,
                          ),
                        ],
                      ),
                      InkWell(
                        onTap: () {
                          Utils.launchWhatsApp(
                            phone: '91${_number.text}',
                            message: '${_message.text} ',
                          );
                        },
                        child: Container(
                          padding: EdgeInsets.only(top: 20.0, bottom: 20.0),
                          decoration: BoxDecoration(
                            color: Colors.cyan,
                            borderRadius: BorderRadius.only(
                                bottomLeft: Radius.circular(32.0),
                                bottomRight: Radius.circular(32.0)),
                          ),
                          child: Text(
                            "NEXT",
                            style: TextStyle(color: Colors.white),
                            textAlign: TextAlign.center,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          );
        },
        transitionDuration: Duration(milliseconds: 300));
  }
  Widget _getBodyWidget() {
    return Container(
      child: HorizontalDataTable(
        leftHandSideColumnWidth: 100,
        rightHandSideColumnWidth: 1300,
        isFixedHeader: true,
        headerWidgets: _getTitleWidget(),
        leftSideItemBuilder: _generateFirstColumnRow,
        rightSideItemBuilder: _generateRightHandSideColumnRow,
        itemCount: responseResult.length,
        rowSeparatorWidget: const Divider(
          color: Colors.black54,
          height: 1.0,
          thickness: 0.0,
        ),
        leftHandSideColBackgroundColor: Colors.grey.shade600,
        rightHandSideColBackgroundColor: Color(0xFFFFFFFF),
      ),
      height: MediaQuery
          .of(context)
          .size
          .height/2,
    );
  }

  List<Widget> _getTitleWidget() {
    return [
      Row(
        children: [
          _getTitleItemWidget('Select All ', 50),
          Container(width: 50,
            height: 40,
            child: Checkbox(
                focusColor: Colors.grey,
                activeColor: Colors.cyan,
                value: enable,
                onChanged: (newValue) {
                  setState(() => enable = newValue);
                }
            ),
          ),
        ],
      ),
      _getTitleItemWidget('Docket No', 100),
      _getTitleItemWidget('Booking Date', 120),
      _getTitleItemWidget('Booking Mode', 120),
      _getTitleItemWidget('Origin', 150),
      _getTitleItemWidget('Destination', 150),
      _getTitleItemWidget('Consigner Name', 150),
      _getTitleItemWidget('Consignee Name', 150),
    ];
  }

  Widget _getTitleItemWidget(String label, double width) {
    return Container(
      child: Text(label, style: TextStyle(fontWeight: FontWeight.bold)),
      width: width,
      height: 56,
      padding: EdgeInsets.fromLTRB(5, 0, 0, 0),
      alignment: Alignment.centerLeft,
    );
  }

  Widget _generateFirstColumnRow(BuildContext context, int index) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: [
        Container(
          child: Checkbox(
              focusColor: Colors.grey,
              activeColor: Colors.cyan,
              value: enable,
              onChanged: (newValue) {
                setState(() => enable = newValue);
              }
          ),
          width: 100,
          height: 52,
          padding: EdgeInsets.fromLTRB(5, 0, 0, 0),
          alignment: Alignment.centerLeft,
        ),
      ],
    );
  }

  Widget _generateRightHandSideColumnRow(BuildContext context, int index) {
    return Row(
      children: <Widget>[
        Container(
          child: Row(
            children: <Widget>[
              Text("${Docket_no[index]}",
                textScaleFactor: 1.0,
              ),
            ],
          ),
          width: 100,
          height: 52,
          padding: EdgeInsets.fromLTRB(5, 0, 0, 0),
          alignment: Alignment.centerLeft,
        ),
        Container(
          child: Text("${Booking_date[index]}"),
          width: 120,
          height: 52,
          padding: EdgeInsets.fromLTRB(5, 0, 0, 0),
          alignment: Alignment.centerLeft,
        ),
        Container(
          child: Text("${booking_mode[index]}"),
          width: 120,
          height: 52,
          padding: EdgeInsets.fromLTRB(5, 0, 0, 0),
          alignment: Alignment.centerLeft,
        ),
        Container(
          child: Text("${originbranch[index]}"),
          width: 150,
          height: 52,
          padding: EdgeInsets.fromLTRB(5, 0, 0, 0),
          alignment: Alignment.centerLeft,
        ),
        Container(
          child: Text("${destinationbranch[index]}"),
          width: 150,
          height: 52,
          padding: EdgeInsets.fromLTRB(5, 0, 0, 0),
          alignment: Alignment.centerLeft,
        ),
        Container(
          child: Text("${consigner_name[index]}"),
          width: 150,
          height: 52,
          padding: EdgeInsets.fromLTRB(5, 0, 0, 0),
          alignment: Alignment.centerLeft,
        ),
        Container(
          child: Text("${consignee_name[index]}"),
          width: 150,
          height: 52,
          padding: EdgeInsets.fromLTRB(5, 0, 0, 0),
          alignment: Alignment.centerLeft,
        ),
      ],
    );
  }
}

[![enter image description here][1]][1]
[![enter image description here][2]][2]


  [1]: https://i.stack.imgur.com/VX3Wk.jpg
  [2]: https://i.stack.imgur.com/MmXCJ.jpg

so how to implement that??

api
flutter
datatable
asked on Stack Overflow Jan 9, 2021 by Technical Support Team • edited Jan 9, 2021 by Technical Support Team

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0