bool value always returns true flutter - flutter

I am having trouble with the bool value. My bool value returns true only.
I have five buttons which set the state for the bool and time for fasting.
ElevatedButton(
onPressed: () async {
final SharedPreferences prefs = await _prefs;
playLocalAsset(0);
if((isFasting = true) && (widget.isFasting = true)) {
showError();
removeHours(fastDurs);
setState(() {
isFasting = false;
widget.isFasting = false;
});
//showAlerts();
} else {
setState(() {
isFasting = true;
widget.isFasting = true;
fastDuration = 16;
sixteen = 16;
eighteen = null;
twenty= null;
twentytwo = null;
twentyfour = null;
widget.fastDuration= 16;
endTime = startTime.add(Duration(hours: fastDuration!));
endTimeS = DateFormat('y/M/d, hh:mma').format(endTime);
_textLine = prefs
.setString('formattedDate', endTimeS)
.then((value) => (prefs
.getString('formattedDate') ??
Languages.of(context)!.setYourFastTime +'\n'+ startTimeS));
textDate = prefs.setString('eatTime', Languages.of(context)!.youWillEatAt)
.then((value) => (prefs.getString('eatTime') ?? ''));
showMessage(Languages.of(context)!.yourFastTimeIsSet);
updateHours(16);
});
}
},
child: Text('16:8', style: Constants.textTitleStyle),
style: Constants.buttonStyle),
const SizedBox(width:170),
ElevatedButton(
onPressed: () async {
final SharedPreferences prefs = await _prefs;
playLocalAsset(0);
if ((isFasting = true) && (widget.isFasting = true)) {
showError();
removeHours(fastDurs);
setState(() {
isFasting = false;
widget.isFasting = false;
});
//showAlerts();
} else {
setState(() {
isFasting = true;
widget.isFasting = true;
fastDuration = 18;
eighteen = 18;
sixteen = null;
twenty= null;
twentytwo = null;
twentyfour = null;
widget.fastDuration = 18;
endTime = startTime.add(Duration(hours: fastDuration!));
endTimeS = DateFormat('y/M/d, hh:mma').format(endTime);
_textLine = prefs
.setString('formattedDate', endTimeS)
.then((value) =>
(prefs
.getString('formattedDate') ??
Languages.of(context)!.setYourFastTime + '\n' + startTimeS));
textDate =
prefs.setString('eatTime', Languages.of(context)!.youWillEatAt)
.then((value) => (prefs.getString('eatTime') ?? ''));
showMessage(Languages.of(context)!.yourFastTimeIsSet);
updateHours(18);
});
}
showNotificationOneTime(context,
startTime.add(const Duration(hours: 14)).hour,
startTime.add(const Duration(minutes: 0)).minute);
showNotif(context,
endTime.hour, endTime.minute);},
child: Text('18:6', style: Constants.textTitleStyle),
style: Constants.buttonStyle
),
i declare my isFasting bool as nullable, then in init I check for the time, and if it is before the endTime then bool isFasting = true. As such:
#override
void initState() {
super.initState();
String startTimeS = DateFormat('y/M/d, hh:mma').format(startTime);
String endTimeS = DateFormat('y/M/d, hh:mma').format(endTime);
_textLine = _prefs.then((SharedPreferences prefs) {
String? fastEndTime = prefs.getString('formattedDate');
if ((fastEndTime != null) && (endTime
.isAfter(DateFormat('y/M/d, hh:mma').parse(fastEndTime)))) {
setState(() {
isFasting = false;
widget.isFasting = false;
});
return Languages.of(context)!.yourFastTimeFinished +"\n"+ endTimeS;
}
if (isFasting = false) {
return Languages.of(context)!.setYourFastTime +"\n"+ startTimeS;
}
if ((fastEndTime != null) && (endTime
.isBefore(DateFormat('y/M/d, hh:mma').parse(fastEndTime)))){
setState(() {
isFasting = true;
widget.isFasting = true;
});
}
return fastEndTime ??
Languages.of(context)!.setYourFastTime + "\n" + startTimeS;
});
textDate = _prefs.then((SharedPreferences prefs) {
String? stillFastingTime = prefs.getString('eatTime');
String? fastEndTime = prefs.getString('formattedDate');
if ((fastEndTime != null) && (endTime
.isBefore(DateFormat('y/M/d, hh:mma').parse(fastEndTime)))) {
setState(() {
isFasting = true;
widget.isFasting = true;
});
return Languages.of(context)!.youWillEatAt;
}
return stillFastingTime ?? '';
});
}
so, if isFasting is true then fast is cancelled and isFasting set to false. then clicking on a diff button should set state as shown in else condition. However, my isFasting is always true. it does not turn off... And it does not remove the previous hours, and it does not change the string of the text according to state. How do I make that bool value work properly? Thank you for your help!

