How to perform Pub Get programatically from a Dart program - dart

I'm building a Dart framework called Modular for backend development and this framework has a installer for convenience. At the end of the installation, I'd like to install all dependancies in the generated pubspec.yaml file. How would I do this? Thank you

import 'dart:io';
void main() {
Process.run('pub', ['get'],
runInShell: true,
workingDirectory: 'dirWherePubspec.yaml_is')
.then((ProcessResult results) {
// ...
});
}
or alternatively Process.start(...)

Related

What is the Difference between Dart console-full and console-simple application?

While learning dart I came across to these type of console application, so I just want to know What is the Difference between Dart console-full and console-simple application?
Both templates generate a Dart project with some default files:
.dart_tool/package_config.json
.gitignore
.packages
analysis_options.yaml
CHANGELOG.md
pubspec.lock
pubspec.yaml
README.md
But does then also create Dart files which depends on the type of template:
console-simple
Creates a very basic Dart project with a single Dart file named bin/<project_name>.dart with the content:
void main(List<String> arguments) {
print('Hello world!');
}
console-full
Create a more complete Dart project where we split the code into bin/, lib/, and test/. The description in the auto-generated README.md file does explain the file structure:
A sample command-line application with an entrypoint in bin/, library code
in lib/, and example unit test in test/.
The project makes use of the test package for unit testing so the project will by default include this package in the pubspec.yaml.
Following Dart files is generated to make use of the three directories:
// bin/project_name.dart
import 'package:project_name/project_name.dart' as project_name;
void main(List<String> arguments) {
print('Hello world: ${project_name.calculate()}!');
}
// lib/project_name.dart
int calculate() {
return 6 * 7;
}
// test/project_name_test.dart
import 'package:project_name/project_name.dart';
import 'package:test/test.dart';
void main() {
test('calculate', () {
expect(calculate(), 42);
});
}

Run dart script outside of a project folder

I am trying to replace python with dart as a scripting language for my tools. I can create a python file anywhere, import global packages and run it but I can't seem to get this working with dart. Do I always need a pubspec.yaml file to run a dart script?
This is the script I am trying to run:
import 'package:http/http.dart' as http;
main(List<String> args) async{
var res = await http.get('https://example.com');
print(res.headers);
}
This is the error I am getting:
Error: Could not resolve the package 'http' in 'package:http/http.dart'.
test2.dart:1:8: Error: Not found: 'package:http/http.dart'
import 'package:http/http.dart' as http;
^
test2.dart:4:19: Error: Method not found: 'get'.
var res = await http.get('https://example.com');
No, you don't need a pubspec.yaml file to run a program, but it does need to somehow be able to resolve all the imports.
The pubspec.yaml file is used for obtaining the packages (from pub.dev, a git repository, etc.) but not for finding the packages at runtime. The pub program reads the pubspec.yaml file and downloads the packages mentioned in it, and maintains a packages specification file indicating where each package resolves to. By default the packages specification is in a file called .packages in the same directory as the pubspec.yaml file. The Dart runtime normally finds the packages by looking at the .packages package specification file, but there are other ways.
Here are some options:
Put a .packages file in the same directory as the Dart program, or in an ancestor directory.
Use the --packages option to specify the package specification file to use:
dart --packages=/home/username/stuff/mypackagespecfile myprogram.dart
The Dart runtime also has a --package-root option. But I haven't figured out how to make it work.
The import statements use URIs, so import 'file://...'; can also work in some cases.
Use dart2native to compile the program into an executable.
Note: Dart scripts can also start with a hash-bang line:
#!/usr/bin/env dart
import 'package:http/http.dart' as http;
main(List<String> args) async{
var res = await http.get('https://example.com');
print(res.headers);
}
Then you can make the program executable and run it without needing to type in the Dart runtime:
$ chmod a+x myprogram.dart
$ ./myprogram.dart

HTTP plugin is not installed error with ionic

