flutter对数组中某个数据二次加工成单独的数组

如何将数据2,1,2,2,2,1,2,2,3,2,2,2,2,3,2,2,2,2,2,3,2,4,2,2,1,2,3,2,4,2加工成

\[2, 1, 2, 2, 2, 1, 2, 2, 3, 2, 2, 2, 2, 3, 2, 2, 2, 2, 2, 3, 2, 4, 2, 2, 1, 2, 3, 2, 4, 2]。这是实际工作中遇到的问题,UI要求将某一类型数据(如上述数组中的2)用宫格(GridView)展示,其他类型数据用列表(ListView)展示,整体就是一个ListView嵌套很多GridView。

代码运行结果:

​​​​​​​

完整代码:

Dart 复制代码
Future<void> main(List<String> args) async {
  List<int> intList = [2,1,2,2,2,1,2,2,3,2,2,2,2,3,2,2,2,2,2,3,2,4,2,2,1,2,3,2,4,2];
  arrayProcess(intList,2);
}
///intList,加工的数组
///加工的数据
List<Object> arrayProcess(List<int> intList,int num){
  List<Object> ints = [];
  int times = 1;
  List<int> temp = [];
  for(int i=0;i<intList.length;i++){
    if(i < (intList.length -1)){
      if(intList[i]==intList[i+1] && intList[i]==num){
        times= times+1;
        temp.add(intList[i]);
      }else {
        if(times>1){
          if(temp.length>0){
            temp.add(intList[i]);
            List<int> _temp = [];
            temp.forEach((element) {
              _temp.add(element);
            });
            ints.add(_temp);
            temp.clear();
          }

          times = 1;
        }
        else{
          if(intList[i]==num){
            temp.add(intList[i]);
            List<int> _temp = [];
            temp.forEach((element) {
              _temp.add(element);
            });
            ints.add(_temp);
            temp.clear();
          }
          else{
            ints.add(intList[i]);
            times = 1;
          }
        }
      }
    }
    else{
      if(times>1){
        if(temp.length>0){
          temp.add(intList[i]);
          List<int> _temp = [];
          temp.forEach((element) {
            _temp.add(element);
          });
          ints.add(_temp);
          temp.clear();
        }

        times = 1;
      }
      else{
        if(intList[i]==num){
          temp.add(intList[i]);
          List<int> _temp = [];
          temp.forEach((element) {
            _temp.add(element);
          });
          ints.add(_temp);
          temp.clear();
        }
        else{
          ints.add(intList[i]);
          times = 1;
        }
      }
    }
  }
  print(ints.toString());
  return ints;
}
相关推荐
TT_Close1 小时前
别劝退了!5秒搞定 Flutter 鸿蒙 FVM 起跑线
flutter·harmonyos·visual studio code
你听得到115 小时前
用户说 App 卡,但说不清在哪?我把 Flutter 监控 SDK 升级成了链路观测工作台
前端·flutter·性能优化
stringwu2 天前
Flutter 开发必备:MVI 架构的高效实现指南
前端·flutter
程序员老刘3 天前
Flutter版本选择指南:3.44系列继续观望 | 2026年6月
flutter·ai编程·客户端
用户965597361904 天前
Provider vs Bloc vs GetX vs Riverpod:Flutter 状态管理方案怎么选?
flutter
恋猫de小郭4 天前
Flutter Patchwork,不用 Fork 改依赖包源码的第三方工具
android·前端·flutter
程序员老刘5 天前
跑分第一的编程大模型,我为啥不用?
flutter·ai编程·vibecoding
恋猫de小郭5 天前
苹果 AirPods 协议,Android 也可以使用完整版 AirPods 能力
android·前端·flutter
张风捷特烈5 天前
Flutter 类库大揭秘#01 | path_provider架构与设计
android·flutter
恋猫de小郭8 天前
Android 限制侧载新进展,谷歌联合国内厂商推验证计划
android·前端·flutter