use == instead of = when checking for equality:
if (isFasting = false) to if (isFasting == false)
and
if((isFasting = true) && (widget.isFasting = true)) to if(isFasting == true && widget.isFasting == true) also the braces here can be removed.
!= is correct here

Related

Flutter QR-code scanner rapidly scan issue, how to control the second scan?

Does anyone know how to adjust the QR code scanner speed? since the second scan is so quick,
source example is down below, you can download it add and run it in your Flutter project to test!
What are the differenceis are in the controller.scannedDataStream.listen() function. I posted down below:
Barcode? result;
var qrText = "";
bool isValid = false;
bool isExpired = false;
QRViewController? controller;
controller.scannedDataStream.listen((scanData) async {
log(scanData.code);
if (!scanData.code.contains('?key=')) {
setState(() {
qrText = "This is not a correct code";
isValid = false;
});
} else {
var key_hash = scanData.code.split('?key=');
log('hash: ' + key_hash[1]);
await decrypt(key_hash[1]).then((String result) async {
if (result == "") {
log('result: ' + result);
await controller.stopCamera();
setState(() {
qrText = result;
isValid = true;
isExpired = true;
});
}
else {
log('result: ' + result);
await controller.pauseCamera();
await controller.stopCamera();
setState(() {
qrText = result;
isValid = true;
isExpired = false;
});
}
});
}
});
https://pub.dev/packages/qr_code_scanner/example

List with sorting function stopped working since i add lazy loader. Flutter/Dart

I had this list but since i add lazy loading function,my sorting fuction stoped working.
here is some of the code and sort function is on top:
I had this list but since i add lazy loading function,my sorting fuction stoped working.
here is some of the code and sort function is on top:
I had this list but since i add lazy loading function,my sorting fuction stoped working.
here is some of the code and sort function is on top:
void showEvsePanels() async{
tempEvses.sort((a, b) {
int nameComp = a.sort_availability.compareTo(b.sort_availability);
if (nameComp == stationAvailability.available.index) {
return a.distance.compareTo(b.distance); // '-' for descending
}
return nameComp;
});
setState(() {
if (evseSearchField.isEmpty){
int i = 0;
if (tempEvses.length != 0){
evsePanels.clear();
while (i < tempEvses.length){
evsePanels.add(new EvsePanel(tempEvses[i], widget.appController, false));
i++;
}
}
}
else{
int i = 0;
if (tempEvses.length != 0){
evsePanels.clear();
while (i < tempEvses.length){
if (containsIgnoreCase(tempEvses[i].friendlyName, evseSearchField))
evsePanels.add(new EvsePanel(
tempEvses[i], widget.appController, false));
i++;
}
}
}
});
}
List<Evse> tempEvses = [];
Future fetch() async {
if (isLoading) return;
isLoading = true;
const limit = 10;
final url = Uri.parse('https://everywhere-dev.iccs.gr:18083/evse/getEvsesPaged?page=$page&pageLimit=$limit');
final response = await http.get(url);
if (response.statusCode == 200) {
final List newItems = json.decode(response.body)["results"];
setState(() {
page++;
isLoading = false;
if (newItems.length <limit) {
hasMore = false;
}
tempEvses.addAll(newItems.map<Evse>((items) {
final evseID = items['evseID'];
final friendlyName = items['friendlyName'];
final street = items['street'];
final streetNumber = items['streetNumber'];
final region = items['region'];
final lat = items['lat'] ?? 0.0;
final lng = items['lng'] ?? 0.0;
final connectorList = items['connectorList'];
final cpSerial = items['cpSerial'];
final img = items['img'];
return new Evse(evseID: evseID, friendlyName: friendlyName, street: street, streetNumber: streetNumber, region: region, lat: lat, lng: lng, connectorList: [connectorList], cpSerial: cpSerial, img: img);
}).toList());
for(int i=0 ; i<tempEvses.length; i++ ){
this.tempEvses[i].calculateDistance(widget.appController.currentLocation);
// this.tempEvses[i].calculateAvailability();
this.tempEvses[i].isEvseFavorite(widget.appController.favoritesList);
this.tempEvses[i].storePlugCounters();
}
showEvsePanels();
});
}
}

How can I get variable data into a Class with ChangeNotifier in Flutter?

