Range Error (Index) Flutter GETX : invalid value - flutter

Here I have an error when I fetch data, I take a reference from youtube then I apply and use data from local but when I run it I get an error as I described. here is my source code
Controller.dart
class ProdukKonvensionalController extends GetxController {
var konvenList = <ProdukKonvenModel>[].obs;
var isLoading = true.obs;
#override
void onInit() {
super.onInit();
fetchKonven();
}
Future<void> fetchKonven() async {
final response =
await http.get(Uri.parse('http://192.168.100.207:8080/konven'));
if (response.statusCode == 200) {
ProdukKonvenModel _produkkonvenModel =
ProdukKonvenModel.fromJson(jsonDecode(response.body));
konvenList.add(ProdukKonvenModel(
kategoriNama: _produkkonvenModel.kategoriNama,
kategoriId: _produkkonvenModel.kategoriId,
kontenId: _produkkonvenModel.kontenId,
kontenMenu: _produkkonvenModel.kontenMenu,
kontenParent: _produkkonvenModel.kontenParent,
kontenUrl: _produkkonvenModel.kontenUrl,
));
isLoading.value = true;
} else {
Get.snackbar("Error Loading Data",
'Server Responded: ${response.statusCode}:${response.reasonPhrase.toString()}');
}
}
}
PageView.dart
class ProdukKonvensionalPage extends StatelessWidget {
const ProdukKonvensionalPage({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
final _controller = Get.find<ProdukKonvensionalController>();
return Scaffold(
body: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('${_controller.konvenList[0].kategoriNama}'),
],
)),
);
}
}
and the following shows an error

try this
var konvenList = <ProdukKonvenModel>[].obs;
var isLoading = true.obs;
#override
void onInit() {
super.onInit();
fetchKonven();
}
Future<void> fetchKonven() async {
final response = await http.get(Uri.parse('http://192.168.100.207:8080/konven'));
if (response.statusCode == 200) {
ProdukKonvenModel _produkkonvenModel =
ProdukKonvenModel.fromJson(jsonDecode(response.body));
_produkkonvenModel.forEach((element) => konvenList.add(element));
isLoading.value = true;
} else {
Get.snackbar("Error Loading Data",
'Server Responded:
${response.statusCode}:${response.reasonPhrase.toString()}');
}
}
}

Related

Not able to use Binance_spot Package in Flutter Dart

I am trying for the past two days to Get user data from binance Api with the Binance test net key using package https://pub.dev/packages/binance_spot/example
I tried every way possible I learned as I am a beginner I am not able to get the user data from the user account
I also changed the links that work for the testnet finance API version
here is the example code snippet
import 'dart:async';
import 'package:binance_spot/binance_spot.dart';
import 'package:flutter/material.dart' hide Interval;
class BinanceScreen extends StatefulWidget {
const BinanceScreen({Key? key}) : super(key: key);
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<BinanceScreen> {
BinanceSpot binanceSpot = BinanceSpot(
key: "3HKUUgtwu8WFWh4q31C5bh1veQqMEkEbF07hpMrq8xnwYsWDnj0ZWgYQkvC3gnE0",
secret: "KWwvWOi4nu8s0Qsi87iJ523cfp9Jcl8mFwt2hZHptMyahhGsxnmvdURIxVa9zA74",
);
double lastClosePrice = 0;
String tradablePairs = "";
String lastEventData = "";
WsAccountUpdate? balance;
late StreamSubscription<dynamic> klineStreamSub;
late StreamSubscription<dynamic> userdataStreamSub;
#override
void initState() {
startKlineStream();
startUserdataStream();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Binance API tester"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text("Current BTC price : $lastEventData"),
// Text("Last userdataStream event : ${balance}"),
TextButton(
onPressed: getTradablePairs,
child: const Text("GET PAIRS"),
),
Expanded(
flex: 1,
child: SelectableText(
tradablePairs,
maxLines: 200,
minLines: 1,
),
),
],
),
),
);
}
void startKlineStream() {
var stream = binanceSpot.klineStream(
symbol: "BTCUSDT",
interval: Interval.INTERVAL_5m,
);
klineStreamSub = stream.listen(handleNewKline);
}
void handleNewKline(WsKlineEvent event) {
setState(() {
lastClosePrice = event.kline.close;
});
}
void startUserdataStream() async {
var response = await binanceSpot.createListenKey();
if (response.isRight) {
var stream = binanceSpot.userDataStream(listenKey: response.right);
userdataStreamSub = stream.listen(handleUserdataEvent);
} else {
lastEventData = response.left;
}
}
void handleUserdataEvent(dynamic event) {
if (event is WsAccountUpdate) {
lastEventData =
"Account update event : ${event.balances.length} balances updated";
} else if (event is WsBalanceUpdate) {
lastEventData = "Balance update event : ${event.asset} balance updated";
} else if (event is WsExecutionReport) {
lastEventData =
"Execution report event : status is ${event.orderStatus.toStr()}";
} else if (event is WsListOrderStatus) {
lastEventData =
"ListOrder update event : status is ${event.listOrderStatus}";
} else {
lastEventData = "Unknown event type : ${event.toString()}";
}
}
void getTradablePairs() async {
var response = await binanceSpot.exchangeInfo();
if (response.isLeft) {
tradablePairs = response.left;
} else {
var listSymbol = response.right.symbols.map((e) => e.symbol).toList();
tradablePairs = "";
for (var s in listSymbol) {
tradablePairs += "$s ";
}
}
}
#override
void dispose() {
klineStreamSub.cancel();
userdataStreamSub.cancel();
super.dispose();
}
}
and here is the class code snippet which I want to acess
class WsOcoOrder {
String symbol;
int orderId;
String clientOrderId;
WsOcoOrder.fromMap(Map m)
: symbol = m['s'],
orderId = m['i'],
clientOrderId = m['c'];
}
What is the Possible way to access this class and its data in the above-given code snippet
Please refer me to the solution or a Link from where I can learn and implement by myself

