Flutter에서 목록 배열을 문자열에 결합하는 방법

이 튜토리얼에서는 Flutter 또는 Dart에서 목록 배열 항목을 문자열에 조인하는 방법을 배웁니다. 여기에서는 일반 문자열 목록과 개체 목록을 단일 문자열 출력에 결합합니다. 목록 항목을 하나의 문자열로 연결하는 간단한 함수를 사용합니다.

문자열 목록을 하나의 문자열로 결합하는 방법:

List<String> strlist = ["Hello", "How", "Are", "You"];

String str1 = strlist.join();
print(str1); //Output: HelloHowAreYou

여기서 List.join()메서드는 목록 내의 모든 문자열 값을 연결하고 단일 문자열로 출력합니다. 아래와 같이 참여하는 동안 구분 기호를 추가할 수도 있습니다.

List<String> strlist = ["Hello", "How", "Are", "You"];

String str2 = strlist.join(" ");
print(str2); //Output: Hello How Are You

여기에서는 공백을 구분 기호로 넣었으므로 위와 다른 출력이 있습니다.

개체 목록을 단일 문자열로 조인하는 방법:

등급:

class Student{
  String name, address;
  Student({required this.name, required this.address});

  @override //don't forgot to add this override
  String toString() {
    return "Name: $name, Address: $address";
    //the string format, you can put any format you like
  }
}

toString()클래스를 만드는 동안 재정의를 추가하는 것을 잊지 마십시오 . 여기에 제공하는 형식은 이 개체를 문자열로 변환하는 데 사용됩니다. 이제 아래와 같이 이 개체의 목록에 가입합니다.

List<Student> studentlist = [
  Student(name: "John", address: "India"),
  Student(name: "Krishna", address: "Nepal"),
  Student(name: "Gita", address: "Canada")
];

String str3 = studentlist.join(" | ");
print(str3);
//Output:
//Name: John, Address: India | Name: Krishna, Address: Nepal | Name: Gita, Address: Canada

//Without toString() override on class
//Instance of 'Student'Instance of 'Student'Instance of 'Student'

여기에서 문자열의 형식은 toString()개체 클래스의 재정의에서 검색됩니다.

이러한 방식으로 목록 배열을 Dart 또는 Flutter에서 하나의 문자열로 결합할 수 있습니다.

1.10 GEEK