How to include git ignored file in github actions with flutter? - macos

In my project I have some JSON files that are used to get environment configurations at runtime through an entrypoint to the main dart file, they hold sensitive data so I put their containing folder in the .gitignore file.
I have written a test that passes when I run it locally, but fails when triggered by the github action because of this error:
The following assertion was thrown running a test:
Unable to load asset: assets/config/dev.json
Is there a way to somehow inject this JSON while performing the action? Any help is much appreciated, my only concern is having private data not stored in the github repository and having the action pass.
This is my code:
custom entry point
dev_run.dart
import 'package:gitgo/main.dart' as App;
void main() {
App.main('dev');
}
The class that has access to the JSON:
EnvironmentConfig
import 'dart:convert';
import 'package:flutter/services.dart';
class EnvironmentConfig {
final Map<String, String> environment;
EnvironmentConfig({this.environment});
static Future<EnvironmentConfig> forEnvironment(String env) async {
env = env ?? 'dev';
final contents = await rootBundle.loadString(
'assets/config/$env.json',
);
final Map<String, String> json = Map.castFrom(jsonDecode(contents));
return EnvironmentConfig(environment: json);
}
}
Dependencies
pubspec.yaml
name: gitgo
description: Git on the go.
version: 1.0.0+1
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
http: ^0.12.1
oauth2: ^1.6.1
url_launcher: ^5.4.10
flutter_config: ^1.0.8
gql: ^0.12.3
gql_exec: ^0.2.4
gql_link: ^0.3.0
gql_http_link: ^0.3.2
dev_dependencies:
flutter_test:
sdk: flutter
build_runner: ^1.11.1
gql_build: ^0.0.11
pedantic: ^1.9.0
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
# To add assets to your application, add an assets section, like this:
assets:
- assets/config/
Main file
main.dart
import 'package:flutter/material.dart';
import 'package:gitgo/inbound/configuration/config_environment_widget.dart';
import 'package:gitgo/outbound/api/viewer.req.gql.dart';
import 'package:gql_exec/gql_exec.dart';
import 'package:gql_link/gql_link.dart';
import 'package:gitgo/outbound/api/viewer.data.gql.dart';
import 'package:gitgo/outbound/auth.dart';
import 'package:gql_http_link/gql_http_link.dart';
import 'inbound/configuration/environment_config.dart';
Future main(String env) async {
WidgetsFlutterBinding.ensureInitialized();
final config = await EnvironmentConfig.forEnvironment(env);
print("starting app in $env mode");
runApp(MyApp(config));
}
class MyApp extends StatelessWidget {
final EnvironmentConfig config;
MyApp(this.config);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'GitGo Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: EnvironmentConfigWidget(
config: config, child: MyHomePage(title: 'GitGo Demo Home Page')),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState(title: "GitHub login");
}
class _MyHomePageState extends State<MyHomePage> {
_MyHomePageState({this.title});
EnvironmentConfigWidget environmentConfigWidget;
String title;
#override
Widget build(BuildContext context) {
return GithubLoginWidget(
builder: (context, httpClient) {
final link = HttpLink(
'https://api.github.com/graphql',
httpClient: httpClient,
);
return FutureBuilder<$ViewerDetail$viewer>(
future: viewerDetail(link),
builder: (context, snapshot) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Center(
child: Text(
snapshot.hasData
? 'Hello ${snapshot.data?.login}!'
: 'Retrieving viewer login details...',
),
),
);
},
);
},
githubClientId: EnvironmentConfigWidget.of(context)
.config
.environment['githubClientId'],
githubClientSecret: EnvironmentConfigWidget.of(context)
.config
.environment['githubClientSecret'],
githubScopes: EnvironmentConfigWidget.of(context)
.config
.environment['githubScopes']
.split(","));
}
}
Future<$ViewerDetail$viewer> viewerDetail(Link link) async {
var result = await link.request(ViewerDetail((b) => b)).first;
if (result.errors != null && result.errors.isNotEmpty) {
throw QueryException(result.errors);
}
return $ViewerDetail(result.data).viewer;
}
class QueryException implements Exception {
QueryException(this.errors);
List<GraphQLError> errors;
#override
String toString() {
return 'Query Exception: ${errors.map((err) => '$err').join(',')}';
}
}
Failing test in github actions but not locally
widget_dart.test
import 'package:flutter_test/flutter_test.dart';
import 'package:gitgo/inbound/configuration/environment_config.dart';
import 'package:gitgo/main.dart';
void main() {
testWidgets('Smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
var env = await EnvironmentConfig.forEnvironment('dev');
await tester.pumpWidget(MyApp(env));
// Verify that our counter starts at 0.
expect(find.text('Log into Github'), findsOneWidget);
expect(find.text('1'), findsNothing);
});
}
Github action
ci.yml
name: ci
jobs:
ci:
name: ci
runs-on: macos-latest
steps:
- name: Checkout code
uses: actions/checkout#v2
- name: Flutter test
uses: subosito/flutter-action#v1.4.0
with:
flutter-version: '1.26.0-17.2.pre'
channel: dev
- run: flutter pub get
- run: flutter analyze
- run: flutter test --no-sound-null-safety
- name : Clean merged branches
run: |
git fetch -p && for branch in $(git branch -vv | grep ': gone]' | awk '{print $1}'); do git branch -D $branch; done
echo "Finished cleaning"