Why is the flutter setState not updating the list?

I have two api's from which I get data, I wanna check if any of the desired field match with each other data coming but it don't seem to work.
I have two api's from which I get data, I wanna check if any of the desired field match with each other data coming but it don't seem to work.
I have two api's from which I get data, I wanna check if any of the desired field match with each other data coming but it don't seem to work.
class Home extends StatefulWidget {
const Home({ Key? key }) : super(key: key);
#override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
List compaints = [];
List found = [];
List match = [];
var u_imei;
var d_imei;
Future fetch() async {
http.Response response_one;
http.Response response_two;
response_one = await http.get(Uri.parse("https://script.google.com/macros/s/AKfycbxi9kN6NWvoFjkQZE1OVJDPpWmQeYk0V5hNfRKqXS19wjz86SYq_FoQ51fjNQY22bN4/exec"));
response_two = await http.get(Uri.parse("https://script.google.com/macros/s/AKfycbx20kfm1g4Hno9DzO1uccmLgmuIQBkXQcA9tnhcup873TsEMEy9ejszCluhf4FzW-YJqQ/exec"));
if(response_one == 200 && response_two == 200){
if(mounted){
setState(() {
compaints = jsonDecode(response_one.body);
found = jsonDecode(response_two.body);
u_imei = compaints[2];
d_imei = found[1];
if(d_imei == u_imei) {
if(mounted){
print("working");
setState(() {
match.add(d_imei);
});
}
}
});
}
}
}
#override
Widget build(BuildContext context) {
// fetchu();
// fetchd();
// check();
fetch();
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Text(compaints.length.toString()),
SizedBox(height: 20,),
Text(found.length.toString()),
],
),
);
}
}
There are several issues:
fetch is called in build, which causes rebuild loop. First step to move it to initState.
Response is compared to 200 (response_one == 200). There is property statusCode.
Parsing imei's is not correct. Responses:
[{time: 2022-07-03T16:07:15.491Z, name: Asif, imei: 1234, number: 9014580667}]
[{time: 2022-07-05T08:12:31.029Z, imei: 1234}]
So should be something like this:
u_imei = compaints[0]['imei'];
d_imei = found[0]['imei'];
Calling the fetch method inside the build will loop as the fetch method calls the setState(). Use initState() to call on the load or on refresh indicator while the user pulls to refresh or any other method.
class Home extends StatefulWidget {
const Home({ Key? key }) : super(key: key);
#override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
List compaints = [];
List found = [];
List match = [];
var u_imei;
var d_imei;
#override
void initState() {
super.initState();
fetch();
}
#override
void dispose() {
super.dispose();
}
Future fetch() async {
http.Response response_one;
http.Response response_two;
response_one = await http.get(Uri.parse("https://script.google.com/macros/s/AKfycbxi9kN6NWvoFjkQZE1OVJDPpWmQeYk0V5hNfRKqXS19wjz86SYq_FoQ51fjNQY22bN4/exec"));
response_two = await http.get(Uri.parse("https://script.google.com/macros/s/AKfycbxEDXZAmieRWk-8kOX-07ta8Q4TIa9Lf_NAiArEWhaU4jXO8d_DM9Jwuc0DRIwmUpPh/exec"));
if(response_one.statusCode == 200 && response_two.statusCode == 200){
if(mounted){
setState(() {
compaints = jsonDecode(response_one.body);
found = jsonDecode(response_two.body);
u_imei = compaints[2];
d_imei = found[1];
if(d_imei == u_imei) {
if(mounted){
print("working");
setState(() {
match.add(d_imei);
});
}
}
});
}
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Text(compaints.length.toString()),
SizedBox(height: 20,),
Text(found.length.toString()),
],
),
);
}
}