I have the following class which pulls in data from a remote JSON source, if I hardcode the URL into the class (daUrl) then it works just great.
But I am planning to use a variable URL which I want to feed into this class when I call it. But declaring the variable at the top just doesn't work.
Any ideas?
class ThreadData with ChangeNotifier
{
Map<String,dynamic> _map = {};
bool _error = false;
String _errorMessage = '';
int _isLoggedIn = 0;
int tid = 1836392;
Map<String,dynamic> get map => _map;
bool get error => _error;
String get errorMessage => _errorMessage;
int get isLoggedIn => _isLoggedIn;
//var daUrl = 'https://jsonplaceholder.typicode.com/todos/';
Future<void> get fetchData async {
final response = await post(Uri.parse(daUrl));
if ((response.statusCode == 200) && (response.body.length >0))
{
try
{
debugPrint('\Thread => Make Call => Success\n');
_map = json.decode(response.body);
_error = false;
}
catch(e)
{
_error = true;
_errorMessage = e.toString();
_map = {};
_isLoggedIn = 0;
}
}
else
{
_error = true;
_errorMessage = 'Error: It could be your internet connection';
_map = {};
_isLoggedIn = 0;
}
notifyListeners(); // if good or bad we will notify the listeners either way
}
void initialValues()
{
_map = {};
_error = false;
_errorMessage = '';
_isLoggedIn = 0;
notifyListeners();
}
}
You can pass it to its constructor:
class ThreadData with ChangeNotifier {
final String url;
// Defaults to some URL if not passed as parameter
ThreadData({this.url = 'https://jsonplaceholder.typicode.com/todos/'});
Map<String,dynamic> _map = {};
bool _error = false;
String _errorMessage = '';
int _isLoggedIn = 0;
int tid = 1836392;
Map<String,dynamic> get map => _map;
bool get error => _error;
String get errorMessage => _errorMessage;
int get isLoggedIn => _isLoggedIn;
Future<void> get fetchData async {
// Access the URL field here
final response = await post(Uri.parse(this.url));
if ((response.statusCode == 200) && (response.body.length >0))
{
try
{
debugPrint('\Thread => Make Call => Success\n');
_map = json.decode(response.body);
_error = false;
}
catch(e)
{
_error = true;
_errorMessage = e.toString();
_map = {};
_isLoggedIn = 0;
}
}
else
{
_error = true;
_errorMessage = 'Error: It could be your internet connection';
_map = {};
_isLoggedIn = 0;
}
notifyListeners(); // if good or bad we will notify the listeners either way
}
void initialValues()
{
_map = {};
_error = false;
_errorMessage = '';
_isLoggedIn = 0;
notifyListeners();
}
}
Then you can call it like that:
ThreadData(); // the URL will be https://jsonplaceholder.typicode.com/todos/
ThreadData(url: 'https://example.com'); // the URL will be https://example.com

Send string values from one smartphone device to another smartphone device via Bluetooth in flutter