You can use GitHub Action secrets.
Put your dev.json contents in a secret (for example, DEV_JSON_CONTENTS), and write it to the correct location with a command.
- name: Write dev.json
run: echo '{{ secrets.DEV_JSON_CONTENTS }}' > assets/config/dev.json

The proposed solution didn't work for me, but as hacker1024 pointed out:
Put your dev.json contents in a secret (for example, DEV_JSON_CONTENTS), and write it to the correct location with a command.
So what worked in my case, was adding the github secret DEV_JSON with the contents of the original file, then
I modified the workflow file by adding the secret as an env variable in the workflow:
env:
DEV_JSON : ${{ secrets.DEV_JSON }}
And I added this step to write the contents to a new file:
- name: Write dev.json
run: |
touch assets/config/dev.json
echo $DEV_JSON >> assets/config/dev.json
cat assets/config/dev.json

Related

Can't add mathtype plugin locally in CKEditor

import React from 'react'
import CKEditor4 from 'ckeditor4-react'
export default function App () {
return (
<CKEditor4
data='<h1>hello</h1>'
config={{
extraPlugins: ['ckeditor_wiris'],
allowedContent: true,
height: 300,
startupFocus: 'end',
skin: 'moono'
}}
onBeforeLoad={(CKEDITOR) => {
CKEDITOR.plugins.addExternal(
'ckeditor_wiris',
'https://www.wiris.net/demo/plugins/ckeditor/',
'plugin.js'
)
}}
/>
)
}
I created a react app using CRA, this code will render CKEditor with Mathtype plugin.
I want to use mathtype from this package, https://www.npmjs.com/package/#wiris/mathtype-ckeditor4, locally instead of the path https://www.wiris.net/demo/plugins/ckeditor/.
CKEDITOR.plugins.addExternal(
'ckeditor_wiris',
'../node_modules/#wiris/mathtype-ckeditor4/',
'plugin.js'
)
But I'm getting an error when I change the mathtype path,
Since we can't directly access files from node_modules folder from CRA App, due to webpack configuration, we should copy #wiris/mathtype-ckeditor4/ folder to public folder at the build time.
To do that, first integrate react-app-rewired to customize webpack without ejecting it. And then install copy-webpack-plugin to copy files at a build time, finally inside config-overrides.js add this snippet to copy mathtype to mathtype-ckeditor4 folder inside public folder.,
const CopyWebpackPlugin = require('copy-webpack-plugin')
module.exports = function override (config, env) {
config.plugins.push(
new CopyWebpackPlugin({
patterns: [
{ from: 'node_modules/#wiris/mathtype-ckeditor4', to: 'mathtype-ckeditor4' }
]
})
)
return config
}
Lastly change the code inside onBeforeLoad to this,
CKEDITOR.plugins.addExternal('ckeditor_wiris', '/mathtype-ckeditor4/', 'plugin.js')
This way we can install and use mathtype locally in CKEditor.