SharedPreference lost data on app Killed/Close Flutter

I am saving modal object converted into String to SharedPreference and Killing the app. But when I come back to app SharedPreference has lost the saved data. I am new to flutter. Please help. I want to save my data and kill the app and again retrieve while coming back.
Here is my code
class HomeScreen extends StatefulWidget {
HomeScreen({Key? key}) : super(key: key);
#override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> with WidgetsBindingObserver {
List<User> selectedUser = [];
List<User> visibleUser = [];
double screenHeight = 0.0;
static const _keyUser = 'users';
#override
initState() {
super.initState();
WidgetsBinding.instance!.addObserver(this);
getUsersFromSharedPref();
}
Future<void> getUsersFromSharedPref() async {
final pref = await SharedPreferences.getInstance();
setState((){
String savedJson = pref.getString(_keyUser) ?? '';
if(savedJson.length > 0) {
selectedUser = UserApi.getUsersFromSharedPref(savedJson);
}
});
}
Future<void> saveInSharedPref() async {
final pref = await SharedPreferences.getInstance();
String encodedData = UserApi.getStringFromobject(selectedUser);
await pref.setString(_keyUser , encodedData);
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder<List<User>>(
future: UserApi.getUserLocally(context),
builder: (context, snapshot) {
final allUsers = (selectedUser.isNotEmpty) ? selectedUser : snapshot.data;
visibleUser = (selectedUser.isNotEmpty)?(selectedUser.where((aUser) => (aUser.isDefaultUser)).toList()) : (allUser!.where((aUser) => (aUser.isDefaultUser)).toList());
.
.
.
})
);
}
#override
void dispose() {
super.dispose();
}
#override
void didChangeAppLifecycleState(AppLifecycleState state) {
super.didChangeAppLifecycleState(state);
final isBackground = state == AppLifecycleState.paused;
if (isBackground || (state == AppLifecycleState.inactive ||
state == AppLifecycleState.detached)) {
saveInSharedPref();
}
if(state == AppLifecycleState.resumed){
getUserFromSharedPref();
}
}
}
class UserApi {
static Future<List<User>> getUserLocally(BuildContext context) async {
final assetBundle = DefaultAssetBundle.of(context);
final data = await assetBundle.loadString('assets/data/Users.json');
final body = json.decode(data.toString()).cast<Map<String, dynamic>>();
return body.map<User>((json) => new User.fromJson(json)).toList();
}
static List<User> getUserFromSharedPref(String jsonString){
final body = json.decode(jsonString).cast<Map<String, dynamic>>();
return body.map<User>((json) => new User.fromJson(json)).toList();
}
}
I am not getting saved data after killing the app from SharedPreferences.

Flutter unspecific Error while triggering an API request with Switch on/off events

