Search code examples
flutterflutter-dependenciesflutter-test

How can I run an example from a Flutter package/library?


I have the following simple directory structure:

flutter_published
    .idea
    android
    build
    ios
    lib
        main.dart 
    flutter_published.iml
    pubspec.lock
    pubspec.yaml
    network_to_file_image
        .idea
        example
            main.dart 
        lib
            network_to_file_image.dart
        test
        network_to_file_image.iml
        pubspec.lock
        pubspec.yaml

network_to_file_image is a package.

There are two main.dart files, one at flutter_published/lib/main.dart and another at flutter_published/network_to_file_image/example/main.dart

I am able to run the first one, but not the one inside of the example directory under network_to_file_image. The second one gives me this error:

   Launching example\lib\main.dart on Android SDK built for x86 in debug mode...
   No application found for TargetPlatform.android_x86.
   Is your project missing an android\AndroidManifest.xml?
   Consider running "flutter create ." to create one.

Also, when the app is generated, what happens to the example and test directories of the packages I use? Are they included or removed from the final app that is deployed?


Solution

  • To solve this, instead of the main.dart file inside of the example directory, you need to create a complete Flutter application-type project inside of the example directory. Then, the example tab will point to the README.md file inside of that directory.

    That example directory will have its own lib directory, containing a main.dart file. Since that file is now inside of an application-type directory it can be run.

    Visit this repo to see how it works:

    https://github.com/marcglasberg/async_redux/tree/master/example


    Update:

    To be clear, the example's pubspec.yaml file can reference its package by using a relative reference. For example, here is the dependencies section of the example dir of the async_redux package I mentioned:

    dependencies:
      http: ^0.13.1
      async_redux:
        path: ../
      flutter:
        sdk: flutter
    

    Since the example dir is at the same level as the package's pubspec.yaml file, then the example's own pubspec.yaml is one level below it. Thus, it may reference the package itself by using a ../ path:

      async_redux:
        path: ../