Problem Explanation
I have a file that looks like this:
myfile1.txt
[
{
"question": "Thanks for the help",
"answer choices": [
"Hi",
"stack",
"over",
"flow",
],
},
...
]
This file contains data that needs to be set to a variable in a separate Dart file. The file type of this data does not matter, so if a .dart file would be easier to work with that would be perfectly fine.
Example of dart file that calls for the above file:
main.dart
void main() {
List<Map<String, dynamic>> data;
for (int i=0; i<5; i++) {
data = getFile("myfile$i.txt");
// Does stuff here
}
}
Note: getFile()
does not actually have to be used. It's just a placeholder for the example.
Question: How would I set the data in this file to the variable data
while in a function (like main()
).
My attempt
Ideally, I wouldn't want to make many changes to the data file but here is what I did:
myfile1.dart
List<Map<String, dynamic>> data = [
...
]
I changed the file type to a .dart file and created a variable that would be set to the data.
I then modified my main.dart file like so:
main.dart
void main() {
for (int i=0; i<5; i++) {
import "myfile$i.dart";
// Does stuff here
}
}
This approach fails because import cannot be called from inside a function.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…