Retrive data from laravel API to flutter app

I have created a connection between my flutter app and laravel api, but i don't know why i can't get some data (image) from the back-end to be display on the app. I'm running the laravel api on a local server and flutter app on an android emulator.
Here's my code...
From Laravel api - CategoriesResource.php
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class CategoriesResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function toArray($request)
{
return [
'categoryName' => $this->categoryName,
'category_image' => 'http://127.0.0.1:8000/api/v1/public/category_images/'.$this->category_image
];
}
}
My flutter code ...
import 'package:flutter/material.dart';
import 'package:restaurant_app/models/category.dart';
class HomeCategoriesGet extends StatefulWidget {
final List<Category> categoryList;
final int categoryId;
final String categoryName;
final String categoryImage;
#override
HomeCategoriesGet(
{this.categoryList,
this.categoryId,
this.categoryName,
this.categoryImage});
_HomeCategoriesGetState createState() => _HomeCategoriesGetState();
}
class _HomeCategoriesGetState extends State<HomeCategoriesGet> {
#override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: this.widget.categoryList.length,
itemBuilder: (context, index) {
return Card(
child: Column(
children: <Widget>[
Image.network(
// This is where i am trying to get the image
this.widget.categoryList[index].catImage,
width: 190.0,
height: 160.0,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(this.widget.categoryList[index].name),
),
],
),
);
},
);
}
}
Error
════════════════════════════ Exception caught by image resource service ════════════════════════════
The following SocketException was thrown resolving an image codec:
OS Error: Connection refused, errno = 111, address = 127.0.0.1, port = 48849
When the exception was thrown, this was the stack
#0 NetworkImage._loadAsync
package:flutter/…/painting/_network_image_io.dart:84
<asynchronous suspension>
#1 NetworkImage.load
package:flutter/…/painting/_network_image_io.dart:48
#2 ImageProvider.resolve.<anonymous closure>.<anonymous closure>.<anonymous closure>
package:flutter/…/painting/image_provider.dart:316
#3 ImageCache.putIfAbsent
package:flutter/…/painting/image_cache.dart:160
...
Image provider: NetworkImage("http://127.0.0.1:8000/api/v1/public/category_images/starters_1578944124.jpeg", scale: 1.0)
Image key: NetworkImage("http://127.0.0.1:8000/api/v1/public/category_images/starters_1578944124.jpeg", scale: 1.0)
Please here's my Repository.dart file
import 'package:http/http.dart' as http;
// Create connection with Back-end (laravel)
class Repository {
// connection with emulator
String _baseUrl = 'http://10.0.2.2:8000/api';
httpGet(String api) async {
return await http.get(_baseUrl + "/" + api);
}
httpGetById(String api, id) async {
return await http.get(_baseUrl + "/" + api + "/" + id.toString());
}
}
Please help me solve this. Thanks
To solve this:
first run php artisan serve --host 0.0.0.0
Then get your local IP by typing the following command on the terminal :
for Windows : ipcofing
Linux or Mac : ifconfig
In my case it's: IPv4 Address . . . . . . . . . . : 192.168.1.122
Finally:
`
class Repository {
// connection with emulator
String _baseUrl = 'http://192.168.1.122:8000/api';
....
}
`
remove the /api in the baseUrl variable

Expected 2 arguments, but got 1.ts(2554) core.d.ts(8054, 47): An argument for 'opts' was not provided

