Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter - Load assets for tests

Not sure if it's a limitation or something, but below code does not load anything. I have some data driven behaviour that I'd like to test isolated.

class Loader

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

class Loader {
  Future<String> load() async{
    return await rootBundle.loadString('assets/json/sketch.json');
  }
}

The test

testWidgets('Should parse load sketch.json', (WidgetTester tester) async {
    var loaderFuture = new Loader();

    Future<String> resultFuture = loaderFuture.load();

    resultFuture.then((value) => print(value))
        .catchError((error) => print(error));

    while(true){};
  });

Future does not return neither success nor error and hangs forever. I know the while(true) locking up the test, but for now I just wanted to see sketch.json printed

Asset location

enter image description here

like image 707
Victor Hugo Montes Avatar asked Mar 25 '18 19:03

Victor Hugo Montes


People also ask

How do you add assets in Flutter?

Step 1: At the root of your project, create a new folder called assets . Step 2: Inside the root folder, create another folder called images . You can give any name to this folder such as pictures, graphics, etc. Step 3: Add your images inside the assets/images folder.

Why does it say unable to load assets in Flutter?

To fix the unable to load asset in Flutter, you can either verify the image path that has correct image spelling or give a proper indentation in pubspec. yaml file.

What is difference between asset AssetBundle and rootBundle in Flutter?

The AssetBundle from which this application was loaded. The rootBundle contains the resources that were packaged with the application when it was built. To add resources to the rootBundle for your application, add them to the assets subsection of the flutter section of your application's pubspec.


1 Answers

To use rootBundle in your tests you need this at the beginning of your test programs:

import 'package:flutter_test/flutter_test.dart';

...
void main() {
  TestWidgetsFlutterBinding.ensureInitialized();
like image 186
Timmmm Avatar answered Sep 19 '22 05:09

Timmmm