In Dart, How to access the element from the array which is created like below?
final Object? elements;
elements= ["element1" , "element2" , "element3"];
CodePudding user response:
First, no need to declare the type:
final elements = ["element1" , "element2" , "element3"];
The compiler can determine the type: List<String>
To access the first element of the array (usually called List in Dart):
elements.first // same as elements[0]
To access the last element of the array:
elements.last // same as elements[elements.length - 1]
To access the n
th element of the array (where 0 is the first index):
elements[n]
CodePudding user response:
convertObject(Object obj) {
if (obj is bool) {
return obj;
} else if (obj is List) {
print("ListType");
return obj.map((e) => e.toString()).toList(); // creating list by converting string
}
///... do for others
}
void main(List<String> args) {
final Object? elements;
elements = ["element1", "element2", "element3"];
final convertedDB = convertObject(elements);
print(convertedDB);
print("0 index item ${convertedDB[0]}");
}
Everything you can place in a variable is an object, and every object is an instance of a class. Even numbers, functions, and null are objects. With the exception of null (if you enable sound null safety), all objects inherit from the Object class.
More about static-checking
Lists (List, also known as arrays)