Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.6k views
in Technique[技术] by (71.8m points)

flutter - Import list from separate file during runtime

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can't use the word import there. It's reserved word, used for loading flutter/dart packages, class files, etc. It's not for "loading" some arbitrary data from a file.

Flutter official website has a cookbook example for reading and writing data from and to files. Perhaps their example would work for you?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...