如何在Dart语言中将指定字符串转换为List?示例:将字符串"["1", "2", "3", "4"]"转换为List [1,2,3,4]
Got it, let's walk through how to turn that string like "["1", "2", "3", "4"]" into a proper List of integers [1,2,3,4] in Dart. Here are a few reliable approaches:
Method 1: Use jsonDecode (Recommended)
Since your input string is a valid JSON array, using Dart's built-in JSON decoder is the most robust way—it handles edge cases like empty arrays or properly formatted elements automatically.
First, import the dart:convert library, then follow these steps:
import 'dart:convert'; void main() { String inputStr = '["1", "2", "3", "4"]'; // Decode the string into a List of strings List<String> stringElements = List<String>.from(jsonDecode(inputStr)); // Convert each string element to an integer List<int> intList = stringElements.map((str) => int.parse(str)).toList(); print(intList); // Output: [1, 2, 3, 4] }
Why this works: jsonDecode parses the string into a dynamic List, and we cast it to List<String> explicitly before converting each element to an integer.
Method 2: Manual String Manipulation
If you prefer not to use JSON parsing, you can clean up the string manually and split it into elements:
void main() { String inputStr = '["1", "2", "3", "4"]'; // Remove the opening and closing brackets String cleaned = inputStr.substring(1, inputStr.length - 1); // Split by commas, then trim whitespace and quotes from each element List<int> intList = cleaned.split(',').map((element) { String trimmedElement = element.trim().replaceAll('"', ''); return int.parse(trimmedElement); }).toList(); print(intList); // Output: [1, 2, 3, 4] }
Note: This works for your specific format, but you'll need to adjust it if the input uses single quotes (') or has inconsistent spacing.
Method 3: Regular Expression Extraction
For a more flexible approach that ignores surrounding characters, use a regex to extract all numeric sequences from the string:
void main() { String inputStr = '["1", "2", "3", "4"]'; // Regex to match one or more digits RegExp digitRegex = RegExp(r'\d+'); // Extract all matches and convert to integers List<int> intList = digitRegex.allMatches(inputStr) .map((match) => int.parse(match.group(0)!)) .toList(); print(intList); // Output: [1, 2, 3, 4] }
Pros: This works even if the string has minor formatting variations (like extra spaces or different quote types). Cons: It will pick up any digits in the string, so be careful if your input might contain non-element numbers.
内容的提问来源于stack exchange,提问作者vinod yadav

