• 15
name

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 191

Backtrace:

File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 191
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

I am using the flutter 'file', trying to read a txt file in lib directory, but I do not know how should I write in code to read the file. I also do not know if I have placed the txt file at a right place, which means I do not know if I can read the file in the lib directory.

I have put a txt file words.txt in the lib directory, where other dart files are put.

Below is my code which tries to read the 'word.txt' file:

Future<String> readFile() async {
  var text;
  try {
    final directory = await getApplicationDocumentsDirectory();
    print(directory.path);

    final file = File('${directory.path}/lib/words.txt');
    text = await file.readAsString();
    return text;
  } catch (e) {
    print(e.message);
  }
}

P.S. I have imported the 'dart:io' and 'path_provider.dart'.

When I run the program, I can see the directory.path is printed in the console, however the e.message 'Cannot open file' is printed in the console.

I think that the error is came from 'File('${directory.path}/lib/words.txt')', so i would like to know how should i write code to read the txt file in lib directory.

Thanks.

Create an assets folder in your project's root folder. In Android Studio you can right click the Project outline and go to New > Directory.

So now you should have

root folder
  --android
  --ios
  --lib
  --assets
  --build

Add your text file to the new folder

You can just copy your text file into the assets directory. The relative path of words.txt, for example, would be assets/words.txt.

Open the pubspec.yaml file that is in the root of your project. Update it as

flutter:
  assets:
    - assets/words.txt

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

Future<String> loadAsset() async {
  var s =  await rootBundle.loadString('assets/my_text.txt');
  print(s);//for debug
  return s;
}
  • 1
Reply Report