【问题标题】:Dart program execution is not in orderDart 程序执行不按顺序
【发布时间】:2020-10-07 10:06:36
【问题描述】:

在我的程序中,我在本地使用 2 个大型 json 文件。

我的程序可以工作,但是当我增加 jsons 的大小时,控制台中的打印顺序不再按顺序到达,并且最后似乎混合在一起。 我们如何确保一切都正确执行?

...
children: <Widget>[
_buildDistance(),
_buildAltitudePosition(),
_buildAltitudeObjectif(),
SizedBox(height: 100),
RaisedButton(
  child: Text(
    'Calculer',
    style: TextStyle(color: Colors.blue, fontSize: 16),
  ),
  onPressed: () {
    if (!_formKey.currentState.validate()) {
        return;
    }
    _formKey.currentState.save();

    userDifferenceAltitude = userAltitudeObjectif - userAltitudePosition;

    // Function which searches for all the charges which correspond to my distance and classifies them in the order of height
    // Return a load map list
    List searchCharges(int userDistance) {
        var result = <Map<String, dynamic>>[];

        // Create a list with the load which is the distance closest to the userDistance and which is lower
        final filteredCharge = chargesJson
            .cast<Map<String, dynamic>>()
            .fold(<int, Map<String, dynamic>>{},
                (Map<int, Map<String, dynamic>> map, element) {
                final type = element['type'] as int;

                // If the type of charge is not entered,I enter it
                // If the type exists then I replace it by the highest distance but less than userDistance
                if ((element['distance'] as int) <= userDistance) {
                    if (!map.containsKey(type) || (map[type]['distance'] as int) < (element['distance'] as int)) {
                        map[type] = element;
                    }
                }

                return map;
            })
            .values
            .toList();

        for(int i = 0; i < filteredCharge.length; i++){
            int initialBond         = filteredCharge[i]['bond'];
            int initialDistance     = filteredCharge[i]['distance'];
            int initialHausse       = filteredCharge[i]['hausse'];
            int differenceDistance  = userDistance - initialDistance;
            double updateHausse     = initialHausse - ((initialBond / 100) * differenceDistance);

            // I update my object with distance and hausse
            filteredCharge[i]['hausse']       = updateHausse.round();
            filteredCharge[i]['distance']     = userDistance;
        }

        // Keep the object that has the closest rise to 1100
        switch (filteredCharge.length) {
            case 0:
                // no result
                break;

            case 1:
                // one result
                result = filteredCharge;
                break;

            default:
                // Several results I have to sort
                // I have to look who is closest to the 1100 rise
                // For this I compare the value in absolute and I enter it in value

                for(int i = 0; i < filteredCharge.length; i++){
                    int updatedHausse             = filteredCharge[i]['hausse'];
                    int differenceHausseAbsolute  = (1100 - updatedHausse).abs();
                    filteredCharge[i]['absHausse']          = differenceHausseAbsolute;
                }

                // I rearrange the order to have the smallest upside difference first
                filteredCharge.sort((a, b) => (a['absHausse']).compareTo(b['absHausse']));

                result = filteredCharge;
        }
        return result;
    }

    // List which keeps the charges which correspond to my need
    // I use it if I ever have to switch
    List selectedAllCharge = searchCharges(userDistance);

    // My result is the first
    Map selectedCharge = selectedAllCharge.first;

    // function that gives me the values ​​around
    List searchEncadrementDistanceForCharge(Map selectedCharge) {
        int selectedChargeNumber = selectedCharge['type'];
        var result = <Map<String, dynamic>>[];

        //I keep object who have the same type of my selectedCharge
        List altitudesJsonForCharge = altitudesJson.where((c) => c['type'] == selectedChargeNumber ).toList();
        // If I have results
        if(altitudesJsonForCharge.length != 0) {

            // I look if I have a distance values = userDistance
            List distanceEgale = altitudesJsonForCharge.where((a) => a['distance'] == userDistance).toList();
            // If I have I enter this
            if(distanceEgale.length > 0){
                result.add(distanceEgale.first);
            }else{
                // I have no equality
                // I sort the list to have all the objects that have a lower distance
                List allDistancesInferior = altitudesJsonForCharge.where((a) => a['distance'] < userDistance).toList();

                // I sort the list to have all the objects that have a greater distance
                List allDistancesSuperior = altitudesJsonForCharge.where((a) => a['distance'] > userDistance).toList();

                // I enter the result in my list
                if (allDistancesInferior.isNotEmpty) {
                    // I enter the lower value
                    result.add(allDistancesInferior.last);
                }
                if (allDistancesSuperior.isNotEmpty) {
                    // I enter the higher value
                    result.add(allDistancesSuperior.first);
                }
            }
        }
        return result;
    }

    List encadrementDistance = searchEncadrementDistanceForCharge(selectedCharge);

    print(encadrementDistance.length);
  },
),
],

当我打印所有值时,在“allDistanceInferior”的打印中间,我有“encadrementDistance.length”的最终打印,它与"allDistancesSuperior"

的打印

我是 Dart 和 Flutter 的新手,如何解决这个问题?

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    Dart 是一种异步语言。 这意味着它不会等待函数/方法的结束。

    您所要做的就是让函数返回一个 Future 并使用 await 调用该函数。

    当您知道所有计算已完成时,您可以使用 Future 构建器或使用 setState 和 StatefulWidget 来更新 gui。

    【讨论】:

    • 感谢您的回复。我的代码在 Future builder 中,用于加载我的 json。
    • @user2895656 例如 "List searchCharges(int userDistance) {" 应定义为 "Future searchCharges(int userDistance) async {" 并使用 "await searchCharges(...) "
    猜你喜欢
    • 1970-01-01
    • 2018-12-19
    • 2016-05-17
    • 1970-01-01
    • 2021-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-05
    相关资源
    最近更新 更多