【问题标题】:How to convert String List to String in flutter?如何在颤振中将字符串列表转换为字符串?
【发布时间】:2019-10-19 22:51:53
【问题描述】:

我需要在飞镖中将List<String> 转换为String

我想从首选项中提取列表的值。我已经尝试过这个实现,但它只给了我最后一个值。

Future<List<String>> services = SharedPrefSignUp.getSelectedServices();
services.then((onValue){
  List<String>servicesList=onValue;
  selectServicesText=servicesList.join(",");
});

【问题讨论】:

  • 您可以迭代列表并使用字符串缓冲区连接项目

标签: list flutter dart converters


【解决方案1】:

以防万一有人想在对象列表中连接特定的成员字符串:这是一种方法-

   string commaSeparatedNames=return listOfObjectsWithNameAttribute
      .map((item) => item.name)
      .toList()
      .join(",");

【讨论】:

    【解决方案2】:
     print(list.toString().replaceAll('[', '').replaceAll(']',''))
    

    【讨论】:

      【解决方案3】:

      如果您想将您的List&lt;String&gt; 转换为coma septated String,您可以这样做

       List<String> list =["one", "Two", "Thee"];
       print(list.join(","));  // Output will be like this : one,Two,Thee
      

      Join() 方法将每个元素转换为字符串并连接字符串。

      【讨论】:

      • 最佳和最简单的解决方案
      • 非常感谢,这是解决我问题的最简单方法。
      【解决方案4】:

      如果你知道你有List&lt;String&gt;,那么你可以使用flutter提供的join()函数。

          var list = ['one', 'two', 'three'];
          var stringList = list.join("");
          print(stringList); //Prints "onetwothree"
      

      简单而简短。 ;)

      你可以这样使用它:

       List<String>servicesList=["one", "Two", "Thee"]; 
       print(servicesList.join(""));
      

      【讨论】:

      • 我怎样才能让它每个人都可以点击?
      【解决方案5】:

      您可以在这样的列表中使用reduce 方法:

      List<String> list = ['one', 'two', 'three'];
      final string = list.reduce((value, element) => value + ',' + element);
      
      // For your example:
      List<String> servicesList = await SharedPrefSignUp.getSelectedServices();
      selectServicesText = servicesList.reduce((value, element) => value + ',' + element);
      

      【讨论】:

        【解决方案6】:

        您可以使用 StringBuffer 迭代列表和连接值

          var list = ['one', 'two', 'three'];
          var concatenate = StringBuffer();
        
          list.forEach((item){
            concatenate.write(item);
          });
        
          print(concatenate); // displays 'onetwothree'
        
          }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-02-08
          • 2021-10-26
          • 2023-04-07
          • 1970-01-01
          • 1970-01-01
          • 2023-02-23
          • 1970-01-01
          • 2020-02-01
          相关资源
          最近更新 更多