【问题标题】:How to get multiple Random Values from Map ? - Dart如何从 Map 中获取多个随机值? - 飞镖
【发布时间】:2021-10-29 17:09:01
【问题描述】:

我试图从map 中获取一些随机的多个值作为列表,代码中有一些解释 //,任何逻辑如果 Function 或喜欢我的逻辑,在此先感谢

   class Test{
      String url;
      int id;
      String name;
      Test({required this.url , required this.id , required this.name});
    }
    
    class Fake{
      static List<Test> getSomeValues = [
        Test(id: 1 , url : "test/test" , name : "1Name"),
        Test(id: 2 , url : "test/test" , name : "2Name"),
        Test(id: 3 , url : "test/test" , name : "3Name"),
      ]; 
    }
    
    void widget(Test t){
      print(t.id);
      
    }
    
    void main(){
      print(Fake.getSomeValues.asMap().entries.where((f){
        // here just I can apply condition on each Value can't get random 
        return f.value.id == 1 ; 
        
      }).map((f){
         // I don't want not needy value arrive here .
        // after I want to use each instance of Test . 
        return widget(f.value);
      }).toList());
    }

例如输出:

void getRandom(List<test> t , int count){
// code
print(t.id)
}
getRandom(test , 2),

输出:

3,1 

【问题讨论】:

  • 你想用map获取随机数吗?
  • 如果你的逻辑返回列表很好:)
  • @Mo7ammed7amad 更新了我的答案,请看一下

标签: list flutter dictionary dart


【解决方案1】:

请检查

import 'dart:math';

class Test{
      String url;
      int id;
      String name;
      Test({this.url ,  this.id ,  this.name});
    }
    
    class Fake{
      static List<Test> getSomeValues = [
        Test(id: 1 , url : "test/test" , name : "1Name"),
        Test(id: 2 , url : "test/test" , name : "2Name"),
        Test(id: 3 , url : "test/test" , name : "3Name"),
        Test(id: 4 , url : "test/test" , name : "4Name"),
        Test(id: 5 , url : "test/test" , name : "5Name"),
        Test(id: 6 , url : "test/test" , name : "6Name"),
        Test(id: 7 , url : "test/test" , name : "7Name"),
      ]; 
    }
    
    
    
    void main(){
     List<Test>  itemOfList= shuffle(Fake.getSomeValues, 3);
      itemOfList.forEach((e)=> print(e.name));
    }

List<Test> shuffle(List<Test> items, int item) {
  var random = new Random();

  items.shuffle();

  return items.sublist(0, item);
}

【讨论】:

  • 对不起,我更新了我的问题,如果可能的话请检查一下
  • @Mo7ammed7amad 你想要带有特定项目的随机列表吗(比如 2 、 3 等等)
猜你喜欢
  • 2012-10-30
  • 1970-01-01
  • 1970-01-01
  • 2022-10-17
  • 1970-01-01
  • 1970-01-01
  • 2022-06-19
  • 1970-01-01
  • 2020-09-07
相关资源
最近更新 更多