I want to send multiple string values from one smartphone device to another device via Bluetooth in flutter. I have seen flutter_blue and flutter_bluetooth_searial package examples also but i cant find anything that sends multiple strings values via Bluetooth. can anyone please suggest how i can be able to achieve this task?
I used flutter_bluetooth_searial in one of my projects, here is the the whole class including: sending data (multiple strings), receiving data, connect, disconnect, auto-pairing, ...etc
Hope you find this helpful.
import 'dart:async';
import 'dart:typed_data';
import 'dart:convert' show utf8;
import 'package:flutter/foundation.dart';
import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';
class BluetoothStore extends ChangeNotifier {
var _instance = FlutterBluetoothSerial.instance;
var _dataBuffer = '';
void Function(String) _onDataCallback = (String data) {};
StreamSubscription<Uint8List> _dataSubscription;
StreamSubscription<BluetoothDiscoveryResult> _scannedDevicesSubscription;
BluetoothDiscoveryResult _connectedDevice;
BluetoothConnection _connection;
var name = "...";
var address = "...";
var pinNum = "1234";
var isScanning = false;
var _isConnecting = false;
var _autoPair = false;
var scannedDevices = List<BluetoothDiscoveryResult>();
var state = BluetoothState.UNKNOWN;
BluetoothStore() {
initBluetooth();
}
bool get autoPair => _autoPair;
bool get isConnecting => _isConnecting;
bool get isConnected => _dataSubscription != null;
set autoPair(bool value) {
_autoPair = value;
if (value) {
_instance.setPairingRequestHandler((request) {
if (request.pairingVariant == PairingVariant.Pin)
return Future.value(pinNum);
return Future.value("");
});
} else {
_instance.setPairingRequestHandler(null);
}
notifyListeners();
}
void initBluetooth() async {
// Get bluetooth initial state
this.state = await _instance.state;
this.address = await _instance.address;
this.name = await _instance.name;
notifyListeners();
_instance.onStateChanged().listen((state) {
this.state = state;
_reset();
});
}
Future<bool> pairWith(BluetoothDevice device) async {
var pairedDevices = await _instance.getBondedDevices();
if (pairedDevices.length < 7) {
var result = await _instance.bondDeviceAtAddress(device.address);
if (result) {
var deviceIndex = scannedDevices.indexWhere((scannedDevice) {
return scannedDevice.device.address == device.address;
});
scannedDevices[deviceIndex] = BluetoothDiscoveryResult(
device: BluetoothDevice(
name: device.name ?? '',
address: device.address,
type: device.type,
bondState:
result ? BluetoothBondState.bonded : BluetoothBondState.none,
),
rssi: scannedDevices[deviceIndex].rssi,
);
notifyListeners();
}
return Future.value(result);
}
return Future.value(false);
}
// Notice the return value
Future<bool> unpairFrom(BluetoothDevice device) async {
var result = await _instance.removeDeviceBondWithAddress(device.address);
if (result) {
var deviceIndex = scannedDevices.indexWhere((scannedDevice) {
return scannedDevice.device.address == device.address;
});
scannedDevices[deviceIndex] = BluetoothDiscoveryResult(
device: BluetoothDevice(
name: device.name ?? '',
address: device.address,
type: device.type,
bondState:
result ? BluetoothBondState.none : BluetoothBondState.bonded,
),
rssi: scannedDevices[deviceIndex].rssi,
);
notifyListeners();
}
return Future.value(result);
}
Future<bool> enable() => _instance.requestEnable();
Future<bool> disable() => _instance.requestDisable();
Future<void> openSettings() => _instance.openSettings();
Future<bool> connectTo(BluetoothDevice device) async {
_isConnecting = true;
if (isConnected) await _connection.close();
notifyListeners();
try {
var connection = await BluetoothConnection.toAddress(device.address);
_isConnecting = false;
_connection = connection;
_dataSubscription = connection.input.listen(_onDataReceived);
_dataSubscription.onDone(_onDisconnect);
var deviceIndex = scannedDevices.indexWhere((scannedDevice) {
return scannedDevice.device.address == device.address;
});
_connectedDevice = scannedDevices[deviceIndex] = BluetoothDiscoveryResult(
device: BluetoothDevice(
name: device.name ?? '',
address: device.address,
bondState: device.bondState,
type: device.type,
isConnected: true,
),
rssi: scannedDevices[deviceIndex].rssi,
);
notifyListeners();
return Future.value(true);
} catch (_) {
_isConnecting = false;
_dataSubscription = null;
_connection = null;
notifyListeners();
return Future.value(false);
}
}
Future<List<BluetoothDevice>> pairedDevices() async {
var result = await _instance.getBondedDevices();
return Future.value(result);
}
void disConnect() async {
if (isConnected) {
this.unpairFrom(_connectedDevice.device);
_connection.dispose();
}
}
void startScanning() {
isScanning = true;
scannedDevices.clear();
notifyListeners();
if (isConnected) scannedDevices.add(_connectedDevice);
_scannedDevicesSubscription = _instance.startDiscovery().listen((device) {
scannedDevices.add(device);
});
_scannedDevicesSubscription.onDone(() async {
isScanning = false;
notifyListeners();
});
}
void _onDataReceived(Uint8List data) {
// Allocate buffer for parsed data
var backspacesCounter = 0;
data.forEach((byte) {
if (byte == 8 || byte == 127) backspacesCounter++;
});
var buffer = Uint8List(data.length - backspacesCounter);
var bufferIndex = buffer.length;
// Apply backspace control character
backspacesCounter = 0;
for (int i = data.length - 1; i >= 0; i--) {
if (data[i] == 8 || data[i] == 127) {
backspacesCounter++;
} else {
if (backspacesCounter > 0) {
backspacesCounter--;
} else {
buffer[--bufferIndex] = data[i];
}
}
}
// Create message if there is new line character
var dataString = String.fromCharCodes(buffer);
var index = buffer.indexOf(13);
if (~index != 0) {
// \r\n
var data = backspacesCounter > 0
? _dataBuffer.substring(0, _dataBuffer.length - backspacesCounter)
: _dataBuffer = _dataBuffer + dataString.substring(0, index);
_onDataCallback(data);
_dataBuffer = dataString.substring(index);
} else {
_dataBuffer = (backspacesCounter > 0
? _dataBuffer.substring(0, _dataBuffer.length - backspacesCounter)
: _dataBuffer + dataString);
}
}
void _onDisconnect() {
// reset
if (this.state == BluetoothState.STATE_ON) {
var deviceIndex = scannedDevices.indexWhere((scannedDevice) {
return scannedDevice.device.address == _connectedDevice.device.address;
});
scannedDevices[deviceIndex] = BluetoothDiscoveryResult(
device: BluetoothDevice(
name: _connectedDevice.device.name ?? '',
address: _connectedDevice.device.address,
type: _connectedDevice.device.type,
bondState: _connectedDevice.device.bondState,
),
rssi: _connectedDevice.rssi,
);
}
_reset();
}
void _reset() {
_dataBuffer = '';
_isConnecting = false;
_dataSubscription = null;
_scannedDevicesSubscription = null;
_connectedDevice = null;
_connection = null;
if (this.state != BluetoothState.STATE_ON) {
scannedDevices.clear();
}
notifyListeners();
}
void onDataReceived(void Function(String) callback) {
_onDataCallback = callback;
}
bool sendData(String data) {
try {
data = data.trim();
if (data.length > 0 && isConnected) {
_connection.output.add(utf8.encode(data + "\r\n"));
return true;
}
} catch (e) {
return false;
}
return false;
}
void dispose() {
_instance.setPairingRequestHandler(null);
if (isConnected) _dataSubscription.cancel();
_scannedDevicesSubscription?.cancel();
super.dispose();
}
}
You can consume this class using ChangeNotifierProvider
ChangeNotifierProvider<BluetoothStore>.value(value: BluetoothStore())

