IMPORT CSV TO LARAVEL 9 Undefined array key 24 - csv

i made import csv file to laravel. this is the contents of the CSV data that I will import :
data csv
when I try to import a CSV file whose contents are in the image I uploaded, which is empty/null, and I have added (Double) $row[24] ?? NULL to handle if the value is NULL then directly insert 0.0 in the table.CSV file
data type 'lemhanor' and 'lemakpek' --> data type lemhanor and lemakpek
whereas for 'lemhanor' and 'lemakpek' they have the same data type and in the CSV the values are both empty. What to do?
this is migration for absensi_table:
public function up()
{
Schema::create('absensi', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('id_karyawan');
$table->string('nik')->nullable()->default(null);
$table->date('tanggal');
$table->string('shift');
$table->time('jadwal_masuk');
$table->time('jadwal_pulang');
$table->time('jam_masuk');
$table->time('jam_keluar')->nullable()->default(null);
$table->double('normal',2,1);
$table->double('riil',2,1);
$table->time('terlambat')->nullable()->default(null);
$table->time('plg_cepat')->nullable()->default(null);
$table->string('absent',5);
$table->time('lembur')->nullable()->default(null);;
$table->time('jml_jamkerja')->nullable()->default(null);
$table->string('pengecualian')->nullable()->default(null);
$table->string('hci',5)->default(True);
$table->string('hco',5)->default(True);
$table->string('id_departemen');
$table->double('h_normal',2,1);
$table->double('ap',2,1);
$table->double('hl',2,1);
$table->time('jam_kerja')->nullable()->default(null);
$table->double('lemhanor',2,1);
$table->double('lemakpek',2,1);
$table->double('lemhali',2,1);
$table->foreign('id_karyawan')->references('id')->on('karyawan')->onDelete('cascade');
$table->timestamps();
});
}
this is AttendanceImport.php in HTTP folder:
<?php
namespace App\Imports;
use Carbon\Carbon;
use App\Models\Absensi;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithStartRow;
use Maatwebsite\Excel\Concerns\WithCustomCsvSettings;
class AttendanceImport implements ToModel
{
public function startRow(): int
{
return 2;
}
public function getCsvSettings(): array
{
return [
'delimiter' => ';'
];
}
/**
* #param array $row
*
* #return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
if(isset($row[0]) && isset($row[2]))
{
if(!Absensi::where('id_karyawan',$row[0])->where('tanggal',Carbon::parse($row[2])->format("Y-m-d"))->exists())
{
return new Absensi([
'id_karyawan' => $row[0],
'nik' => $row[1] ?? null,
'tanggal' => Carbon::parse($row[2])->format("Y-m-d"),
'shift' => $row[3] ?? null,
'jadwal_masuk' => $row[4] ?? null,
'jadwal_pulang' => $row[5] ?? null,
'jam_masuk' => $row[6] ?? null,
'jam_keluar' => $row[7] ?? null,
'normal' => $row[8] ?? null,
'riil' => (Double) $row[9] ?? null,
'terlambat' => $row[10] ?? null,
'plg_cepat' => $row[11] ?? null,
'absent' => $row[12] ?? null,
'lembur' => $row[13] ?? null,
'jml_jamkerja' => $row[14] ?? null,
'pengecualian' => $row[15] ?? null,
'hci' => $row[16] ?? null,
'hco' => $row[17] ?? null,
'id_departemen' => $row[18] ?? null,
'h_normal' => (Double) $row[19] ?? null,
'ap' => (Double) $row[20] ?? null,
'hl' => (Double) $row[21] ?? null,
'jam_kerja' => $row[22] ?? null,
'lemhanor' => (Double) $row[23] ?? null,
'lemakpek' => (Double) $row[24] ?? null,
'lemhali' => (Double) $row[25] ?? null,
]);
// dd($row);
}
// else{
// Log::info('id karyawan dan tanggal absensi sudah ada');
// }
}
// else{
// Log::info('Row 0 dan 2 kosong');
// }
}
}
Controller:
public function importcsv(Request $request)
{
Excel::import(new AttendanceImport, request()->file('file'));
return redirect()->back()->with('success','Data Imported Successfully');
}

Related

NoSuchMethodError: Class 'int' has no instance method '[]'

I'm trying to get mysql data using laravel api and passing to a list, but it is returning "NoSuchMethodError: Class 'int' has no instance method '[]'."
=========
Error
I/flutter ( 8481): NoSuchMethodError: Class 'int' has no instance method '[]'.
I/flutter ( 8481): Receiver: 1
I/flutter ( 8481): Tried calling: []("idAnunFr")
This is the error
Provider (where the ForEach is)
import 'package:bicos_app/model/anuncio_Freelancer.dart';
import 'package:bicos_app/model/freelancer.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:intl/intl.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../utils/freelancer_preferences.dart';
import '../utils/user_preferences.dart';
class AnunFreelancerProvider with ChangeNotifier {
late Freelancer freelancer;
List<AnuncioFreelancer> _anunciosMyFreelancer = [];
List<AnuncioFreelancer> getAnunciosMyFreelancer() => _anunciosMyFreelancer;
Future<dynamic> loadAnunMyFreelancer(int id) async {
try {
_anunciosMyFreelancer.clear();
var response = await Dio()
.get('http://10.0.2.2:8000/api/getAnunFreelancerByFreelancer/$id');
if (response.data['status'] == '200') {
response.data['anuncios'].forEach(
(k, e) {
AnuncioFreelancer anuncio = AnuncioFreelancer(
idAnunFr: e['idAnunFr'],
TituloAnunFr: e['TituloAnunFr'],
DescAnunFr: e['DescAnunFr'],
PrecoAnunFr: e['PrecoAnunFr'],
ImgAnunFr: e['ImgAnunFr'],
StatusAnunFr: e['StatusAnunFr'],
DataAnunFr: e['DataAnunFr'],
idFrAnunFr: e['idFrAnunFr'],
idTipoServAnunFr: e['idTipoServAnunFr'],
);
if (anuncio.StatusAnunFr == '1') {
if (_anunciosMyFreelancer
.any((element) => element.idAnunFr == anuncio.idAnunFr)) {
print('_');
} else {
_anunciosMyFreelancer.add(anuncio);
}
}
},
);
} else {
print(response.data['message'].toString());
}
notifyListeners();
} catch (e) {
print(e);
}
}
}
I tried to get all the 'anuncios' data and pass to a list
=========
Model
class AnuncioFreelancer {
final int idAnunFr;
final String TituloAnunFr;
final String DescAnunFr;
final double PrecoAnunFr;
final String ImgAnunFr;
final String StatusAnunFr;
final String DataAnunFr;
final int idFrAnunFr;
final int idTipoServAnunFr;
const AnuncioFreelancer({
required this.idAnunFr,
required this.TituloAnunFr,
required this.DescAnunFr,
required this.PrecoAnunFr,
required this.ImgAnunFr,
required this.StatusAnunFr,
required this.DataAnunFr,
required this.idFrAnunFr,
required this.idTipoServAnunFr,
});
}
========
Laravel Api Controller
this is the function that Dio.get is calling
public function getAnunFreelancerByFreelancer($idFrAnunFr)
{
if(TblAnunFreelancer::where('idFrAnunFr', $idFrAnunFr)->exists())
{
$anunfr = TblAnunFreelancer::find($idFrAnunFr);
return response()->json([
'status'=>'200',
'anuncios'=>$anunfr,
]);
} else {
return response()->json([
'status'=>'400',
'message'=>'Você não possui anúncios',
]);
}
}
==========
response.data sample:
idAnunFr: 1,
TituloAnunFr: 'Title',
DescAnunFr: 'Description',
PrecoAnunFr: 200.00,
ImgAnunFr: 'assets/images/testeImagemAnun.png',
StatusAnunFr: '1',
DataAnunFr: '2022-11-27',
idFrAnunFr: 1,
idTipoServAnunFr: 1,
it was supposed to get something like this
================
response variable debug
Your issue is in this logic:
response.data['anuncios'].forEach( ... )
Your API is only returning a single Record, not an array or multiple records, so there is no need for the forEach() at all:
if (response.data['status'] == '200') {
AnuncioFreelancer anuncio = AnuncioFreelancer(
idAnunFr: response.data['anuncios']['idAnunFr'],
TituloAnunFr: response.data['anuncios']['TituloAnunFr'],
DescAnunFr: response.data['anuncios']['DescAnunFr'],
PrecoAnunFr: response.data['anuncios']['PrecoAnunFr'],
ImgAnunFr: response.data['anuncios']['ImgAnunFr'],
StatusAnunFr: response.data['anuncios']['StatusAnunFr'],
DataAnunFr: response.data['anuncios']['DataAnunFr'],
idFrAnunFr: response.data['anuncios']['idFrAnunFr'],
idTipoServAnunFr: response.data['anuncios']['idTipoServAnunFr'],
);
}
If, for some reason you want to keep the .forEach(), then you'd need to change your API to return an array:
$anunfr = TblAnunFreelancer::where('id', $idFrAnunFr)->get();
return response()->json([
'status' => '200',
'anuncios' => $anunfr
]);
// OR
$anunfr = TblAnunFreelancer::find($idFrAnunFr);
return response()->json([
'status' => '200',
'anuncios' => [$anunfr]
]);
You can either use where('id', $idFrAnunFr)->get() to make $anunfr a Collection (array), or use ::find($idFrAnunFr) and return this single record as an array via 'anuncios' => [$anunfr]

Processing function in Yii2 Kartik GridView property

In my Kartik GridView viewfile, I am attempting to process a function for the detailRowCssClass property of an ExpandRowColumn. Regardless of setup, (such as applying an empty function or returning direct strings), the result is always the same and an object is returned.
'detailRowCssClass' => function($data){
if($data->status == 0)
{
return GridView::TYPE_INFO;
}
elseif($data->status == 1)
{
return GridView::TYPE_WARNING;
}
elseif($data->status == 2)
{
return GridView::TYPE_SUCCESS;
}
},
returns a class of [object Object]
Does anyone know a workaround, or what I am fundamentally missing in that this does not return a string? Thanks!
The problem is, that detailRowCssClass of the class kartik\grid\ExpandRowColumn is a simple string and not a closure. The appropriate parts from the source file vendor/kartik-v/yii2-grid/src/ExpandRowColumn.php:
class ExpandRowColumn extends DataColumn
{
...
/**
* #var string the CSS class for the detail content table row.
*/
public $detailRowCssClass;
...
/**
* #inheritdoc
* #throws InvalidConfigException
*/
public function init()
{
if (!isset($this->detailRowCssClass)) {
$this->detailRowCssClass = $this->grid->getCssClass(GridView::BS_TABLE_INFO);
}
...
$clientOptions = Json::encode(
[
'gridId' => $this->grid->options['id'],
'hiddenFromExport' => $this->hiddenFromExport,
'detailUrl' => empty($this->detailUrl) ? '' : $this->detailUrl,
'onDetailLoaded' => $onDetailLoaded,
'expandIcon' => $this->expandIcon,
'collapseIcon' => $this->collapseIcon,
'expandTitle' => $this->expandTitle,
'collapseTitle' => $this->collapseTitle,
'expandAllTitle' => $this->expandAllTitle,
'collapseAllTitle' => $this->collapseAllTitle,
'rowCssClass' => $this->detailRowCssClass,
'animationDuration' => $this->detailAnimationDuration,
'expandOneOnly' => $this->expandOneOnly,
'enableRowClick' => $this->enableRowClick,
'enableCache' => $this->enableCache,
'rowClickExcludedTags' => array_map('strtoupper', $this->rowClickExcludedTags),
'collapseAll' => false,
'expandAll' => false,
'extraData' => $this->extraData,
]
);
...
}

Creating actionView in yii2-dynamic form

I am working on yii2. I have created a dynamic form using wbraganca
/
yii2-dynamicform. Now I want to implement the view. In the given extension there is no procedure that has implemented a view. It just shows the action method of view. I have tried to implement but couldn't able to do it completely.
Controller Code
/**
* Finds the MdcTariffSlabs model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return MdcTariffSlabs|\yii\db\ActiveQuery
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModelSlabs($id)
{
if (($model = MdcTariffSlabs::find()->where(['t_id'=>$id])) !== null) {
return $model;
}
throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
}
public function actionView($id)
{
$model = $this->findModel($id);
$modelTarrifSlabs = $this->findModelSlabs($model->id);
return $this->render('view', [
'model' => $model,
'modelTarrifSlabs' => $modelTarrifSlabs,
]);
}
View
/* #var $this yii\web\View */
/* #var $model common\models\MdcTariff */
/* #var $modelTarrifSlabs \common\models\MdcTariffSlabs */
.
.
.
.
.
.
.
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'id',
't_name',
'created_by',
'created_at',
],
]) ?>
<?= DetailView::widget([
'model' => $modelTarrifSlabs,
'attributes' => [
'id',
't_name',
'created_by',
'created_at',
],
]) ?>
After creating I am rendering my view and getting an error
Getting unknown property: yii\db\ActiveQuery::id
var_dump($modelTarrifSlabs);
exit();
The above code gives me
object(yii\db\ActiveQuery)#131 (33) { ["sql"]=> NULL ["on"]=> NULL ["joinWith"]=> NULL ["select"]=> NULL ["selectOption"]=> NULL ["distinct"]=> NULL ["from"]=> NULL ["groupBy"]=> NULL ["join"]=> NULL ["having"]=> NULL ["union"]=> NULL ["withQueries"]=> NULL ["params"]=> array(0) { } ["queryCacheDuration"]=> NULL ["queryCacheDependency"]=> NULL ["_events":"yii\base\Component":private]=> array(0) { } ["_eventWildcards":"yii\base\Component":private]=> array(0) { } ["_behaviors":"yii\base\Component":private]=> array(0) { } ["where"]=> array(1) { ["t_id"]=> int(1) } ["limit"]=> NULL ["offset"]=> NULL ["orderBy"]=> NULL ["indexBy"]=> NULL ["emulateExecution"]=> bool(false) ["modelClass"]=> string(28) "common\models\MdcTariffSlabs" ["with"]=> NULL ["asArray"]=> NULL ["multiple"]=> NULL ["primaryModel"]=> NULL ["link"]=> NULL ["via"]=> NULL ["inverseOf"]=> NULL ["viaMap":"yii\db\ActiveQuery":private]=> NULL }
I think your error is because you get an Active Query instead of Model. And that what the error says:
Getting unknown property: yii\db\ActiveQuery::id
Try this:
Change this:
protected function findModelSlabs($id)
{
if (($model = MdcTariffSlabs::find()->where(['t_id'=>$id])) !== null) { //<---- here i guess you have error
return $model;
}
throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
}
To this:
protected function findModelSlabs($id)
{
if (($model = MdcTariffSlabs::find()->where(['t_id'=>$id])->one()) !== null) {
return $model;
}
throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
}

