首页 > 解决方案 > Flutter,在 null 上调用了 getter 'currentState'

问题描述


class ReservationBranchesSlotsScreen extends StatefulWidget {
  

  **ReservationBranchesSlotsScreen({Key key}) : super(key: key);**

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

class ReservationBranchesSlotsScreenState extends State<ReservationBranchesSlotsScreen> {
.
.
.
 void changeData({
  String areaId,  
  int coastPerPerson,
  int selectedBranchChecked,
  String formatted,
  bool showCreateReservationButton,
  bool isExpanded,
  int expandedIndex
  }){
    setState(() {
          _areaId = areaId;
          _coastPerPerson = coastPerPerson;
          _selectedBranchChecked = selectedBranchChecked;
          _formatted = formatted; 
          _showCreateReservationButton = showCreateReservationButton;
          _isExpanded = isExpanded;
          _expandedIndex = expandedIndex;
        });
  }
Widget build(BuildContext context) {
  return Scaffold(
      **key: widget.key,**
      body: (_isCreateReservationButtonLoading)
          ? Center(
              child: CircularProgressIndicator(backgroundColor: Colors.white),
            )
          : Container(
              margin: EdgeInsets.only(bottom: 16),
              child: SingleChildScrollView(
                child: Column(children: <Widget>[
                  _isLoading
                      ? Center()
                      : SelectBranchWidget(
                        parentKey: widget.key,
                        branches: _branches,
                        coastPerPerson: _coastPerPerson,
                        areaId: _areaId,
                        selectedBranchChecked: _selectedBranchChecked,
                        formatted: _formatted,
                        isExpanded: _isExpanded,
                        showCreateReservationButton: _showCreateReservationButton,
                        expandedIndex: _expandedIndex,
                        **changeData: changeData,**
                      ),
class SelectBranchWidget extends StatefulWidget {



// here i create a Globalkey
  **GlobalKey<ReservationBranchesSlotsScreenState> parentKey = GlobalKey<ReservationBranchesSlotsScreenState>();**


  List<RestaurantBranch> branches;
  int coastPerPerson;
  String areaId;
  int selectedBranchChecked;
  String formatted;
  bool isExpanded;
  bool showCreateReservationButton;
  int expandedIndex;
  Function changeData;
  SelectBranchWidget(
      {
      this.parentKey,
      this.branches,
      this.coastPerPerson,
      this.areaId,
      this.selectedBranchChecked,
      this.formatted,
      this.isExpanded,
      this.showCreateReservationButton,
      this.expandedIndex,
      this.changeData,
      });
  @override
  _SelectBranchWidgetState createState() => _SelectBranchWidgetState();
}

class _SelectBranchWidgetState extends State<SelectBranchWidget> {
  void _changedValues(int i, int branchAreaIndex) {
    widget.coastPerPerson = widget.branches[i].branchAreas[branchAreaIndex].costPerSeat;
    widget.areaId = widget.branches[i].branchAreas[branchAreaIndex].guid;
    print('areaId IS ${widget.areaId}');
      widget.selectedBranchChecked = i;
      widget.formatted ='';
      widget.isExpanded = false;
      widget.showCreateReservationButton = false;
      widget.expandedIndex = -1;

// 这里我使用 currentState 来更新父级,数据发生了变化

 **widget.parentKey.currentState.changeData(
        areaId:widget.areaId,
        coastPerPerson: widget.coastPerPerson,
        selectedBranchChecked: widget.selectedBranchChecked,
        formatted: widget.formatted,
        showCreateReservationButton: widget.showCreateReservationButton,       
        isExpanded: widget.isExpanded,
        expandedIndex: widget.expandedIndex,**
      
      );
  }



  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
          color: Theme.of(context).primaryColorDark,
          borderRadius: BorderRadius.all(Radius.circular(10))),
      padding: EdgeInsets.all(8),
      margin: EdgeInsets.only(left: 16, right: 16),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Align(
            alignment: Alignment.centerLeft,
            child: Text(
              'Select Branch',
              style: TextStyle(
                  color: Colors.white,
                  fontSize: 20,
                  fontWeight: FontWeight.bold),
            ),
          ),
          SizedBox(
            height: 8,
          ),
          Align(
            alignment: Alignment.centerLeft,
            child: Padding(
              padding: const EdgeInsets.only(left: 8.0),
              child: Text(
                'Number of branches = ${widget.branches.length}',
                style: TextStyle(color: Colors.grey, fontSize: 10),
              ),
            ),
          ),
          SizedBox(
            height: 16,
          ),
          ConstrainedBox(
            constraints:
                BoxConstraints(maxHeight: 230, maxWidth: double.infinity),
            child: ListView.builder(
              shrinkWrap: true,
              itemCount: widget.branches.length,
              itemBuilder: (ctx, i) {
                return GestureDetector(
                  onTap: () {
                    if (widget.branches[i].branchAreas.length == 1) {
                      _changedValues(i, 0);
                      return;
                    }
                    showDialog(
                        context: context,
                        builder: (BuildContext context) {
                          return AlertDialog(
                            backgroundColor: Theme.of(context).backgroundColor,
                            title: Text(
                              'Select Area',
                              style: TextStyle(
                                  color: Colors.white,
                                  fontWeight: FontWeight.bold),
                            ),
                            content: Container(
                              decoration: BoxDecoration(
                                color: Theme.of(context).primaryColorDark,
                                borderRadius: BorderRadius.all(
                                  Radius.circular(10),
                                ),
                              ),

                              // height: (_branches[i].branchAreas.length == 1)
                              //     ?70
                              //     : (_branches[i].branchAreas.length == 2)
                              //     ? 100
                              //     :150,
                              width: 100.0,
                              child: ConstrainedBox(
                                constraints: BoxConstraints(maxHeight: 120),
                                child: ListView.builder(
                                  shrinkWrap: true,
                                  itemCount:
                                      widget.branches[i].branchAreas.length,
                                  itemBuilder:
                                      (BuildContext context, int index) {
                                    return GestureDetector(
                                      onTap: () {
                                       _changedValues(i, index);
                                        Navigator.of(context).pop();
                                      },
                                      child: Padding(
                                        padding: const EdgeInsets.only(
                                            top: 16, left: 36.0, right: 36),
                                        child: Column(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          children: [
                                            Text(
                                              widget.branches[i]
                                                  .branchAreas[index].name,
                                              style: TextStyle(
                                                  color: Colors.white),
                                            ),
                                            Divider(
                                              color: Colors.grey,
                                              thickness: 1,
                                            ),
                                          ],
                                        ),
                                      ),
                                    );
                                  },
                                ),
                              ),
                            ),
                          );
                        });
                  },
                  child: Card(
.
.
.

标签: flutterdartnullstateparent-child

解决方案


推荐阅读