1

this is my first question here on stackoverflow. Before i get into the question itself, i want to point out that i'm a beginner on Flutter and Dart and have no previous experience in mobile development.

Now, as the title says i'm having some issues while trying to extract the content of a text file and store the individual names inside the indexes of a list. The end goal of my application is to print a never ending list of these names, each separated to another by a comma. For example:

top model,
torcitóre,
torcolière,
tornitóre,
tosacàni,
tossicòlogo,
tour operator,
tracciatóre,
tranvière,
trattorìsta,
trattóre²,
trebbiatóre,
trecciaiòlo,
trevière,
tributarìsta,
trinciatóre,
trivellatóre,
truccatóre,
tubìsta,
turnìsta,

The text file, named jobs.txt contains more than a 1000+ italian job names. After several hours searching, all i have here is this (got from another user):


import 'dart:async';
import 'dart:convert';
import 'dart:io';

void main(List<String> arguments) {
  try {
    final _jobs = File('jobs.txt');

    List<String> lines = _jobs.readAsLinesSync(encoding: ascii);
    for (var l in lines) print(l);
  } catch (Exception) {
    print(Exception.toString());
    
  }
}

jobs.txt is inside the same directory as the dart file, which is bin.

While trying to give the _jobs variable the relative path:

FileSystemException: Cannot open file, path = 'binjobs.txt' (OS Error: Impossibile trovare il file specificato.
, errno = 2)

With absolute path:

FileSystemException: Cannot open file, path = 'C:UsersUserDesktopdartdart_application_injobs.txt' (OS Error: La sintassi del nome del file, della directory o del volume non è corretta.
, errno = 123)

For reasons i don't know, if that even matters, in the path specified in the error message, the \ look like they don't even exist.

By the way, this is my project structure: project structure

If your solution includes the usage of the Future class or async-await keywords, i'll be thankful if you could explain me how they work.

UPDATE: Look in the comments for the full solution to this issue. The verified answer isn't the full solution.

2 Answers2

1

Create an assets folder in your project, in your pubspec.yaml specify the asset (make sure it's in your assets folder, that the file exists and is readable)

flutter:
  assets:
    - assets/jobs.txt

Now you can access your text file like so -

import 'dart:async' show Future;
import 'package:flutter/services.dart' show rootBundle;
Future<String> loadAsset() async {
  return await rootBundle.loadString('assets/jobs.txt');
}

When the function returns your text, you can split it by commas and loop through all the jobs as you wish

Ilan P
  • 1,602
  • 1
  • 8
  • 13
  • After loading the file, how do i get it to be a string? I tried using the .then(), but i have no clue right now – Davide Pulvirenti Apr 12 '22 at 13:39
  • String data = await DefaultAssetBundle.of(context).loadString("assets/jobs.txt"); now data will contain the string value of the jobs.txt content. – Ilan P Apr 12 '22 at 13:41
  • I'm getting an error at ".of(context)", undefined. Is there any library i have to import? – Davide Pulvirenti Apr 12 '22 at 13:53
  • 1
    Since comments have a char limitation, let me refer you to this resource, create a new sample dart file and add this code (with tweaking to your environment) - https://www.yourowncodes.com/how-to-read-content-of-text-file-from-assets-in-flutter/ it's very simple; btw your error is because your context is undefined (not sure where you added that line) but kindly refer to this URL above for me; once you get it once it'll resonate throughout everything you're doing – Ilan P Apr 12 '22 at 13:59
  • I'm getting an error accessing that page: "Error communicating with origin". Could you send me the code snippet, pasting it in a website like pastebin? – Davide Pulvirenti Apr 12 '22 at 14:04
  • https://pastebin.com/gku54YmQ check it out – Ilan P Apr 12 '22 at 14:06
  • Done, i'm able to read and display the file content on screen. The only thing is that i can't scroll through its content. But, that's about it for this question. Thanks! – Davide Pulvirenti Apr 12 '22 at 14:23
  • Aye that would have to do with your container, whether your pushing the return to a view such as a SingleChildScrollView that's all UI debugging - most important part is, you figured out how to access the string from your text file :) – Ilan P Apr 12 '22 at 14:25
  • If that doesn't bother you, could you pick up again that code you gave me, and add some explanatory comments? I'd like to understand the code you gave in order to avoid this error again in the future – Davide Pulvirenti Apr 12 '22 at 14:56
  • For the UI issue where you are unable to scroll? or for getting the text? I think getting the text is straight forward, you registered your jobs.txt asset in pubspec and in your dart class you loaded the asset - the container you returned your asset data to child: Text(dataFromFile), <-- should be in a scrollview, reason being it overflows a static position because you have so many items; you can also parse it into a list builder and add it to a listview :) - I recommend flutterawesome.com as a great learning resource – Ilan P Apr 12 '22 at 15:01
0

try using rootBundle

  pubspec.yaml
      assets:
        - text_file/

  import 'package:flutter/services.dart' show rootBundle;

  Future<String> getData() async {
    try {
      return await rootBundle.loadString('text_file/four_words.txt');
    } catch (e) {
      throw (e.toString());
    }
  }
Golden Lion
  • 3,840
  • 2
  • 26
  • 35