i need to get data from json but

i have an API that return data type of _HttpClientResponse cause i am using httpClient, i decode the result to string using the below
var reply = await memoryResponse.transform(utf8.decoder).join();
when i print the result
I/flutter (23708): String
I/flutter (23708): {"results":
[{"IPAddress":"192.1.1.1","Description":"Windows 2016 Server"},
{"IPAddress":"192.1.1.1","Description":"Windows 2016 Server"},{"IPAddress":"192.1.1.1","Description":"Windows 2016 Server"}]}
then decode it with json.decod
var memJasonData = json.decode(reply);
when i print the runType
_InternalLinkedHashMap<String, dynamic>
{results:[{IPAddress": 192.1.1.1, Description: Windows 2016 Server},
{IPAddress: 192.1.1.1", Description : Windows 2016 Server },{ IPAddress :
192.1.1.1", Description : Windows 2016 Server }]}
i created a class to to be used here an i tried
List<Results> _getMemoryData1 = memJasonData.map((json) =>
Results.fromJson(json)).toList();
setState(() {
print(_getMemoryData1);
getMemoryData = _getMemoryData1;
print(getMemoryData);
also i tried to for lop after converting the map to list
var memToListData = memJasonData['results'] as List; '''
but nothing working with me
i appreciate your help
the function
''' var getMemoryData = const [];
Future _getMemoryData() async {
var url ='https://10.1.1.1/v3/Json/Query?query';
HttpClient client = new HttpClient();
client.addCredentials(Uri.parse(url), '10.1.1.1',
HttpClientBasicCredentials('user', 'pass'));
client.badCertificateCallback =
((X509Certificate cert, String host, int port) => true);
HttpClientRequest memoryRequest = await client.getUrl(Uri.parse(
'$url=SELECT+TOP+15+IPAddress,+Description,+DNS,+SysName,+Vendor,+Status,+Last Boot,+PercentMemoryUsed,+PercentMemoryAvailable,+MachineType, +TotalMemory+FROM+Orion.Nodes+ORDER+By+PercentMemoryUsed+DESC'));
memoryRequest.headers.set('content-type', 'application/json',);
HttpClientResponse memoryResponse = await memoryRequest.close();
var reply = await memoryResponse.transform(utf8.decoder).join();
var memJasonData = json.decode(reply);
// var memToListData = memJasonData['results'] as List;
List<Results> _getMemoryData1 = memJasonData.map((json) =>
Results.fromJson(json)).toList();
setState(() {
print(_getMemoryData1);
getMemoryData = _getMemoryData1;
print(getMemoryData);
});
// for (var v in memToListData){
// Results memResults = Results(v['iPAddress'], v['description'], v['dNS'], v['sysName'], v['vendor'], v['status'], v['lastBoot'], v['percentMemoryUsed'], v['percentMemoryAvailable'], v['machineType']);
// getMemoryData.add(memResults);
// }
// print(getMemoryData.length);
// print(getMemoryData.runtimeType);
// return getMemoryData;
} '''
class below
below is the class
class Results {
String iPAddress;
String description;
String dNS;
String sysName;
String vendor;
int status;
String lastBoot;
int percentMemoryUsed;
int percentMemoryAvailable;
String machineType;
Results(
this.iPAddress,
this.description,
this.dNS,
this.sysName,
this.vendor,
this.status,
this.lastBoot,
this.percentMemoryUsed,
this.percentMemoryAvailable,
this.machineType,
);
Results.fromJson(Map<String, dynamic> json) :
iPAddress = json['IPAddress'],
description = json['Description'],
dNS = json['DNS'],
sysName = json['SysName'],
vendor = json['Vendor'],
status = json['Status'],
lastBoot = json['LastBoot'],
percentMemoryUsed = json['PercentMemoryUsed'],
percentMemoryAvailable = json['PercentMemoryAvailable'],
machineType = json['MachineType'];
}
Error
type '(dynamic) => Results' is not a subtype of type '(String, dynamic) =>
MapEntry' of 'transform'
you can copy paste and run full code below
If your json look like this
{"results": [
{"IPAddress":"192.1.1.1",
"Description":"Windows 2016 Server",
"DNS" : "",
"SysName" :"",
"Vendor":"",
"Status":12,
"LastBoot":"",
"PercentMemoryUsed":123,
"PercentMemoryAvailable": 456,
"MachineType":""
}, {"IPAddress":"192.1.1.1","Description":"Windows 2016 Server"},{"IPAddress":"192.1.1.1",
"Description":"Windows 2016 Server"}]}
code snippet for parse and print
Payload payload = payloadFromJson(jsonString);
print('${payload.results[0].ipAddress}');
related class
// To parse this JSON data, do
//
// final payload = payloadFromJson(jsonString);
import 'dart:convert';
Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));
String payloadToJson(Payload data) => json.encode(data.toJson());
class Payload {
List<Result> results;
Payload({
this.results,
});
factory Payload.fromJson(Map<String, dynamic> json) => Payload(
results: List<Result>.from(json["results"].map((x) => Result.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"results": List<dynamic>.from(results.map((x) => x.toJson())),
};
}
class Result {
String ipAddress;
String description;
String dns;
String sysName;
String vendor;
int status;
String lastBoot;
int percentMemoryUsed;
int percentMemoryAvailable;
String machineType;
Result({
this.ipAddress,
this.description,
this.dns,
this.sysName,
this.vendor,
this.status,
this.lastBoot,
this.percentMemoryUsed,
this.percentMemoryAvailable,
this.machineType,
});
factory Result.fromJson(Map<String, dynamic> json) => Result(
ipAddress: json["IPAddress"],
description: json["Description"],
dns: json["DNS"] == null ? null : json["DNS"],
sysName: json["SysName"] == null ? null : json["SysName"],
vendor: json["Vendor"] == null ? null : json["Vendor"],
status: json["Status"] == null ? null : json["Status"],
lastBoot: json["LastBoot"] == null ? null : json["LastBoot"],
percentMemoryUsed: json["PercentMemoryUsed"] == null ? null : json["PercentMemoryUsed"],
percentMemoryAvailable: json["PercentMemoryAvailable"] == null ? null : json["PercentMemoryAvailable"],
machineType: json["MachineType"] == null ? null : json["MachineType"],
);
Map<String, dynamic> toJson() => {
"IPAddress": ipAddress,
"Description": description,
"DNS": dns == null ? null : dns,
"SysName": sysName == null ? null : sysName,
"Vendor": vendor == null ? null : vendor,
"Status": status == null ? null : status,
"LastBoot": lastBoot == null ? null : lastBoot,
"PercentMemoryUsed": percentMemoryUsed == null ? null : percentMemoryUsed,
"PercentMemoryAvailable": percentMemoryAvailable == null ? null : percentMemoryAvailable,
"MachineType": machineType == null ? null : machineType,
};
}
full code
import 'package:flutter/material.dart';
// To parse this JSON data, do
//
// final payload = payloadFromJson(jsonString);
import 'dart:convert';
Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));
String payloadToJson(Payload data) => json.encode(data.toJson());
class Payload {
List<Result> results;
Payload({
this.results,
});
factory Payload.fromJson(Map<String, dynamic> json) => Payload(
results:
List<Result>.from(json["results"].map((x) => Result.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"results": List<dynamic>.from(results.map((x) => x.toJson())),
};
}
class Result {
String ipAddress;
String description;
String dns;
String sysName;
String vendor;
int status;
String lastBoot;
int percentMemoryUsed;
int percentMemoryAvailable;
String machineType;
Result({
this.ipAddress,
this.description,
this.dns,
this.sysName,
this.vendor,
this.status,
this.lastBoot,
this.percentMemoryUsed,
this.percentMemoryAvailable,
this.machineType,
});
factory Result.fromJson(Map<String, dynamic> json) => Result(
ipAddress: json["IPAddress"],
description: json["Description"],
dns: json["DNS"] == null ? null : json["DNS"],
sysName: json["SysName"] == null ? null : json["SysName"],
vendor: json["Vendor"] == null ? null : json["Vendor"],
status: json["Status"] == null ? null : json["Status"],
lastBoot: json["LastBoot"] == null ? null : json["LastBoot"],
percentMemoryUsed: json["PercentMemoryUsed"] == null
? null
: json["PercentMemoryUsed"],
percentMemoryAvailable: json["PercentMemoryAvailable"] == null
? null
: json["PercentMemoryAvailable"],
machineType: json["MachineType"] == null ? null : json["MachineType"],
);
Map<String, dynamic> toJson() => {
"IPAddress": ipAddress,
"Description": description,
"DNS": dns == null ? null : dns,
"SysName": sysName == null ? null : sysName,
"Vendor": vendor == null ? null : vendor,
"Status": status == null ? null : status,
"LastBoot": lastBoot == null ? null : lastBoot,
"PercentMemoryUsed":
percentMemoryUsed == null ? null : percentMemoryUsed,
"PercentMemoryAvailable":
percentMemoryAvailable == null ? null : percentMemoryAvailable,
"MachineType": machineType == null ? null : machineType,
};
}
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
String jsonString = '''
{"results": [
{"IPAddress":"192.1.1.1",
"Description":"Windows 2016 Server",
"DNS" : "",
"SysName" :"",
"Vendor":"",
"Status":12,
"LastBoot":"",
"PercentMemoryUsed":123,
"PercentMemoryAvailable": 456,
"MachineType":""
}, {"IPAddress":"192.1.1.2","Description":"Windows 2016 Server"},{"IPAddress":"192.1.1.3",
"Description":"Windows 2016 Server"}]}
''';
void _incrementCounter() {
Payload payload = payloadFromJson(jsonString);
print('${payload.results[0].ipAddress}');
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
#override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
Output
I/flutter ( 9422): 192.1.1.1

Node-RED function and multiple outputs

at the moment I've a little problem with one function. I'll create a function as switch. But I can't see that I route the msg block to the right output.
payloadJSON = JSON.parse(msg.payload, (key, value)=> {
if(key == "changeType") {
if (value === "create" ) {
node.error('In: ' + value);
return [ msg, null, null, null ];
}else if(value === "update" ) {
node.error('In: ' + value);
return [ null, msg, null, null ];
}else if(value === "delete" ) {
node.error('In: ' + value);
return [ null, null, msg, null ];
}else{
node.error('In: ' + "otherwise");
return [ null, null, null, msg ];
}
}
});
Yes I configure 4 Outputs in the function
I can see the node.error message in the log, but I can't see any Output from the attached Debug Output .
Your return statements are inside the function you've passed to the JSON.parse call - so they are not returning anything to Node-RED.
You need to use node.send([msg,null ... ]); in place of those return statements.