I am having a Future that is async and returns a List of HashMap<String, dynamic> that I would like to log. I am using
Below is the Future
Future<List<HashMap<String, dynamic>>> _fetchUsersUsingListOfHashMap() async {
try {
final response = await http.get(Uri.parse("https://jsonkeeper.com/b/XBCA"));
final decodedJson = json.decode(response.body);
final responseList = decodedJson.map<HashMap<String, dynamic>>((e) => HashMap<String, dynamic>.from(e)).toList();
return responseList;
} catch (e) {
log("FetchUsersUsingListOfHashMapException $e");
rethrow;
}
}
Below is my initState where i am printing
#override
void initState() {
log("PrintFetchUsersUsingListOfHashMap $_fetchUsersUsingListOfHashMap()");
super.initState();
}
Below is how the list should look like when i am logging
[
{
"name": "Kamchatka",
"about": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Maxime mollitia,molestiae quas vel sint commodi repudiandae consequuntur voluptatum laborumnumquam blanditiis harum quisquam eius sed odit fugiat iusto fuga praesentium optio, eaque rerum! Provident similique accusantium nemo autem.",
"email": "kamchatka#mail.com",
"index": 1,
"picture": "https://thispersondoesnotexist.com/"
},
{
"name": "Valjakutse",
"about": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Maxime mollitia,molestiae quas vel sint commodi repudiandae consequuntur voluptatum laborumnumquam blanditiis harum quisquam eius sed odit fugiat iusto fuga praesentium optio, eaque rerum! Provident similique accusantium nemo autem.",
"email": "valjakutse#mail.com",
"index": 2,
"picture": "https://thispersondoesnotexist.com/"
},
{
"name": "Shipment",
"about": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Maxime mollitia,molestiae quas vel sint commodi repudiandae consequuntur voluptatum laborumnumquam blanditiis harum quisquam eius sed odit fugiat iusto fuga praesentium optio, eaque rerum! Provident similique accusantium nemo autem.",
"email": "shipment#mail.com",
"index": 3,
"picture": "https://thispersondoesnotexist.com/"
}
]
But when I am logging I am getting something like this below
PrintFetchUsersUsingListOfHashMap Closure: () => Future<List<HashMap<String, dynamic>>> from Function '_fetchUsersUsingListOfHashMap#20327479':.()
How can i be able to print the list i have tried using print below but its return Closure
print("PrintFetchUsersUsingListOfHashMap $_fetchUsersUsingListOfHashMap()");
In your code _fetchUsersUsingListOfHashMap() is Future and if you directly try to print it it will return you a Instance of Future not the value and to print the value you need to call another function using async and await to fetch the value from your Future function like and call that function in your initState.
void printData() async {
log("PrintFetchUsersUsingListOfHashMap ${ await _fetchUsersUsingListOfHashMap()}");
}
#override
void initState() {
printData();
super.initState();
}
_fetchUsersUsingListOfHashMap is a future, consider using the await keyword before printing.
As a example:
var result = await someFutureFunction();
print('result: $result')
All that inside a async function.
I have created a template:
<template>
<div>
<slot></slot>
</div>
</template>
<script>
export default {
data() {
return {
isShowing: false
}
},
methods: {
toggleShow: function() {
this.isShowing = !this.isShowing;
setTimeout(() => {
this.toggleShow1();
}, 800);
}
}
<script>
<style>
..
</style>
And in the HTML document i'd like to toggle a heading only when isShowing is set to true:
<div v-if="isShowing">
<div>
<h1>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</h1>
</div>
</div>
But then i get this error: ReferenceError: isShowing is not defined
Any help would be much appreciated. Thanks!
You're using a data of vue instance outside of itself. isShowing can only be used inside the <template> of the same .vue file.
For example:
<template>
<div>
<div v-if="isShowing">
<slot></slot>
</div>
</div>
</template>
<script>
export default {
data() {
return {
isShowing: false
}
},
methods: {
toggleShow: function() {
this.isShowing = !this.isShowing;
setTimeout(() => {
this.toggleShow1();
}, 800);
}
}
<script>
<style>
..
</style>
I'm trying to create a regular expression to sift through information in a text file (Notepad++), but only if the character has a "the" in the name.
My current expression: \\{[\r\n]+id:(.\*?)+name:\s+(\bthe\b)(.*?)[\r\n]\\}
{
id: 1
locID: A
tStart: 17:10:00
tEnd: 17:35:00
name: the man 45
text: Lorum Ipsum
}
{
id: 2
locID: A
tStart: 17:11:00
tEnd: 17:12:00
name: Frank
text: Lorum Ipsum
}
{
id: 3
locID: A
tStart: 17:11:00
tEnd: 17:14:00
name: Frank
text: Lorum Ipsum
}
{
id: 4
locID: B
tStart: 17:51:00
tEnd: 17:56:00
name: the woman 2
text: Lorum Ipsum
}
{
id: 5
locID: A
tStart: 17:11:00
tEnd: 16:11:00
name: the man with the golden gun
text: Lorum Ipsum
}
{
id: 6
locID: C
tStart: 17:11:00
tEnd: 17:11:00
name: the woman with the dragon tattoo
text: Lorum Ipsum
}
{
id: 7
locID: A
tStart: 17:15:00
tEnd: 17:15:00
name: Jo
text: Lorum Ipsum
}
What I want is to only get
{
id: 1
locID: A
tStart: 17:10:00
tEnd: 17:35:00
name: the man 45
text: Lorum Ipsum
}
{
id: 4
locID: B
tStart: 17:51:00
tEnd: 17:56:00
name: the woman 2
text: Lorum Ipsum
}
{
id: 5
locID: A
tStart: 17:11:00
tEnd: 16:11:00
name: the man with the golden gun
text: Lorum Ipsum
}
{
id: 6
locID: C
tStart: 17:11:00
tEnd: 17:11:00
name: the woman with the dragon tattoo
text: Lorum Ipsum
}
Can someone tell me what I need to do to skip the rest of the line?
My current setup returns everything, and Frank id:2 Frank id:3 the woman 2 id:4.
Thanks mickmackusa.
Solution: {[^}]*name:[^}]*\bthe\b[^}]*\}
The negated character classes [^}] speed everything up and avoid getting snagged on newline characters. The * can be greedy because they will be halted on name:, the, and }.
Pattern (Demo Link):
{[^}]*name:[^}]*\bthe\b[^}]*}
Edit (escaping the curly bracket version):
\{[^}]*name:[^}]*\bthe\b[^}]*\}
I have a problem which might be simple but I can't figure it out :)
I have a slim 3 / twig app and have made an global variable so I can get the currentUrl in twig.
In a template-file I wan't an if statement checking if the currentUrl contains the string '/forretter' so it only show these products in an for loop.
If I do an simple {{ currentUrl }} it prints the url as expected - but the if statement doesn't seem to accept the currentUrl variable.
I have tried to do an {% set url = currentUrl %} but no luck.
The if statement I am using looks like this {% if '/forretter' in currentUrl %} all other if statements I set up works like a charm.
home someone has an idea about this cause I beginning to get grey hair on my bald head :)
I have now tried Georgy Ivanov answer and tried to match it to my code - and the twig extension works - but the if statement doesn't.
Here is my container code
<?php
use function DI\get;
use Slim\Views\Twig;
use Cart\Basket\Basket;
use Cart\Models\Product;
use Cart\Models\Edit;
use Cart\Models\Order;
use Cart\Models\Customer;
use Cart\Models\Address;
use Cart\Models\Payment;
use Slim\Views\TwigExtension;
use Slim\Views\IsInUrlExtension;
use Interop\Container\ContainerInterface;
use Cart\Support\Storage\SessionStorage;
use Cart\Support\Storage\Contracts\StorageInterface;
use Cart\Validation\Contracts\ValidatorInterface;
use Cart\Validation\Validator;
return [
'router' => get(Slim\Router::class),
ValidatorInterface::class => function (ContainerInterface $c) {
return new Validator;
},
StorageInterface::class => function (ContainerInterface $c) {
return new SessionStorage('cart');
},
Twig::class => function (ContainerInterface $c) {
$twig = new Twig(__DIR__ . '/../resources/views', [
'debug' => true,
'cache' => false,
]);
$basePath = rtrim(str_ireplace('index.php', '', $c->get('request')->getUri()->getBasePath()), '/');
// Add Slim specific extension
$twig->addExtension(new Twig_Extension_Debug());
$twig->addExtension(new TwigExtension(
$c->get('router'), $basePath,
$c->get('request')->getUri()
));
$twig->addExtension(new IsInUrlExtension($c->get('request')->getUri()));
$twig->getEnvironment()->addGlobal('currentUrl',$c->get('request')->getUri());
$twig->getEnvironment()->addGlobal('basket', $c->get(Basket::class));
return $twig;
},
Product::class => function (ContainerInterface $c) {
return new Product;
},
Edit::class => function (ContainerInterface $c) {
return new Edit;
},
Order::class=> function (ContainerInterface $c) {
return new Order;
},
Customer::class=> function (ContainerInterface $c) {
return new Customer;
},
Address::class=> function (ContainerInterface $c) {
return new Address;
},
Payment::class=> function (ContainerInterface $c) {
return new Payment;
},
Basket::class => function (ContainerInterface $c) {
return new Basket(
$c->get(SessionStorage::class),
$c->get(Product::class)
);
}
];
And here is the twig code with the if statement
{% extends 'templates/app.twig' %}
{% block navigation %}
{% include 'templates/partials/navigation.twig' %}
{% endblock %}
{% block content %}
<div class="row p__top">
{% include 'templates/partials/sidebar_left.twig' %}
<section class="col-sm-12 col-md-6">
<div class="product">
{% if is_in_url('/forretter') %}
<div class="row">
<div class="categori__image">
<img class="card-img-top" src="{{site_url}}/images/varmrogetlaks.jpg" alt="Forretter">
</div>
<header class="menu__block">
<h3 class="menu__title">Forretter</h3>
</header>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
<div class="card-deck">
{% include 'products/dinertransportable/partials/produkter.twig' %}
</div>
</div>
{% else %}
test2
{{ dump(currentUrl) }}
{% endif %}
</div>
</section>
{% include 'templates/partials/sidebar_right.twig' %}
</div>
{% endblock %}
You could create a Twig extension, something like this:
<?php
class IsInUrlExtension extends \Twig_Extension
{
public function __construct($currentUrl)
{
$this->currentUrl;
}
public function getName()
{
return 'extName';
}
public function getFunctions()
{
return [
new \Twig_SimpleFunction('is_in_url', [$this, 'isInUrl']);
];
}
public function isInUrl(string $substr) : bool
{
return strpos($this->currentUrl, $substr) !== false;
}
}
Add this extension when you're registering Twig component in your container:
// Register component on container
$container['view'] = function ($container) {
$view = new \Slim\Views\Twig('path/to/templates', [
'cache' => 'path/to/cache'
]);
// Instantiate
$basePath = rtrim(str_ireplace('index.php', '', $container['request']->getUri()->getBasePath()), '/');
// Add Slim specific extension
$view->addExtension(new Slim\Views\TwigExtension($container['router'], $basePath));
// Add your extension
$view->addExtension(new IsInUrlExtension($container->get('request')->getUri()));
return $view;
};
Then you could use it within your templates like this:
{% if is_in_url('/forreter') %}
// substring is in current URL
{% endif %}
The benefit of this method is that you don't have to declare global currentUrl variable in your templates, and this strpos logic is not implemented in your templates, or, rather, it is encapsulated in your reusable extension.
I'm still trying to figure out how ember works and I want to have more info on managing multiple checkboxes in ember..
here's what I tried to do: http://jsbin.com/datojebu/2/edit
as you can see all checkboxes get selected and the checked function doesn't get called
what's the correct way of doing this?
Check this now. http://jsbin.com/datojebu/3/edit
{{#each genre in genres}}
{{input type="checkbox" name=genre.id checked=genre.isChecked}} {{genre.nom}}
{{/each}}
you have to add genre.isChecked else same isChecked will be binded to all checkboxes.
BTW if you want to have controller for each item, you can add ItemController in the array controller. Here is another example.
/* controllers */
App.AnimesController = Ember.ArrayController.extend({
itemController: 'anime'
});
Okay further to your additional questions, I've basically finished your app for you:
http://jsbin.com/datojebu/11/edit
App = Ember.Application.create();
App.ApplicationAdapter = DS.RESTAdapter.extend({
host: '/api',
namespace: 'fr'
});
/* router */
App.Router.map(function() {
this.resource('animes');
});
App.AnimesRoute = Ember.Route.extend({
model: function() {
return this.store.find('anime');
},
setupController: function(controller, model) {
this._super();
this.store.find('genre').then(function(genres) {
controller.set('genres', genres);
});
controller.set('model', model);
}
});
/* models */
var model = DS.Model,
attr = DS.attr,
hasMany = DS.hasMany;
App.Genre = model.extend({
animes: hasMany('anime', {async: true}),
nom: attr('string')
});
App.Anime = model.extend({
nom: attr('string'),
parution: attr('number'),
synopsis: attr('string'),
likes: attr('number'),
auteur: attr('string'),
genres: hasMany('genre', {async: true})
});
/* controllers */
App.AnimesController = Em.ArrayController.extend({
genres: Em.A([]),
selectedGenreIds: Em.A([]), // a set of ids
selectedGenres: function() {
var genres = this.get('genres'),
selectedGenreIds = this.get('selectedGenreIds');
return genres.filter(function(genre) {
return selectedGenreIds.contains(genre.get('id'));
});
}.property('selectedGenreIds.#each', 'genres.#each'),
selectedAnimes: function() {
var allAnimes = this.get('model'),
selectedGenres = this.get('selectedGenres'),
filteredAnimes;
// for an anime to be shown, it has to have at
// least one of its genres selected
filteredAnimes = allAnimes.filter(function(anime) {
return anime.get('genres').any(function(animeGenre) {
return selectedGenres.contains(animeGenre);
});
});
return filteredAnimes;
}.property('model.#each', 'selectedGenres.#each', 'genres.#each')
});
App.GenreController = Em.ObjectController.extend({
needs: ['animes'],
isChecked: function(key, value) {
if(arguments.length > 1) {
// setter
var selectedGenreIds = this.get('controllers.animes.selectedGenreIds'),
thisId = this.get('id');
if(!selectedGenreIds.contains(thisId) && value) {
selectedGenreIds.addObject(thisId);
} else {
selectedGenreIds.removeObject(thisId);
}
}
// always return the value for the getter and the setter
return value;
}.property('controllers.animes.selectedGenreIds')
});
/* mockjax */
var animes = [
{
id: 1,
nom: 'Blah',
parution: 2014,
genres: [1, 3],
synopsis: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tempore, eveniet, ab pariatur omnis dolor sunt alias atque voluptate neque reiciendis maiores impedit quibusdam perferendis optio ratione expedita adipisci et. Cupiditate!',
likes: 206,
auteur: 'Moi :p'
}
],
genres = [
{
id: 1,
nom: 'action',
animes: []
},
{
id: 2,
nom: 'magie',
animes: [1]
},
{
id: 3,
nom: 'amour et amitier',
animes: []
},
{
id: 4,
nom: 'aventures',
animes: [1]
}
];
$.mockjax({
url: '/api/fr/animes',
responseTime: 750,
responseText: {
'animes': animes
}
});
$.mockjax({
url: '/api/fr/genres',
responseTime: 750,
responseText: {
'genres': genres
}
});
You need to do as CodeJack said...
Once you've done that, you use bindings to "know" which one is checked. That is to say you don't need to know it yourself, you just need to bind the correct values to the right spot.
Anyway, this jsbin should alleviate your issues... notice the console gets set with the value and triggered at the correct tiems/places.
http://jsbin.com/datojebu/6/edit
App = Ember.Application.create();
App.ApplicationAdapter = DS.RESTAdapter.extend({
host: '/api',
namespace: 'fr'
});
/* router */
App.Router.map(function() {
this.resource('animes');
});
App.AnimesRoute = Ember.Route.extend({
model: function() {
return this.store.find('anime');
},
setupController: function(controller, model) {
this._super(controller, model);
this.store.find('genre').then(function(genres){
controller.set('genres', genres);
});
}
});
/* models */
var model = DS.Model,
attr = DS.attr,
hasMany = DS.hasMany;
App.Genre = model.extend({
animes: hasMany('anime', {async: true}),
nom: attr('string')
});
App.Anime = model.extend({
nom: attr('string'),
parution: attr('number'),
synopsis: attr('string'),
likes: attr('number'),
auteur: attr('string'),
genres: hasMany('genre', {async: true})
});
/* controllers */
App.GenreController = Em.ObjectController.extend({
isChecked: function(key, value) {
if(arguments.length > 1) {
// setter
console.log('huzzah' + this.get('id') + ' val: ' + value);
}
// always return the value for the getter and the setter
return this.get('model.isChecked');
}.property(),
actions: {
click: function() {
console.log("hi");
}
}
});
/* mockjax */
var animes = [
{
id: 1,
nom: 'Blah',
parution: 2014,
genres: [1, 3],
synopsis: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tempore, eveniet, ab pariatur omnis dolor sunt alias atque voluptate neque reiciendis maiores impedit quibusdam perferendis optio ratione expedita adipisci et. Cupiditate!',
likes: 206,
auteur: 'Moi :p'
}
],
genres = [
{
id: 1,
nom: 'action',
animes: []
},
{
id: 2,
nom: 'magie',
animes: [1]
},
{
id: 3,
nom: 'amour et amitier',
animes: []
},
{
id: 4,
nom: 'aventures',
animes: [1]
}
];
$.mockjax({
url: '/api/fr/animes',
responseTime: 750,
responseText: {
'animes': animes
}
});
$.mockjax({
url: '/api/fr/genres',
responseTime: 750,
responseText: {
'genres': genres
}
});