This is a part of my code that I get this error:
Expected 2 arguments, but got 1.ts(2554)
core.d.ts(8054, 47): An argument for 'opts' was not provided.
from here:
import {ViewChild, ChangeDetectorRef, AfterViewInit} from "#angular/core";
import {RadSideDrawerComponent, SideDrawerType} from "nativescript-telerik-ui/sidedrawer/angular";
export class DrawerPage implements AfterViewInit {
#ViewChild(RadSideDrawerComponent) protected drawerComponent: RadSideDrawerComponent;
protected drawer: SideDrawerType;
constructor(private _changeDetectorRef: ChangeDetectorRef) { }
ngAfterViewInit() {
this.drawer = this.drawerComponent.sideDrawer;
this._changeDetectorRef.detectChanges();
}
protected openDrawer() {
this.drawer.showDrawer();
}
protected closeDrawer() {
this.drawer.closeDrawer();
}
}
I can't understand what is the problem? I am new learner who follows a tutorial video to learn NativeScript!
In Angular 8 , ViewChild takes 2 parameters:
Try like this:
#ViewChild('nameInput', { static: false }) nameInputRef: ElementRef;
Explanation:
{ static: false }
If you set static false, the component ALWAYS gets initialized after the view initialization in time for the ngAfterViewInit/ngAfterContentInit callback functions.
{ static: true}
If you set static true, the initialization will take place at the view initialization at ngOnInit
By default you can use { static: false }. If you are creating a dynamic view and want to use the template reference variable, then you should use { static: true}
For more info, you can read this here
Thank you.
You are using nativescript-telerik-ui/sidedrawer and that is not supported by latest version of Nativscript.This package has been deprecated.
For side drawer, use nativescript-ui-sidedrawer.

How do I pass an Internationalization Object to Child Widgets in Flutter

