如何根据颤振中的 if 条件动态显示两个按钮

How can display two buttons dynamically based on an if condition in flutter

我是 flutter 的新手,我遇到了执行两个 if 条件的艰巨挑战。我想要实现的是对下面数组中的两个布尔条件执行 if 语句。我想检查 Success == true && Stock['Submitted'] == true,那么它应该显示一个标有“验证农民”的按钮,但如果这两个条件不成立,那么它应该显示一个标有“盘点”。但它不起作用。请问我怎样才能访问提交的值?

这是arry的结构:

{
  "StatusCode": 200,
  "Message": "Record Found",
  "Success": true,
  "Stock": {
    "Oid": 30,
    "CreatedBy": "johndoh",
    "CreatedOn": "2020-07-07T10:28:19.09",
    "ModifiedBy": null,
    "ModifiedOn": null,
    "Season": null,
    "SeasonTitle": null,
    "Anchor": 11,
    "AnchorName": null,
    "AnchorAcronym": null,
    "DistributionCentre": 11,
    "DistributionCentreName": null,
    "Agent": "John Doh",
    "StateCoordinator": "Godwin Obute",
    "StockDate": "2020-07-07T10:27:49.03",
    "TransId": "20200707102819089",
    "StateCoordinatorId": "38",
    "AgentId": "57",
    "UserId": "b6caf34c-a425-4710-a3ee-aa22a382882a",
    "Submitted": false,
    "SubmittedOn": null,
    "SubmittedBy": null,
    "StockItems": []
  }
}

调用 http 请求的函数,returns 上面的数组就在我的有状态小部件状态之后:

var user;
  var userData;
  var userDetail;
  var anchors;
  var dailyStatus;
  var dailyStocks;
  var found = false;
  var stockoid;

  // var dataSubmitted = false;

  @override
  void initState() {
    _getUserInfo();
    super.initState();
  }

//This getuser info gives me the parameters to use on the checkinventorystatus
  void _getUserInfo() async {
    SharedPreferences localStorage = await SharedPreferences.getInstance();
    var userJson = localStorage.getString('loginRes');
    user = json.decode(userJson);
    userDetail = user['UserDetail'];
    print('${userDetail['Oid']} poii'); //Just to get the userId
    anchors = user['Anchors'];

    setState(() {
      userData = user;
      print('${userData['UserId']} ioo');

      // var dc = value['DistributionCentres'][1]['Oid'];
      // print(dc);
    });
  }


//This is the main function that gives me the array above
  Future<CheckInventoryStatus> checkDailyStatus() async {
    final response = await http.get(
        'http://api.ergagro.com:112/CheckDailyStockTakingStatus?userId=${userData['UserId']}&agentId=${userDetail['Oid']}',
        headers: {
          'Content-type': 'application/json',
          'Accept': 'application/json',
        });

    if (response.statusCode == 200) {
      found = true;
      final jsonStatus = jsonDecode(response.body);
      var stock = jsonStatus['Stock'];
      bool submitted = stock['Submitted'];
      stockoid = stock['Oid'].toString();

      setState(() {
        found = submitted;
      });
      return CheckInventoryStatus.fromJson(jsonStatus);
    } else {
      throw Exception();
    }
  }

这是我的小部件视图:

在我的 children 小部件之后:

    Row(
                              children: <Widget>[
                                /////////// Based on the response I want to use it to control these two buttons below
                                ///if the response is 200 it should display validate farmer else it should display Take Inventory/////////////


                                Padding(
                                    padding: const EdgeInsets.all(10.0),
                                    //this is where I want to perform the check but its not working
                                    // dailyStatus['StatusCode'] == 200
                                    child:
                                        found ?
                                        FlatButton(
                                      child: Padding(
                                        padding: EdgeInsets.only(
                                            top: 8,
                                            bottom: 8,
                                            left: 10,
                                            right: 10),
                                        child: Text(
                                          'Validate Farmers',
                                          textDirection: TextDirection.ltr,
                                          style: TextStyle(
                                            color: Colors.white,
                                            fontSize: 15.0,
                                            decoration: TextDecoration.none,
                                            fontWeight: FontWeight.normal,
                                          ),
                                        ),
                                      ),
                                      color: Colors.green,
                                      shape: new RoundedRectangleBorder(
                                          borderRadius:
                                              new BorderRadius.circular(20.0)),
                                      onPressed: () {
                                        Navigator.push(
                                            context,
                                            new MaterialPageRoute(
                                                builder: (context) =>
                                                    StartScanPage()));
                                        // Edit()was here
                                      },
                                    )
                                    //if the status is not 200 then it should allow an agent to take inventory
                                    : FlatButton(
                                        child: Padding(
                                          padding: EdgeInsets.only(
                                              top: 8,
                                              bottom: 8,
                                              left: 10,
                                              right: 8),
                                          child: Text(
                                            'Take Inventory',
                                            textDirection: TextDirection.ltr,
                                            style: TextStyle(
                                              color: Colors.white,
                                              fontSize: 15.0,
                                              decoration: TextDecoration.none,
                                              fontWeight: FontWeight.normal,
                                            ),
                                          ),
                                        ),
                                        color: Colors.blueGrey,
                                        shape: new RoundedRectangleBorder(
                                            borderRadius:
                                                new BorderRadius.circular(
                                                    20.0)),
                                        onPressed: () {
                                          Navigator.push(
                                              context,
                                              new MaterialPageRoute(
                                                  builder: (context) =>
                                                      StockInventoryPage(
                                                          userData['UserId'],
                                                          '${userDetail['Oid']}',
                                                          '${value['DistributionCentres'][i]['Oid']}',
                                                          stockoid)));
                                        },
                                      ),
                                    ),

                                /////////// End of Buttons /////////////
                              ],
                            ),

像这样的东西怎么样:

  Widget _showButton(bool firstCondition, bool seacondCondition) {
return Padding(
    padding: const EdgeInsets.all(10.0),
    child: FlatButton(
      child: Padding(
        padding: EdgeInsets.only(top: 8, bottom: 8, left: 10, right: 10),
        child: Text(
          (firstCondition && seacondCondition)?'Validate Farmers':'Take Inventory',
          textDirection: TextDirection.ltr,
          style: TextStyle(
            color: Colors.white,
            fontSize: 15.0,
            decoration: TextDecoration.none,
            fontWeight: FontWeight.normal,
          ),
        ),
      ),
      color: Colors.green,
      shape: new RoundedRectangleBorder(
          borderRadius: new BorderRadius.circular(20.0)),
      onPressed: () {
        if(firstCondition && seacondCondition)
        Navigator.push(context,
            new MaterialPageRoute(builder: (context) => StartScanPage()));
        else
          Navigator.push(
              context,
              new MaterialPageRoute(
                  builder: (context) =>
                      StockInventoryPage(
                          userData['UserId'],
                          '${userDetail['Oid']}',
                          '${value['DistributionCentres'][i]['Oid']}',
                          stockoid)));
        // Edit()was here
      },
    ));

}

然后只需将 _showButton 放入您的子部件中