$ ionic cordova plugin add cordova-plugin-http
$ npm install --save #ionic-native/http
The implementation is:
constructor(private https: HTTP ) {
}
this.https.get('http://ionic.io', {}, {})
.then(data => {
this.httpData =data;
console.log(data.status);
})
.catch(error => {
console.log(error.status);
});
And I get this error:
[20:49:03] console.warn: Native: tried calling HTTP.get, but the HTTP plugin is not installed.
[20:49:03] console.warn: Install the HTTP plugin: 'ionic plugin add cordova-plugin-http'
If you do not want to modify the ionic-native plugin like suggested by #alpere or if the solution does not work you can always use the cordova plugin without ionic-native. To do so tell typescript that the http handle exists by adding the following somewhere below your imports:
declare var http;
And then use it like this:
http.get(
'https://ionic.io/',
{},
{},
response => {
console.log(response.status);
},
response => {
console.error(response.error);
},
);
Note that there is no need of this because cordova plugins are defined on a global scope. The downside of using plugins without the ionic-native wrapper is that you loose the nice type annotations, promise callbacks and in some cases you will have to trigger angular change-detection yourself.
The Ionic Native HTTP changed the cordova plugin they are using since the old one hasn't been updated for a while. During the change the reference to the plugin has't been updated so it's broken.
(See: https://github.com/silkimen/cordova-plugin-advanced-http/issues/8)
You can fix it by changing the old referenced plugin to new one:
(After the commit also updating the plugin will fix the issue)
in #ionic-native/plugins/http/index.ts:
change:
pluginRef: 'cordovaHTTP',
to:
pluginRef: 'cordova.plugin.http',
See commit:
https://github.com/ionic-team/ionic-native/commit/49ee0d85a304770a9a3bd3e04eb9609e6d565b67
It may be caused by any of these three issues:
The plugin is not installed;
You ran the code on a browser (or other limited environment); or
The platform is not ready (You called your code before the plugin was loaded).
The master branch of ionic already fixed pluginRef: 'cordova.plugin.http',
problem,
Still if the problem persists or you don't want to change the source files try these steps, it worked for me.
remove existing builds
rm -rf node_modules/ platforms/ plugins/ www/
update ionic native to latest build :
npm i --save ionic-native#latest
(please check with other plugin dependencies as well if its a problem try isolating packages via virtual environment setup - https://github.com/ekalinin/nodeenv ) :
add all your plugins required and http plugin ::
ionic cordova plugin add cordova-plugin-advanced-http
Then finally your plugins required and http plugin
npm install #ionic-native/http
Now your upon builds iOS or android should detect all the plugins
Ionic3 Cordova SSL pinning example
https://github.com/sijovijayan/SSL-pinning-with-ionic-cordova-example
In this example, you will get an idea about how implement SSL Pinning and How to Generate .cer file
try to run below command as suggested in error message to install HTTP plugin
ionic plugin add cordova-plugin-http
I would switch to Angular's HTTP instead of Cordova HTTP. Advantage: Does not require any plugin.
package.json:
"dependencies": {
...
"#angular/http": "4.1.3",
...
}
app.module.ts:
import { Http, HttpModule } from '#angular/http';
...
#NgModule({
declarations: [
MyApp,
],
imports: [
...
HttpModule,
...
]...
calling .ts-class:
import { Http } from '#angular/http';
...
constructor(... , public http: Http, ...) {
//Example: .get for a JSON and map it:
this.http.get(url).map(res => res.json()).subscribe(data => {
this.data = data;
});
}
Answer to first Comment:
As you seem to need SSL Pinning and I did not find an easy way in Angular HTTP yet, i saw that your command of adding the cordova plugin differs a little from the one from the documentation:
You wrote:
ionic cordova plugin add cordova-plugin-http
Now the command seems to be:
ionic cordova plugin add cordova-plugin-advanced-http
(https://ionicframework.com/docs/native/http/)
As you can see there, it supports your needs with methods like enableSSLPinning(enable).
If you are running the app from your pc, you might get such error.
Try using ionicdev
Ionic native plugins depend on the device features. So because of this plugins like http, contacts or camera would not work on your browser. An Example of such error is
Native: tried calling HTTP.post, but Cordova is not available. Make sure to include cordova.js or run in a device/simulator
So try to get ionic's app for developing app here https://play.google.com/store/apps/details?id=io.ionic.devapp
I had the same problem. And I managed to get rid of that error simply by declaring the Angular's HTTP module.
In app/app.modules.ts
import { HttpClientModule } from '#angular/common/http';
#NgModule({
imports: [
// import HttpClientModule after BrowserModule.
HttpClientModule,
],
})
Even if I don't use Angular's Module, this solved my problem.
Have you ever try to call plugin after the platform ready then check platform?
async checkVersion() {
const ready = !!await this.platform.ready();
if (ready && this.platform.is('cordova')) {
// try to add your code here
}
}
you have to remove code from ngoninit and add it in ionviewdidenter
ionViewDidEnter(){
//your code here
}

Cannot install material design lite for dart

I cannot seem to install MDL for Dart. My files are very simple.
pubspec.yaml:
name: mdl_test
dependencies:
mdl: "^1.0.0"
browser: '^0.10.0'
di: "^3.3.4"
transformers:
- di
main.dart:
import 'package:mdl/mdl.dart' as mdl;
main() async {
mdl.registerMdl();
await mdl.componentFactory().run();
}
I am getting multiple errors. Example: Target of URI does not exist: package:logging/logging.dart - I checked, and logging is downloaded properly.
There are many "Target of URI does not exist" errors as well. It seems that packages in main.dart are imported fine, but packages installed with pub, that import other packages, are not working. Does anyone know why this is, or what the fix is? Thanks.

How to use Dart with Webstorm 6 on Windows (running Codelab from Google IO 2013)

I searched for but didn't find any other posts remotely related to my question. Essentially, I'm attempting to follow the Dart Codelab from Google IO 2013 which I found here: http://goo.gl/4E21M
I'm attempting to use the Dart plugin in Webstorm 6 which I setup using the directions here: http://blog.jetbrains.com/webide/2012/12/dart-support-in-webstorm-6/
Lastly, I'm doing this on Windows 8.
My build.dart is:
import 'package:web_ui/component_build.dart';
import 'dart:io';
import 'dart:async';
void main() {
var args = new List.from(new Options().arguments);
build(new Options().arguments, ['web/index.html'])
.then((_) => print('Build finished!'));
}
My pubspec.yaml is:
name: writer
version: 0.0.1
author: Dart Team <misc#dartlang.org>
description: This is the finished version of the application built in the Google I/O 2013 Dart Codelab.
homepage: https://github.com/dart-lang/io-2013-dart-codelab
dependencies:
intl: any
web_ui: any
Yet, when I attempt to run the step 1 code, I see in my Event Log: Error running Test: build.dart: Missing library statement in build.dart.
So that seems straight-forward enough...except I can't figure out which library statement should be there that isn't... the only line of code I removed was:
#!/usr/bin/env dart
Because I'm attempting to run this on Windows, and that is for a UNIX environment.
Any thoughts? I really appreciate any assistance you can provide getting up and running with this Codelab in Webstorm (which is LIGHT YEARS more refined then the default Dart Editor). In other words, I FAR prefer Webstorm--if I can get things up and running in it.
Thank you in advance!
Thanks to #ChrisBuckett and #PixelElephant my question was answered. In order to get the Codelab from Google IO 2013, Step 1, to run I had to include "library build;" at the top of my build.dart file. In order to see the post-build output, I had to look in the /out folder and "run" the index.html file in Chromium.
This combination worked.
My fixed build.dart file:
library build;
import 'package:web_ui/component_build.dart';
import 'dart:io';
import 'dart:async';
void main() {
var args = new List.from(new Options().arguments);
build(args, ['web/index.html'])
.then((_) => print('Build finished!'));
}

Resources