gitman-2021
gitman-2021

Reputation: 41

How to convert text file asset into List<String>

May I ask, How do i read a plaintext, located at assets/plaintext.txt, with the following content

1st line
2nd line
3rd line

and convert it into something, which act like, the following would have

List<String> stri = <String>[
"1st line",
"2nd line",
"3rd line",
];

The following code makes the app screen go black

import 'dart:core';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

String stri = '0';
Future<void> main() async {
  stri = await rootBundle.loadString('assets/plaintext.txt');
  runApp(
    const MyApp(),
  );
}

Thanking you...

Upvotes: 1

Views: 1025

Answers (1)

Muhammad Hussain
Muhammad Hussain

Reputation: 1244

You can load a string first using rootBundle.loadString() method, and then construct a list out of a pattern.

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

void loadAsset() async {
  String loadedString = await rootBundle.loadString('assets/plaintext.txt');
  List<String> result = loadedString.split('\n');
}

Don't forget to add it in your pubspec.yaml

flutter:
  assets:
    - assets/plaintext.txt

Upvotes: 1

Related Questions