How to search and display results from an array field in cloud firestore in flutter?

The logic behind my search function is, The searchKey field stored a value's capitalized first letter. Basically, I will store any value with it's searchKey; which is the values First letter capitalized and stored in a new field called SearchKey.
I wanted to display searched results from an array in Cloud Firestore. The code I have written for a string field works perfectly. Here it is:
void initiateSearch(String val) async {
if (val.length == 0) {
setState(() {
queryResultSet = [];
tempSearchStore = [];
queryResultGigSet = [];
tempSearchGigStore = [];
queryResultTagSet = [];
tempSearchTagStore = [];
});
}
String capitalizedValue =
val.substring(0, 1).toUpperCase() + val.substring(1);
if (queryResultGigSet.length == 0 && val.length == 1) {
// SearchService().searchByName(val);
await databaseReference
.collection('posts')
.where('searchKey', isEqualTo: val.substring(0, 1).toUpperCase())
.getDocuments()
.then((QuerySnapshot docs) {
for (int i = 0; i < docs.documents.length; ++i) {
setState(() {
isLoading = false;
queryResultGigSet.add(docs.documents[i].data);
});
}
});
} else {
tempSearchGigStore = [];
queryResultGigSet.forEach((element) {
if (element['category'].startsWith(capitalizedValue)) {
setState(() {
isLoading = false;
tempSearchGigStore.add(element);
});
}
});
}
But For an array it isn't working. The code I have written is :
if (queryResultTagSet.length == 0 && val.length == 1) {
// SearchService().searchByName(val);
await databaseReference
.collection('posts')
.where('searchKeyTags', arrayContains: val.substring(0, 1).toUpperCase())
.getDocuments()
.then((QuerySnapshot docs) {
for (int i = 0; i < docs.documents.length; ++i) {
setState(() {
isLoading = false;
queryResultTagSet.add(docs.documents[i].data);
});
}
});
} else {
tempSearchTagStore = [];
queryResultTagSet.forEach((element) {
if (element['tags'].values.startsWith(capitalizedValue)) {
setState(() {
isLoading = false;
tempSearchTagStore.add(element);
});
}
});
}
}
}
the answer is
if (queryResultTagSet.length == 0 && val.length == 1) {
// SearchService().searchByName(val);
await databaseReference
.collection('posts')
.where('searchKeyTags',
arrayContains: val.substring(0, 1).toUpperCase())
.getDocuments()
.then((QuerySnapshot docs) {
for (int i = 0; i < docs.documents.length; ++i) {
setState(() {
isLoading = false;
queryResultTagSet.add(docs.documents[i].data);
});
}
});
} else {
tempSearchTagStore = [];
queryResultTagSet.forEach((element) {
List.from(element['tags']).forEach((p) {
if (p.toString().startsWith(capitalizedValue)) {
setState(() {
isLoading = false;
tempSearchTagStore.add(element);
});
}
});
});
}