How to convert text file asset into List<String> - flutter

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...

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

Related

error in MemoryImage not defined in package pdf/widgets.dart

import 'dart:io';
import 'package:flutter/material.dart' as material ;
import 'package:flutter/services.dart';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pw;
class PdfParagraphApi {
static Future<void> generate(key) async {
final pdf = pw.Document();
final img = pw.MemoryImage(await rootBundle.load('assets/img.png')).buffer.asUint8List();
pdf.addPage(
pw.MultiPage(
build: (context) => <pw.Widget>[
pw.Image(img),
]),
);
}
}
i'm trying to create a pdf with an image inside it and i'm using the library pdf/widgets.dart to create the image as i found in flutters documentation but i'm facing a problem.
the error message is the following :
The function 'MemoryImage' isn't defined.
Try importing the library that defines 'MemoryImage', correcting the name to the name of an existing function, or defining a function named 'MemoryImage'.dartundefined_function
insert image into pdf not working
Replace pw.MemoryImage with material.MemoryImage, because MemoryImage comes from the painting library, which is included inside the material library.
Try to replace the below import:
import 'package:flutter/material.dart' as material ;
with this import 'package:flutter/material.dart';
Try this below way:
Imports you need
import 'package:flutter/material.dart';
import 'dart:math';
import 'dart:typed_data';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart ' as pw;
import 'dart:io';
import 'package:permission_handler/permission_handler.dart';
and in the top you need to define the image you want to print _imageFile = someImage:
Uint8List? _imageFile ;
Then this is the function to make an image to pdf and save it in the Downloads Folder
Future getPdf() async {
var random = Random();
var uniqueNum = random.nextInt(99999);
//get storage permission
Map<Permission, PermissionStatus> storagePermission = await [
Permission.storage,
].request();
pw.Document pdf = pw.Document();
pdf.addPage(
pw.Page(
pageFormat: PdfPageFormat.a4,
build: (context) {
return pw.Expanded(
child: pw.Image(pw.MemoryImage(_imageFile), fit: pw.BoxFit.contain),
);
},
),
);
String path = await ExternalPath.getExternalStoragePublicDirectory(
ExternalPath.DIRECTORY_DOWNLOADS);
String mainPath = "$path/Report$uniqueNum.pdf";
File pdfFile = File(mainPath);
pdfFile.writeAsBytesSync(await pdf.save());
}

FlutterError (Unable to load asset: assets/audio/assets/Sound3.mp3)

I want to play an audio as the app background music(without button click/autoplay). The code seen like no problem, but cant display.Did I do anything wrong with the code?
import 'package:flutter/material.dart';
import 'package:flame/game.dart';
import 'package:flame/input.dart';
import 'package:flame_audio/flame_audio.dart';
import 'package:flutter/widgets.dart';
void main() {
runApp(GameWidget(game: Audio()));
}
class Audio extends FlameGame with TapDetector {
#override
Future<void> onLoad() async {
super.onLoad();
}
#override
void onTapUp(TapUpInfo) {
FlameAudio.bgm.play('assets/Sound3.mp3');
}
}
pubspec.yaml
assets:
- assets/Sound3.mp3
[The Error Show in C:\flutter_windows_2.10.4-stable\flutter\packages\flutter\lib\src\services\asset_bundle.dart][1]
[1]: https://i.stack.imgur.com/p383i.png
const AssetImage('icons/heart.png', package: 'my_icons');
Assets used by the package (or plugin) itself should also be fetched using the package argument.
line: https://docs.flutter.dev/development/ui/assets-and-images

Is there is any way to capture print() statement during integration test

Is there is any way during the integration testing to monitor or save or read whatever the print() statement is printing to the console. I m using integration_test for testing.
Maybe this will help you?
import 'dart:async';
import 'dart:developer';
void main(List<String> args) async {
final printed = <String>[];
final result = runZoned(() => foo(), zoneSpecification: ZoneSpecification(
print: (self, parent, zone, line) {
printed.add(line);
},
));
print('Result: $result');
print('Printed:\n${printed.join('\n')}');
debugger();
}
int foo() {
print('Hello');
print('Goodbye');
return 41;
}
P.S.
I added a debugger call so that the result of the work was visible. This statement can (and should) be removed.

Flutter Send a post request while waiting for gps data

I'm stuck on my flutter project, I want to send the gps coordinate every time the user open the app to check if its position is on specific place referenced on my base (if yes it send a notification). I have two futures, one of which is dependent on the other (sending needs gps data).
import 'package:http/http.dart' as http;
import 'package:location/location.dart';
import 'dart:convert';
class Islandmenu extends StatelessWidget {
Widget build(BuildContext context) {
......
}
Future<void>getgpscoordinates() async{
final locdata = await Location().getLocation();
List<double> gps= [locdata.latitude,locdata.longitude];
return gps;
}
Future<void>checkUser(gps) async{
const String userurl="*********/input_dbco.php";
final response = await http.post(userurl, body:jsonEncode({
"id": "",
"gps":[gps[0],gps[1]],
"dateco": "",
}));
return response;
}
}//end of class
but it's make my VM crash so i guess i do it in the wrong way ^^.

How to export and use global variable

I am creating a Flutter App and I need a global http client with some setup.
Flutter: 1.5.4
Dart: 2.3.2
// utils/http.dart
import 'dart:io';
import 'package:cookie_jar/cookie_jar.dart';
import 'package:dio/dio.dart';
import 'package:path_provider/path_provider.dart';
Dio http = Dio();
void main() async {
// Save cookies to cookie jar.
Directory appDir = await getApplicationDocumentsDirectory();
http.interceptors.add(CookieManager(PersistCookieJar(dir: appDir.path)));
}
// main.dart
import 'package:flutter/material.dart';
import 'app.dart';
import 'utils/http.dart';
void main() {
print(http.interceptors); // returns []
runApp(App());
}
I expect that main function in http should be automatically executed.
A common solution to this is to wrap it in a Widget and place that widget in the Widget Tree. High up in the tree, so that it's sort of global. It's called "lifing state up".
The out of box solution of Flutter for such things is InheritedWidget. It's worth looking at and understand because most 3rd-party solutions rely on it.
To make life a tad easier, however, I use pacakge:provider. Code would look like so:
Creating
Provider<Dio>(
builder: (_) => Dio(),
child: MaterialApp(/*...*/)
);
Consuming
later in the widget tree:
Consumer<Dio>(
builder: (ctx, dio, _) {
// widget builder method
debugPrint('Dio instance: ${dio}');
return Container();
}
);