Just getting started with Flutter/dart, transitioning for PHP, and struggling to figure out how to pass classes into widgets.
I am working on creating my first android and iOS applications using flutter.
I am working with internationalization and everything works fine at my initial build page using the internationalization class I have. However, when passing it on to another widget I get:
NoSuchMethodError: The getter textTitle was called on null.
Receiver: null
tried calling: textTitle
What is the best way of handling this?
Flutter Doctor
[✓] Flutter (Channel beta, v0.1.5, on Mac OS X 10.13.3 17D47, locale en-US)
[✓] Android toolchain - develop for Android devices (Android SDK 27.0.1)
[✓] Android Studio (version 3.0)
[✓] Connected devices (1 available)
Localization dart
class HnLocalizations{
HnLocalizations(this.locale);
final Locale locale;
static HnLocalizations of(BuildContext context){
return Localizations.of<HnLocalizations>(context, HnLocalizations);
}
static Map<String, Map<String, String>> _localizedValues = {
'en': {
'btnLabelLoginS1': 'Login',
'btnLabelRegisterS1': 'Sign Up'
},
;
String get s1ButtonLabelLogin =>
_localizedValues[locale.languageCode]['btnLabelLoginS1'];
class HnLocalizationsDelegate extends LocalizationsDelegate<HnLocalizations> {
const HnLocalizationsDelegate();
#override
bool isSupported(Locale locale) => ['en', 'es'].contains(locale.languageCode);
#override
Future<HnLocalizations> load(Locale locale) =>
new SynchronousFuture<HnLocalizations>(new HnLocalizations(locale)); //HnLocalizations.load(locale);
#override
bool shouldReload(HnLocalizationsDelegate old) => false;
}
Main Dart
void main() {
runApp(new MaterialApp(
localizationsDelegates: [
const HnLocalizationsDelegate(),
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
supportedLocales: [
const Locale('en', 'US'), /// Americans
const Locale('en', 'GB') /// Brits
],
title: 'HN',
home: new EntryPage(),
));
}
class EntryPage extends StatelessWidget {
final HnColors _hnColors = new HnColors();
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
// !!!**** THIS WORKS AS EXPECTED ****!!!!
title: new Text(HnLocalizations.of(context).s1ButtonLabelLogin),
backgroundColor: _hnColors.transparent(),
elevation: 0.0,
),
backgroundColor: _hnColors.accent(),
body: new Container(
decoration: new BoxDecoration(
image: new DecorationImage(
image: new AssetImage("assets/Background_World.png"),
fit: BoxFit.fitWidth,
),
),
child: new PanelArea(),
)
);
}
}
class PanelArea extends StatelessWidget {
#override
Widget build(BuildContext context) {
HnColors _hnColors = new HnColors();
return new Container(
child: new Center(
child: new Container(
decoration: new BoxDecoration(
borderRadius: new BorderRadius.circular(15.0),
color: _hnColors.transparent()
),
child: new Column(
children: [
new Image.asset('assets/Icon_Intro_login'),
new Text(
// !!!**** ERROR IS HERE ****!!!!
HnLocalizations.of(context).s1M1HeaderTitle,
style: new TextStyle(
color: _haillioColors.white()
),
),
What is the best way of handling this?
Update: Mar 11 2018
I've discovered that if I move all of the code into the main.dart file. All localization works fine. However, when I move my widgets into a separate dart file, the errors come back, even though all of the code is the same.
Update: Mar 12 2018
nicolás-carrasco pointed in the right direction by a reference in this post (Thank you). The problem had to do with imports which is addressed in this post here which ended up being the solution that worked for me. The example is added below in answers.
Nicolás Carrasco pointed towards a solution which was related to what was causing the problem for me by way of link to this post.
In the localization.dart file imports I had:
import 'package:hn/hnLocalization.dart';
While in the main.dart file imports I had:
import 'hnLocalization.dart';
These are not the same thing as described here
Making sure that all files are imported using relative paths vs packages resolved the problem. The distinction is that my files, not the dependencies use relative path. That part stumped at first.
Now my localization.dart file has the following.
import 'hnLocalization.dart'; // <--- Using relative Path
class PanelArea extends StatelessWidget {
#override
Widget build(BuildContext context) { ...
child: new Column(
children: [
new Image.asset('assets/Icon_Intro_login'),
// This Now Works --->
new Text(HnLocalizations.of(context).s1M1HeaderTitle,
]
...
and all is right now.

ionic 2 build error on visual studio

I imported my ionic 2 app into the visual studio. Before I did that, There was not any build error but, know it gives me following errors;
this is my firms.ts file;
import { Component } from '#angular/core';
import { FirmService } from '../../providers/getFirms';
import { Observable } from 'rxjs/Rx';
import {ReportsPage} from '../report/report';
import { Auth } from '../../providers/auth';
import {LoginPage} from '../login-page/login-page';
import { NavController, ModalController, AlertController, LoadingController,NavParams } from 'ionic-angular';
import {
FormGroup,
FormControl
} from '#angular/forms';
/*
Generated class for the Firms page.
See http://ionicframework.com/docs/v2/components/#navigation for more info on
Ionic pages and navigation.
*/
#Component({
selector: 'page-firms',
templateUrl: 'firms.html'
})
export class FirmsPage {
langs;
langForm;
loading: any;
username : string;
firms: string[];
constructor(public navCtrl: NavController, private navParams: NavParams, public firmService: FirmService, public loadingCtrl: LoadingController, public authService: Auth) {
this.getFirms();
this.username = this.navParams.get("param");
this.langForm = new FormGroup({
"langs": new FormControl('')
});
}
how can it cannot find them. I think, I imported correct paths.
Probably you are not taking the correct names of those Providers. Remember that you have to make reference to the class name.
export class AuthService { }
Both seem related to the providers route, are you 100% sure its correct? It would be easier to answer your question if you could make a jsfiddle or link to a repo.
1 - install npm https://nodejs.org
2 - install typescript npm install -g typescript
3 - Change the settings in VS to use your PATH first, this is the main issue always when you install npm, VS now comes with npm embedded.
Tools -> Options -> Projects and Solutions -> External Web Tools
Select $(PATH) and with the arrows (right corner) move the PATH to the first row.

Resources