Issue
I am trying to return a List<List<String>>
back to my Flutter code from my MainActivity.java
.
I created a
new MethodChannel(Objects.requireNonNull(getFlutterEngine()).getDartExecutor(), CHANNEL).setMethodCallHandler(new MethodChannel.MethodCallHandler() {
@Override
public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
if (call.method.equals("getOTD")) {
result.success(listOfList);
}
}
}
to return the listOfList variable. However, whenever it always coverts the List<List<String>>
to <Object>
while returning the "success" value. How can I make the method return the value without changing the data type? If that is not possible, how can I convert the Object back to List<List<String>>
in the dart part?
Here is my dart side of the code snippet:
void getOTD() async {
try {
otdList = await platform.invokeMethod("getOTD");
otdList = otdList.cast<List<List<String>>>();
print(otdList);
} catch (e) {
print(e);
}
}
I tried casting the variable, but it did not work. I want to perform many operations on that variable later, so I need the List<List<>String>
format. I have declared otdList in my dart code as follows since I was receiving an Object:
List<Object?> otdList = [];
Solution
I think I found a solution for the problem. With help of @pskink it turns out all one needs is a nested for loop. For example,
final dynamicList = await platform.invokeMethod("methodName") as List<dynamic>;
List<List<String>> listOfListString = [];
for (int i = 0; i < dynamicList.length; i++) {
List<String> subString = [];
for (int j = 0; j < dynamicList[i].length; j++) {
subString.add((dynamicList[i][j]).toString());
}
listOfListString.add(subString);
}
Then, use the listOfListString anywhere you want. It will be in a List<List> format.
Answered By - Omkar Phadke
Answer Checked By - Cary Denson (JavaFixing Admin)