I want to control raspberry pins with a flutter app. Therefore I build an API with Python Flask. In this case, I want to turn on and off a light with a Switch in Flutter. When the switch is toggled, I want a request to be triggered telling the API to turn the light on or off.
Switch:
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
bool lampStatus = false;
void toggleSwitch(bool value) async{
if (lampStatus == false) {
bool lampenstatus = await lampon();
setState(() {
lampStatus = lampenstatus;
});
print('Lights on');
} else {
setState(() {
lampStatus = false;
});
print('Lights off');
// await lampoff();
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
children: [
Container(child: Text('Lights are ${lampStatus==true? 'on': 'off'}')),
Switch(
value: lampStatus,
onChanged: toggleSwitch,
activeTrackColor: Colors.lightGreenAccent,
activeColor: Colors.green,
),
],
),
),
);
}
}
Future<bool> lampon() async {
final response =
await http.post(Uri.http(url, '/lampon'));
if (response.statusCode == 200) {
final bool lampenstatus = json.decode(response.body);
print(lampenstatus);
return lampenstatus;
} else {
return false;
}
}
Future lampoff() async {
final response =
await http.post(Uri.http(url, '/lampoff'));
if (response.statusCode == 200) {
return true;
} else {
return null;
}
}
With this switch and both functions (I've tried both with lampon) I can send my request to the API and the light goes on, but then the following error occurs and my Flutter app crashes:
unawaited(xhr.onError.first.then((_) {
// Unfortunately, the underlying XMLHttpRequest API doesn't expose any
// specific information about the error itself.
completer.completeError(
ClientException('XMLHttpRequest error.', request.url),
StackTrace.current);
}));
Does somebody have a solution for it?
Here is my PythonCode:
from flask import Flask, jsonify, request
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(23, GPIO.OUT)
app = Flask(__name__)
#app.route('/lampon', methods=['GET','POST'])
def lamp_on():
GPIO.output(23, GPIO.HIGH)
return jsonify({'Lampenstatus':True})
#app.route('/lampoff', methods=['GET','POST'])
def lamp_off():
GPIO.output(23, GPIO.LOW)
return jsonify({'Lampenstatus':False})
if __name__ == '__main__':
app.run(host='0.0.0.0')

Flutter, problem using InitState method and problem using setState

I have tried many things to get to call an API and get data, this has been satisfactory but I have not been able to do it from the correct method, when I do it from build it works perfectly but it is not the right place, when I try to do it in initState it simply does not it works, it doesn't even execute the print ();
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
class Post {
final List<dynamic> data;
Post({this.data});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
data: json['response'],
);
}
}
class LoaderPublicity extends StatefulWidget {
#override
State<StatefulWidget> createState() {
// TODO: implement createState
return _LoaderPublicity();
}
}
class _LoaderPublicity extends State<LoaderPublicity> {
List allPublicity;
#override
void initState() {
super.initState();
getPublicity().then((value) {
print(allPublicity);
});
print(allPublicity);
}
//Obtener todas las publicidades desde el api
Future<void> getPublicity() async {
var response = await http.post(
'http://contablenift.co:3008/consult/getGeneralPublicity',
body: {'actividad': "Turistico", 'location': "No"});
print('????????2');
if (response.statusCode == 200) {
setState(() {
allPublicity = Post.fromJson(json.decode(response.body)).data;
});
}
}
#override
Widget build(BuildContext context) {
getPublicity();
// TODO: implement build
return Container(
child: Column(
children: <Widget>[Text('Aqui va la publicidad')],
),
);
}
}
**
Solved the problem, after going to the entire development team we realized that my phone did not have internet, happy day**
The code below should work, I've added a callback in the initState method.
class LoaderPublicity extends StatefulWidget {
#override
State<StatefulWidget> createState() {
// TODO: implement createState
return _LoaderPublicity();
}
}
class _LoaderPublicity extends State<LoaderPublicity> {
List allPublicity;
#override
void initState() {
super.initState();
getPublicity().then((value) {
print(allPublicity);
print(value);
});
}
//Obtener todas las publicidades desde el api
Future<void> getPublicity() async {
var response = await http.post(
'http://contablenift.co:3008/consult/getGeneralPublicity',
body: {'actividad': "Turistico", 'location': "No"})
print('????????2');
if (response.statusCode == 200) {
setState(() {
allPublicity = Post.fromJson(json.decode(response.body)).data;
});
}
}
#override
Widget build(BuildContext context) {
return Container(
child: Column(
children: <Widget>[Text('Aqui va la publicidad')],
),
);
}
}