I am trying to apply filters in firebase and am doing so by using startswith filters in the results.I have initialized the variables which act as a filter outside of all the classes
int duration = 1440;
String destination = '';
String Company = '';
int Maxcost = 99999999999;
int MinCost = 0;
String cla = '';
String airport = '';
This means that all files will be allowed to come. But when I change the variables from another class like this.
FILTER CLASS
Navigator.pushReplacement(
context, MaterialPageRoute(builder: (context) => Home(email:email,destination:destination,duration:duration,Maxcost: maxCost,Mincost: minCost,airport: airport,Company: company,)));
RECIEVING CLASS(Stateful Widget)
Home({this.email,duration = 1440,destination ='',Company = '',Maxcost = 99999999,Mincost = 0,cla = '',airport = ''});
I have added "=" as there are other classes which lead to this but they don't give these values. This makes it so that when those classes don't pass these values, it becomes the default values instead of null. Now where the problem occurs
StreamBuilder(
stream: Firestore.instance.collection("Planes").where(
"cost", isLessThan: Maxcost).where(
"cost", isGreaterThan: MinCost).snapshots(),
builder: (context, snapshot) {
List<DocumentSnapshot> m = snapshot.data.documents;
List<DocumentSnapshot> l=[];
DocumentSnapshot i;
for (i in m) {
if (i[' destination'].startsWith(destination) && i['duration']<(duration) && i['airport'].startsWith(airport) && i['class'].startsWith(cla) && i['company'].startsWith(Company)) {
l.add(i);
}
}
return ListView.builder(
itemCount: l.length,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.symmetric(
vertical: 1.0, horizontal: 4.0),
child: Card(
child: ListTile(
onTap: () {
Navigator.push(context, MaterialPageRoute(
builder: (context) =>
ViewPlane(plane: snapshot,
index: index,
email: email,)));
},
leading: Icon(Icons.airplanemode_active),
title: Text(l[index][' destination']),
subtitle: Text(
l[index]['airport']),
),
),
);
},
);
}
),
Before this happens(It is one of the first things done), the variable is set to the default values. How come? The variables are not initialized in the build function. Here is the entire code for the main class if needed.
MAIN CLASS
import 'dart:io';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:discount_app/AddSheets/AddPlane.dart';
import 'package:discount_app/FilterPage/PlaneFilter.dart';
import 'package:discount_app/Headings/home_screen_plane_packages.dart';
import 'package:discount_app/chat_pack/Loading.dart';
import 'package:discount_app/chat_pack/Settings.dart';
import 'package:discount_app/chat_pack/chat_home_page.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:discount_app/ViewSheets/ViewPlane.dart';
import 'package:discount_app/login_signup/Login.dart';
import 'package:discount_app/chat_pack/Const.dart';
import 'package:google_sign_in/google_sign_in.dart';
List<Choice> choices = const <Choice>[
const Choice(title:"Filters",icon:Icons.filter),
const Choice(title: 'Settings', icon: Icons.settings),
const Choice(title: 'Log out', icon: Icons.exit_to_app),
];
int duration = 1440;
String destination = '';
String Company = '';
int Maxcost = 99999999999;
int MinCost = 0;
String cla = '';
String airport = '';
#override
class Home extends StatefulWidget {
String email;
Home({this.email,duration = 1440,destination ='',Company = '',Maxcost = 99999999,Mincost = 0,cla = '',airport = ''});
#override
_HomeState createState() => _HomeState(email:email);
}
class _HomeState extends State<Home> {
var s;
void onItemMenuPress(Choice choice,) {
if (choice.title == 'Log out') {
handleSignOut();
}
else if (choice.title == 'Filters') {
Navigator.push(
context, MaterialPageRoute(builder: (context) => planeFilter(email:email)));
}
else {
Navigator.push(
context, MaterialPageRoute(builder: (context) => Settings()));
}
}
final GoogleSignIn googleSignIn = GoogleSignIn();
bool isLoading = false;
Future<Null> openDialog() async {
switch (await showDialog(
context: context,
builder: (BuildContext context) {
return SimpleDialog(
contentPadding: EdgeInsets.only(
left: 0.0, right: 0.0, top: 0.0, bottom: 0.0),
children: <Widget>[
Container(
color: themeColor,
margin: EdgeInsets.all(0.0),
padding: EdgeInsets.only(bottom: 10.0, top: 10.0),
height: 100.0,
child: Column(
children: <Widget>[
Container(
child: Icon(
Icons.exit_to_app,
size: 30.0,
color: Colors.white,
),
margin: EdgeInsets.only(bottom: 10.0),
),
Text(
'Exit app',
style: TextStyle(color: Colors.white,
fontSize: 18.0,
fontWeight: FontWeight.bold),
),
Text(
'Are you sure to exit app?',
style: TextStyle(color: Colors.white70, fontSize: 14.0),
),
],
),
),
SimpleDialogOption(
onPressed: () {
Navigator.pop(context, 0);
},
child: Row(
children: <Widget>[
Container(
child: Icon(
Icons.cancel,
color: primaryColor,
),
margin: EdgeInsets.only(right: 10.0),
),
Text(
'CANCEL',
style: TextStyle(
color: primaryColor, fontWeight: FontWeight.bold),
)
],
),
),
SimpleDialogOption(
onPressed: () {
Navigator.pop(context, 1);
},
child: Row(
children: <Widget>[
Container(
child: Icon(
Icons.check_circle,
color: primaryColor,
),
margin: EdgeInsets.only(right: 10.0),
),
Text(
'YES',
style: TextStyle(
color: primaryColor, fontWeight: FontWeight.bold),
)
],
),
),
],
);
})) {
case 0:
break;
case 1:
exit(0);
break;
}
}
Future<Null> handleSignOut() async {
this.setState(() {
isLoading = true;
});
await FirebaseAuth.instance.signOut();
await googleSignIn.disconnect();
await googleSignIn.signOut();
this.setState(() {
isLoading = false;
});
Navigator.of(context)
.pushAndRemoveUntil(
MaterialPageRoute(builder: (context) => LoginScreen()), (
Route<dynamic> route) => false);
}
String email;
_HomeState({this.email});
#override
Widget build(BuildContext context) {
return GestureDetector(
onPanUpdate: (details) {
if (details.delta.dx > 0) {
Navigator.pushReplacement(context, MaterialPageRoute(
builder: (context) => PlanePackages(email: email,)));
}
},
child: new Scaffold(
backgroundColor: Colors.pink[800],
appBar: new AppBar(
title: new Text('Home page'),
actions: <Widget>[
Padding(
padding: EdgeInsets.only(right: 20.0),
child: GestureDetector(
onTap: () {
Navigator.push(context, MaterialPageRoute(
builder: (context) =>
HomeScreen(currentUserId: email,)));
},
child: Icon(Icons.chat),
)),
PopupMenuButton<Choice>(
onSelected: onItemMenuPress,
itemBuilder: (BuildContext context) {
return choices.map((Choice choice) {
return PopupMenuItem<Choice>(
value: choice,
child: Row(
children: <Widget>[
Icon(
choice.icon,
color: primaryColor,
),
Container(
width: 10.0,
),
Text(
choice.title,
style: TextStyle(color: primaryColor),
),
],
));
}).toList();
},
),
],
),
body: WillPopScope(
child: Stack(
children: <Widget>[ StreamBuilder(
stream: Firestore.instance.collection("Planes").where(
"cost", isLessThan: Maxcost).where(
"cost", isGreaterThan: MinCost).snapshots(),
builder: (context, snapshot) {
List<DocumentSnapshot> m = snapshot.data.documents;
List<DocumentSnapshot> l=[];
DocumentSnapshot i;
for (i in m) {
if (i[' destination'].startsWith(destination) && i['duration']<(duration) && i['airport'].startsWith(airport) && i['class'].startsWith(cla) && i['company'].startsWith(Company)) {
l.add(i);
}
}
return ListView.builder(
itemCount: l.length,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.symmetric(
vertical: 1.0, horizontal: 4.0),
child: Card(
child: ListTile(
onTap: () {
Navigator.push(context, MaterialPageRoute(
builder: (context) =>
ViewPlane(plane: snapshot,
index: index,
email: email,)));
},
leading: Icon(Icons.airplanemode_active),
title: Text(l[index][' destination']),
subtitle: Text(
l[index]['airport']),
),
),
);
},
);
}
),
Positioned(
child: isLoading ? const Loading() : Container(),
)
]
),
onWillPop: () async {
openDialog();
return Future.value(false);
},
),
floatingActionButton: FloatingActionButton(
onPressed: () {
print(cla);
Navigator.push(context, MaterialPageRoute(
builder: (context) => AddPlane(email: email,)));
},
backgroundColor: Colors.green,
child: Icon(
Icons.add,
size: 30,
),
),
),
);
}
}
Any help will be appreciated
Navigator.pushReplacement(
context, MaterialPageRoute(builder: (context) => Home(email:email,destationName:destination,durationValue:duration,maximumCost: maxCost,minimumCost: minCost,airportName: airport,CompanyName: company,)));
assign it this way, since they're global variables you can't assign directly in the constructor parameters
Home({this.email,durationValue = 1440,destinationName ='',companyName = '',maximumCost = 99999999,minimumCost = 0,claValue = '',airportName = ''})
{
duration=durationValue;
destination=destinationName;
Maxcost = maximumCost;
Mincost = minimmCost;
cla=claValue;
airport=airportName;
Company = companyName;
}
Related
enter image description here I get Unexpected Null value error when switching from Home page to Vehicle Add page. I couldn't understand what caused this.
I tried to run it in debug mode, but it was very confusing in debug mode, I couldn't understand it.
home.dart page
import 'package:Car_Price_App/Pages/category_add.dart';
import 'package:Car_Price_App/Pages/vehicle_add.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import '../services/auth_service.dart';
class Home extends StatefulWidget {
const Home({super.key});
#override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
#override
Widget build(BuildContext context) {
final user = FirebaseAuth.instance.currentUser;
final email = user?.email;
return Scaffold(
appBar: AppBar(
title: Center(child: Text("Sıfır Araçlar ${email?.toUpperCase()}")),
leading: const Icon(Icons.car_rental),
actions: [
IconButton(onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (context)=> CategoryAdd(gelenEmail: email.toString(),)));
print("giden $email");
}, icon: const Icon(Icons.category)),
IconButton(onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (context)=> VehicleAdd()));
}, icon: const Icon(Icons.add)),
IconButton(onPressed: () {}, icon: const Icon(Icons.update)),
IconButton(onPressed: () {}, icon: const Icon(Icons.delete)),
],
),
body: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Giriş Yapıldı $email"),
const SizedBox(height: 10,),
ElevatedButton(onPressed: (){
AuthService().signOut();
}, child: const Text("Çıkış Yap",),),
],
),
),
);
}
}
vehicle_add.dart page
import 'dart:io';
import 'dart:math';
import 'dart:core';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:currency_text_input_formatter/currency_text_input_formatter.dart';
import 'package:file_picker/file_picker.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../models/trade_mark_model.dart';
import '../models/type_of_vehicle_model.dart';
import '../models/vehicle_body_type_model.dart';
import '../models/vehicle_model.dart';
import '../models/vehicle_year_model.dart';
class VehicleAdd extends StatefulWidget {
const VehicleAdd({Key? key}) : super(key: key);
#override
State<VehicleAdd> createState() => _VehicleAddState();
}
class _VehicleAddState extends State<VehicleAdd> {
GlobalKey? aracEkleKey = GlobalKey<FormState>();
var db = FirebaseFirestore.instance;
TextEditingController vehicleProperties = TextEditingController();
TextEditingController vehiclePrice = TextEditingController();
String? vasitaTipi = "";
String? kasaTipi = "";
String? marka = "";
String? model = "";
String? yil = "";
PlatformFile? pickedFile;
UploadTask? uploadTask;
Future selectFile() async {
final result = await FilePicker.platform.pickFiles();
if (result == null) return;
setState(() {
pickedFile = result.files.first;
});
}
Future uploadFile() async {
final path = 'aracResimleri/${pickedFile?.name}';
final file = File(pickedFile!.path!);
final ref = FirebaseStorage.instance.ref().child(path);
setState(() {
uploadTask = ref.putFile(file);
});
final snapshot = await uploadTask?.whenComplete(() {});
final urlDownload = await snapshot?.ref.getDownloadURL();
print('Download Link : $urlDownload');
setState(() {
uploadTask = null;
});
}
Stream<List<TypeOfVehicleModel>> readVehicleType() => db.collection("Vasıtalar").snapshots().map((snapshot) => snapshot.docs.map((doc) => TypeOfVehicleModel.fromJson(doc.data())).toList());
Stream<List<VehicleBodyTypeModel>> readBodyType() => db.collection("KasaTipleri").snapshots().map((snapshot) => snapshot.docs.map((doc) => VehicleBodyTypeModel.fromJson(doc.data())).toList());
Stream<List<TradeMarkModel>> readTradeMark() => db.collection("Markalar").snapshots().map((snapshot) => snapshot.docs.map((doc) => TradeMarkModel.fromJson(doc.data())).toList());
Stream<List<VehicleModel>> readVehicleModel() => db.collection("Modeller").snapshots().map((snapshot) => snapshot.docs.map((doc) => VehicleModel.fromJson(doc.data())).toList());
Stream<List<VehicleYearModel>> readVehicleYear() => db.collection("Yıllar").snapshots().map((snapshot) => snapshot.docs.map((doc) => VehicleYearModel.fromJson(doc.data())).toList());
late int _key;
_collapse() {
int? newKey;
do {
_key = Random().nextInt(10000);
} while (newKey == _key);
}
#override
void initState() {
super.initState();
_collapse();
}
#override
Widget build(BuildContext context) {
var screenInfo = MediaQuery.of(context);
final double screenWidth = screenInfo.size.width;
final double screenHeight = screenInfo.size.height;
return Scaffold(
appBar: AppBar(
title: const Text("Araç Ekle"),
),
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 30, vertical: 20),
child: Center(
child: Form(
autovalidateMode: AutovalidateMode.onUserInteraction,
key: aracEkleKey,
child: SizedBox(
width: screenWidth / 2,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
FutureBuilder<List<TypeOfVehicleModel>>(
future: readVehicleType().first,
builder: (context, snapshot) {
if (snapshot.hasError) {
return const Text("Something went wrong");
} else if (snapshot.hasData) {
final typeOfVehicle = snapshot.data!;
return ExpansionTile(
key: Key(_key.toString()),
initiallyExpanded: false,
leading: const Icon(Icons.merge_type),
title: const Text("Vasıta Seçiniz"),
children: typeOfVehicle.map(buildTov).toList(),
);
} else {
return const Center(
child: Padding(
padding: EdgeInsets.all(8.0),
child: CircularProgressIndicator(),
),
);
}
},
), // Vasıta Tipi
Text("$vasitaTipi"),
Text("$kasaTipi"),
Text("$marka"),
Text("$model"),
Text("$yil"),
FutureBuilder<List<VehicleBodyTypeModel>>(
future: readBodyType().first,
builder: (context, snapshot) {
if (snapshot.hasError) {
return const Text("Something went wrong");
} else if (snapshot.hasData) {
final bodyType = snapshot.data!;
return ExpansionTile(
key: Key(_key.toString()),
initiallyExpanded: false,
leading: const Icon(Icons.type_specimen),
title: const Text("Kasa Tipi Seçiniz"),
children: bodyType.map(buildBodyType).toList(),
);
} else {
return const Center(
child: Padding(
padding: EdgeInsets.all(8.0),
child: CircularProgressIndicator(),
),
);
}
},
), // Kasatipi
FutureBuilder<List<TradeMarkModel>>(
future: readTradeMark().first,
builder: (context, snapshot) {
if (snapshot.hasError) {
return const Text("Something went wrong");
} else if (snapshot.hasData) {
final tradeMarka = snapshot.data!;
return ExpansionTile(
key: Key(_key.toString()),
initiallyExpanded: false,
leading: const Icon(Icons.branding_watermark),
title: const Text("Marka Seçiniz"),
children: tradeMarka.map(buildTradeMark).toList(),
);
} else {
return const Center(
child: Padding(
padding: EdgeInsets.all(8.0),
child: CircularProgressIndicator(),
),
);
}
},
), //Markalar
FutureBuilder<List<VehicleModel>>(
future: readVehicleModel().first,
builder: (context, snapshot) {
if (snapshot.hasError) {
return const Text("Something went wrong");
} else if (snapshot.hasData) {
final model = snapshot.data!;
return ExpansionTile(
key: Key(_key.toString()),
initiallyExpanded: false,
leading: const Icon(Icons.time_to_leave),
title: const Text("Model Seçiniz"),
children: model.map(buildModel).toList(),
);
} else {
return const Center(
child: Padding(
padding: EdgeInsets.all(8.0),
child: CircularProgressIndicator(),
),
);
}
},
), //Modeller
FutureBuilder<List<VehicleYearModel>>(
future: readVehicleYear().first,
builder: (context, snapshot) {
if (snapshot.hasError) {
return const Text("Something went wrong");
} else if (snapshot.hasData) {
final year = snapshot.data!;
return ExpansionTile(
key: Key(_key.toString()),
initiallyExpanded: false,
leading: const Icon(Icons.calendar_month),
title: const Text(
"Yıl Seçiniz",
),
children: year.map(buildYear).toList(),
);
} else {
return const Center(
child: Padding(
padding: EdgeInsets.all(8.0),
child: CircularProgressIndicator(),
),
);
}
},
), //Yıllar
Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
controller: vehicleProperties,
decoration: const InputDecoration(
labelText: "Araç Özellikleri Giriniz",
suffixText: "Araç Özellikleri Giriniz",
border: OutlineInputBorder(),
),
minLines: 1,
maxLines: screenHeight.toInt(),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
keyboardType: TextInputType.number,
inputFormatters: <TextInputFormatter>[
// for below version 2 use this
FilteringTextInputFormatter.allow(RegExp(
r'\d',
)),
FilteringTextInputFormatter.digitsOnly,
CurrencyTextInputFormatter(
symbol: '₺',
name: "TL",
)
],
controller: vehiclePrice,
decoration: const InputDecoration(
labelText: "Araç Fiyat Giriniz",
suffixText: "Araç Fiyat Giriniz",
border: OutlineInputBorder(),
),
minLines: 1,
maxLines: screenHeight.toInt(),
),
),
Expanded(
child: Image.file(
File(pickedFile!.path!),
width: double.infinity,
fit: BoxFit.cover,
),
),
ElevatedButton.icon(
icon: const Icon(Icons.image),
onPressed: () {
selectFile();
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text("Araç Resmi Seç"),
content: Text(pickedFile!.name),
actions: [
TextButton(
onPressed: () async {
uploadFile();
},
child: const Center(
child: Text(
"Galeri'den Seç",
style: TextStyle(color: Colors.black, fontSize: 20),
))),
],
);
});
},
label: const Text("Araç Resimi Ekle"),
),
const SizedBox(
height: 30,
),
StreamBuilder<TaskSnapshot>(
stream: uploadTask!.snapshotEvents,
builder: (context, snapshot) {
if (snapshot.hasData) {
final data = snapshot.data!;
double progress = data.bytesTransferred / data.totalBytes;
return SizedBox(
height: 50,
child: Stack(
fit: StackFit.expand,
children: [
LinearProgressIndicator(
value: progress,
color: Colors.green,
backgroundColor: Colors.grey,
),
Center(
child: Text(
'${(100 * progress).roundToDouble()} %',
style: const TextStyle(color: Colors.white),
),
)
],
),
);
} else {
return const SizedBox(
height: 50,
);
}
},
)
],
),
),
),
),
),
),
// Fab Buton visible olacak doldurulması geren herşey dolduğunda gözükecek
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.add),
onPressed: () {
// bool kontrolSonucu = aracEkleKey.currentState!.validate();
},
),
);
}
Widget buildTov(TypeOfVehicleModel typeOfVehicleModel) => ListTile(
onTap: () {
setState(() {
_collapse();
vasitaTipi = typeOfVehicleModel.typeOfVehicle;
});
if (kDebugMode) {
print("$vasitaTipi");
}
},
leading: const Icon(
Icons.stars_outlined,
size: 10,
),
title: Text(typeOfVehicleModel.typeOfVehicle.toString()),
); //Araç vasıta tipi
Widget buildBodyType(VehicleBodyTypeModel vehicleBodyTypeModel) => ListTile(
onTap: () {
setState(() {
_collapse();
kasaTipi = vehicleBodyTypeModel.vehicleBodyType;
});
if (kDebugMode) {
print(vehicleBodyTypeModel.vehicleBodyType);
}
},
leading: const Icon(
Icons.stars_outlined,
size: 10,
),
title: Text(vehicleBodyTypeModel.vehicleBodyType.toString()),
); // Araç kasa tipi
Widget buildTradeMark(TradeMarkModel tradeMarkModel) => ListTile(
onTap: () {
setState(() {
_collapse();
marka = tradeMarkModel.tradeMarkName;
});
if (kDebugMode) {
print(tradeMarkModel.tradeMarkName);
}
},
leading: const Icon(
Icons.stars_outlined,
size: 10,
),
title: Text(tradeMarkModel.tradeMarkName.toString()),
); // Araç MArka
Widget buildModel(VehicleModel vehicleModel) => ListTile(
onTap: () {
setState(() {
_collapse();
model = vehicleModel.modelName;
});
if (kDebugMode) {
print(vehicleModel.modelName);
}
},
leading: const Icon(
Icons.stars_outlined,
size: 10,
),
title: Text(vehicleModel.modelName.toString()),
); // Araç Modeli
Widget buildYear(VehicleYearModel vehicleYearModel) => ListTile(
onTap: () {
setState(() {
_collapse();
yil = vehicleYearModel.year;
});
if (kDebugMode) {
print(vehicleYearModel.year);
}
},
leading: const Icon(
Icons.stars_outlined,
size: 10,
),
title: Text(vehicleYearModel.year.toString()),
); // Araç Yılı
Widget buildProgress() => StreamBuilder<TaskSnapshot>(
stream: uploadTask?.snapshotEvents,
builder: (context, snapshot) {
if (snapshot.hasData) {
final data = snapshot.data!;
double progress = data.bytesTransferred / data.totalBytes;
return SizedBox(
height: 50,
child: Stack(
fit: StackFit.expand,
children: [
LinearProgressIndicator(
value: progress,
color: Colors.green,
backgroundColor: Colors.grey,
),
Center(
child: Text(
'${(100 * progress).roundToDouble()} %',
style: const TextStyle(color: Colors.white),
),
)
],
),
);
} else {
return const SizedBox(
height: 50,
);
}
},
);
}
I don't know which variable is causing the problem. I'm inexperienced in flutter.
The error message says on which line the error is. See
That means it's on line 297. If I'm not mistaken that is the line:
child: Image.file(File(pickedFile!.path!),
So pickedFile is null
Hi the listview that is displayed below allows you to scroll a series of elements that are shown in a flutter list, the problem is that it is not possible to scroll the entire list, how can I correct this thing?
Flutter code:
import 'package:costal/Model/Maintenance.dart';
import 'package:costal/View/constants/color.dart';
import 'package:costal/View/utils/support.dart';
import 'package:costal/View/widgets/SceduledCard.dart';
import 'package:flutter/material.dart';
import 'package:rflutter_alert/rflutter_alert.dart';
import 'DetailScreen.dart';
class ScheduledScreen extends StatelessWidget {
const ScheduledScreen({Key? key}) : super(key: key);
Future<List<Maintenance>> loadvalues() async {
return await Maintenance.getMaintenanceScheduled();
}
Future<bool> completeDay(BuildContext context, Maintenance man) async {
var check = await man.completeDay();
if (check == true) {
Share.alertCustom(context, AlertType.success, 'Manutenzione Completa', 'Hai completato la manutenzione', true);
} else {
Share.alertCustom(context, AlertType.error, 'Errore', 'non è stato possibile completare le manutenzioni', false);
}
return check;
}
Widget getLoader() {
return const Align(
alignment: Alignment.center,
child: CircularProgressIndicator(
value: 50,
semanticsLabel: 'Loading value',
),
);
}
#override
Widget build(BuildContext context) {
return FutureBuilder<List<Maintenance>>(
future: loadvalues(),
builder: (BuildContext context, AsyncSnapshot<List<Maintenance>> snapshot) {
if (!snapshot.hasData) {
return getLoader();
} else {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: const Text(
'Manutenzioni',
style: TextStyle(
fontFamily: 'Poppins',
color: kPrimaryColor,
),
),
leading: CircleAvatar(
radius: 20,
backgroundColor: const Color(0xff94d500),
child: IconButton(
icon: const Icon(Icons.access_alarms_sharp),
onPressed: () async {
completeDay(context, snapshot.data![0]);
},
),
),
),
body: Wrap(
//the magic
children: [
Container(
padding: const EdgeInsets.all(20),
child: ListView.separated(
shrinkWrap: true,
itemCount: snapshot.data!.length,
separatorBuilder: (context, index) {
return const SizedBox(
height: 10,
);
},
itemBuilder: (context, index) {
return GestureDetector(
onTap: (() {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => DetailScreen(snapshot.data![index])),
);
}),
child: SceduledCard(man: snapshot.data![index], c: Colors.blue),
);
}))
],
),
);
}
});
}
}
I am getting an error and red screen while trying to click a button. RangeError (index): Invalid value: Valid value range is empty: 0. I do not know how to fix this error because nothing is flagged until I run my emulator. I have attached my
If I need to add some code please let me know I am more than willing to. Thank you!
home_page.dart
import 'package:flutter/material.dart';
import 'package:timestudy_test/pages/study_page.dart';
import 'package:timestudy_test/pages/timer_page.dart';
import 'package:timestudy_test/viewmodels/study_viewmodel.dart';
class HomePage extends StatefulWidget {
#override
State createState() => HomePageState();
}
class HomePageState extends State<HomePage> {
TextEditingController textController = new TextEditingController();
late String filter;
#override
void initState() {
textController.addListener(() {
setState(() {
filter = textController.text;
});
});
super.initState();
}
#override
void dispose() {
textController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
appBar: AppBar(
title: Text('TimeStudyApp'),
),
body: Material(
child: Column(
children: <Widget>[
Padding(
padding: EdgeInsets.only(top: 8.0, left: 16.0, right: 16.0),
child: TextField(
style: TextStyle(fontSize: 18.0),
decoration: InputDecoration(
prefixIcon: Icon(Icons.search),
suffixIcon: IconButton(
icon: Icon(Icons.close),
onPressed: () {
textController.clear();
FocusScope.of(context).requestFocus(FocusNode());
},
),
hintText: "Search...",
),
controller: textController,
)),
Expanded(
child: StudyViewModel.studies.length > 0
? ListView.builder(
itemCount: StudyViewModel.studies.length,
itemBuilder: (BuildContext context, int index) {
if (filter == null || filter == "") {
return buildRow(context, index);
} else {
if (StudyViewModel.studies[index].name
.toLowerCase()
.contains(filter.toLowerCase())) {
return buildRow(context, index);
} else {
return Container();
}
}
},
)
: Center(
child: Text('No studies found!'),
),
)
],
),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () async {
int? nullableInterger;
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => StudyPage(
title: 'Add a study',
selected: nullableInterger ?? 0,
)));
},
),
);
}
Widget buildRow(BuildContext context, int index) {
return ExpansionTile(
title: Text(StudyViewModel.studies[index].name, style: TextStyle(fontSize: 18.0)),
children: <Widget>[
ListView.builder(
shrinkWrap: true,
physics: ClampingScrollPhysics(),
itemCount: StudyViewModel.studies[index].tasks.length,
itemBuilder: (context, int taskIndex) {
return ListTile(
title: Text(StudyViewModel.studies[index].tasks[taskIndex].name),
contentPadding: EdgeInsets.symmetric(horizontal: 32.0),
subtitle: Text(
StudyViewModel.studies[index].tasks[taskIndex].elapsedTime),
trailing: IconButton(
icon: Icon(
Icons.timer
),
onPressed: () async {
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => TimerPage(
task: StudyViewModel
.studies[index].tasks[taskIndex])));
},
),
);
},
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
IconButton(
icon: Icon(
Icons.edit
),
onPressed: () async {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => StudyPage(
title: StudyViewModel.studies[index].name,
selected: index)));
},
),
IconButton(
icon: Icon(
Icons.delete
),
onPressed: () async {
await showDialog(
context: context,
builder: (context) {
return AlertDialog(
content: Text('Do you wish to delete this study?'),
actions: <Widget>[
FlatButton(
child: Text('Accept'),
onPressed: () async {
StudyViewModel.studies.removeAt(index);
await StudyViewModel.saveFile();
Navigator.of(context).pop();
},
),
FlatButton(
child: Text('Cancel'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
});
},
),
],
),
],
);
}
}
study_page.dart
import 'package:flutter/material.dart';
import 'package:timestudy_test/models/study.dart';
import 'package:timestudy_test/models/task.dart';
import 'package:timestudy_test/viewmodels/study_viewmodel.dart';
class StudyPage extends StatefulWidget {
final String title;
final int selected;
StudyPage({required this.title, required this.selected});
#override
State createState() => StudyPageState();
}
class StudyPageState extends State<StudyPage> {
late Study study;
late TextField nameField;
TextEditingController nameController = new TextEditingController();
late TextField taskNameField;
TextEditingController taskNameController = new TextEditingController();
#override
void initState() {
nameField = new TextField(
controller: nameController,
decoration: InputDecoration(
labelText: 'Study name'),
);
taskNameField = new TextField(
controller: taskNameController,
decoration:
InputDecoration(labelText: 'Task name'),
);
if(widget.selected != null) {
study = StudyViewModel.studies[widget.selected];
nameController.text = study.name;
} else {
study = new Study(
name: "",
tasks: <Task>[]
);
}
super.initState();
}
#override
void dispose() {
nameController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
appBar: AppBar(
title: Text(widget.title),
),
body: Material(
child: Padding(padding: EdgeInsets.all(16.0), child: Column(
children: <Widget>[
Padding(padding: EdgeInsets.only(bottom: 8.0), child: nameField),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text('Tasks:', style: TextStyle(fontSize: 18.0),),
IconButton(
icon: Icon(Icons.add),
onPressed: () async {
await showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text('Add a task'),
content: taskNameField,
actions: <Widget>[
FlatButton(
child: Text('Cancel'),
onPressed: () {
Navigator.of(context).pop();
},
),
FlatButton(
child: Text('Accept'),
onPressed: () {
if(taskNameController.text == ""){
errorDialog(context, 'Please enter a task name!');
} else {
setState(() {
study.tasks.add(new Task(
name: taskNameController.text,
elapsedTime:
StudyViewModel.milliToElapsedString(
0)));
taskNameController.clear();
});
Navigator.of(context).pop();
}
},
),
],
);
});
},
)
],
),
Expanded(
child: ListView.builder(
itemCount: study.tasks.length,
itemBuilder: (context, int index) {
return ListTile(
title: Text(study.tasks[index].name),
trailing: IconButton(
icon: Icon(Icons.delete),
onPressed: () {
setState(() {
study.tasks.removeAt(index);
});
},
),
);
},
),
), Spacer(),
Center(
child: RaisedButton(
color: Theme.of(context).accentColor,
child: Text('Save'),
onPressed: () async {
if (nameController.text == "") {
errorDialog(context, 'Please enter a study name!');
} else {
if (study.tasks.length < 1) {
errorDialog(context, 'Please add at least one task!');
} else {
study.name = nameController.text;
if (widget.selected != null) {
StudyViewModel.studies[widget.selected] = study;
await StudyViewModel.saveFile();
Navigator.of(context).pop();
} else {
if (StudyViewModel.checkName(nameController.text)) {
errorDialog(context, 'Study name already taken!');
} else {
StudyViewModel.studies.add(study);
await StudyViewModel.saveFile();
Navigator.of(context).pop();
}
}
}
}
},
))
],
),
)));
}
void errorDialog(BuildContext context, String message) async {
await showDialog(
context: context,
builder: (context) {
return AlertDialog(
content: Text(message),
actions: <Widget>[
FlatButton(
child: Text('Close'),
onPressed: () {
Navigator.of(context).pop();
},
)
],
);
}
);
}
}
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () async {
int? nullableInterger;
// the issue is here you need to assign value
// the nullableInterger is use here as nothing.. declare it on state level and
// assign it when your listview builder done so the value of nullable integer is
// changed and passing value as argument will not be 0 and this error will not appear again
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => StudyPage(
title: 'Add a study',
selected: nullableInterger ?? 0,
)));
},
),
I need to refresh my FutureBuilder => Listview.builder => Listtile, but i found no work around. when i do a hot reload, it updates, so there must be a way to reload whole classes? Its enIt would also be enough if I could only update the Listview.builder/FutureBuilder/ListTile. My code of my .dart:
import 'dart:async' show Future;
import 'package:ListGet/QR_Code/QR_Code_main.dart';
import 'package:ListGet/global/classes/routing_consting.dart';
import 'package:ListGet/localization/localizatzion_constants.dart';
import 'package:flutter/services.dart' show rootBundle;
import 'dart:convert';
import 'package:ListGet/global/global.dart' as globals;
import 'package:ListGet/global/classes/OverviewProduct.dart';
import 'package:flutter/material.dart';
import '../../main.dart';
class OverViewList extends StatefulWidget {
OverViewList({Key key}) : super(key: key);
#override
_OverViewListState createState() => _OverViewListState();
}
class _OverViewListState extends State<OverViewList> {
String data = "";
#override
Widget build(BuildContext context) {
return Scaffold(
body: RefreshIndicator(
onRefresh: _loadproductsoverview,
child: Container(
child: Column(
children: [
Expanded(
child: Container(
child: FutureBuilder(
builder: (context, snapshot) {
var showData = json.decode(snapshot.data.toString());
globals.jsongetitemlist = showData;
if (snapshot.hasData) {
return ListView.builder(
itemCount: showData.length,
itemBuilder: (BuildContext context, int index) {
return Padding(
padding: EdgeInsets.fromLTRB(12, 0, 12, 0),
child: GestureDetector(
onLongPress: () {
loadproductsoverview(index).then(
(value) => print(globals.productName));
},
onDoubleTap: () {
print("2");
},
onTap: () {
print("3");
},
child: Card(
child: ListTile(
contentPadding:
EdgeInsets.fromLTRB(8, 5, 5, 5),
title: Padding(
padding: const EdgeInsets.fromLTRB(
0, 0, 0, 10),
child:
Text(showData[index]["Product_Name"]),
),
subtitle: Text(getLang(context, "stock") +
" : " +
showData[index]["Stock"] +
"\n" +
getLang(context, "expiry_date") +
" " +
showData[index]["Expiry_date"]),
),
),
),
);
},
);
}
return CircularProgressIndicator();
},
future: DefaultAssetBundle.of(context).loadString(
"lib/global/Overview_Products/Overview_Product.json"),
),
),
),
Container(
color: "dark" == "dark"
? globals.darkThemeslide4
: globals.whiteThemeslide7,
height: 46,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(4, 5, 15, 5),
child: IconButton(
onPressed: () => _scan(),
icon: Icon(Icons.qr_code_scanner_rounded),
iconSize: 30,
tooltip: "Scan your Product",
),
),
Padding(
padding: const EdgeInsets.fromLTRB(4, 5, 15, 5),
child: IconButton(
onPressed: () {
Navigator.pushNamed(context, InterfaceViewRoute,
arguments: "");
print(globals.themeswitch);
main();
},
icon: Icon(Icons.edit),
iconSize: 30,
tooltip: "Enter your Product by your self",
),
),
],
),
),
],
),
),
),
);
}
Future<String> _loadproductsoverview() async {
print("1");
return await rootBundle
.loadString('lib/global/Overview_Products/Overview_Product.json');
}
Future loadproductsoverview(index) async {
String jsonString = await _loadproductsoverview();
final jsonResponse = json.decode(jsonString);
OverviewProducts student =
new OverviewProducts.fromJson(jsonResponse[index]);
globals.productName = student.productName;
}
// ignore: missing_return
Future<String> _scan() async {
await FlutterBarcodeScanner.scanBarcode(
"#000000", "Back", true, ScanMode.BARCODE)
.then((value) => setState(() => data = value));
if (data != "-1") {
Navigator.pushNamed(context, InterfaceViewRoute, arguments: data);
}
}
}
test() {}
when i swipe from top to bottom, all entrys should be updated, out of the json.
tried also this :
class _OverViewListState extends State<OverViewList> {
String data = "";
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: Column(
children: [
Expanded(
child: Container(
child: FutureBuilder(
builder: (context, snapshot) {
var showData = json.decode(snapshot.data.toString());
globals.jsongetitemlist = showData;
if (snapshot.hasData) {
return RefreshIndicator(
onRefresh: _loadproductsoverview,
child: ListView.builder(
itemCount: showData.length,
itemBuilder: (BuildContext context, int index) {
return Padding(
padding: EdgeInsets.fromLTRB(12, 0, 12, 0),
child: GestureDetector(
onLongPress: () {
loadproductsoverview(index).then(
(value) => print(globals.productName));
},
onDoubleTap: () {
print("2");
},
onTap: () {
print("3");
},
child: Card(
child: ListTile(
contentPadding:
EdgeInsets.fromLTRB(8, 5, 5, 5),
title: Padding(
padding: const EdgeInsets.fromLTRB(
0, 0, 0, 10),
child:
Text(showData[index]["Product_Name"]),
),
subtitle: Text(getLang(context, "stock") +
" : " +
showData[index]["Stock"] +
"\n" +
getLang(context, "expiry_date") +
" " +
showData[index]["Expiry_date"]),
),
),
),
);
},
),
);
}
return CircularProgressIndicator();
},
future: DefaultAssetBundle.of(context).loadString(
"lib/global/Overview_Products/Overview_Product.json"),
),
),
),
Container(
color: "dark" == "dark"
? globals.darkThemeslide4
: globals.whiteThemeslide7,
height: 46,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(4, 5, 15, 5),
child: IconButton(
onPressed: () => _scan(),
icon: Icon(Icons.qr_code_scanner_rounded),
iconSize: 30,
tooltip: getLang(context, "tooltip_qrcode"),
),
),
Padding(
padding: const EdgeInsets.fromLTRB(4, 5, 15, 5),
child: IconButton(
onPressed: () {
Navigator.pushNamed(context, InterfaceViewRoute,
arguments: "");
print(globals.themeswitch);
main();
},
icon: Icon(Icons.edit),
iconSize: 30,
tooltip: getLang(context, "tooltip_pencil"),
),
),
],
),
),
],
),
),
);
}
Future<String> _loadproductsoverview() async {
print("1");
setState(() {}); // <======= Add here
return await rootBundle
.loadString('lib/global/Overview_Products/Overview_Product.json');
}
Future loadproductsoverview(index) async {
String jsonString = await rootBundle.loadString('lib/global/Overview_Products/Overview_Product.json'); //<== dont call the function here
final jsonResponse = json.decode(jsonString);
OverviewProducts student =
new OverviewProducts.fromJson(jsonResponse[index]);
globals.productName = student.productName;
}
Please add a setState in _loadproductsoverview() method. This should do the trick;
Method loadString has a property cache, which is true by default. Set it to false and the file will be re-read.
https://api.flutter.dev/flutter/services/AssetBundle/loadString.html
And also swap FutureBuilder and RefreshIndicator. Then you can control state via using setState.
I have added a GIF where you can see that when I click on favourite (heart) menu it loads smoothly and doesn't flick but when I click on side menu it flicks
I am working on an app and I am trying to resolve an issue, there is a screen whenever I click it, it flicks or blinks, it kind of refreshes. All the content it contain refresh, like if I click it I feel like I come on that screen then the items come there later on, it happens in few frictions of seconds but it is too annoying. I tried everything but still.
I tried to slow down the animation globally by using time dilation but it is still happening.
const String logo = "assets/profile/images/stadia_logo.svg";
class ProfileScreen extends StatefulWidget {
#override
_ProfileScreenState createState() => _ProfileScreenState();
}
class _ProfileScreenState extends State<ProfileScreen> {
#override
Widget build(BuildContext context) {
final user = Provider.of<User>(context);
final StorageService ref = StorageService();
final screenHeight = MediaQuery.of(context).size.height;
final screenWidth = MediaQuery.of(context).size.width;
final logoHeight = screenHeight * 0.4;
return Scaffold(
backgroundColor: Colors.white,
body: FutureBuilder(
future: ref.getProfileUrl(user.uid),
builder: (BuildContext context, AsyncSnapshot<String> url) {
if (url.connectionState == ConnectionState.waiting) {
return Loading(
size: 20,
);
}
if (url.hasData) {
return StreamBuilder<DocumentSnapshot>(
stream: DatabaseService(uid: user.uid).userData,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Loading(
size: 15,
);
}
if (snapshot.data == null) {
return Loading(
size: 15,
);
}
var userData = snapshot.data;
String _imageUrl = url.data;
if (snapshot.hasData) {
List books = userData['audio_read'];
if (books == null) {
return Loading(
size: 15,
);
//this
}
return Scaffold(
body: Stack(
children: <Widget>[
Transform.translate(
offset: Offset(screenWidth * 0.4, 10),
child: Transform.rotate(
angle: -0.1,
child: SvgPicture.asset(
logo,
height: logoHeight,
color: logoTintColor,
),
),
),
SingleChildScrollView(
child: Column(
children: <Widget>[
SizedBox(
height: 60,
),
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 16.0),
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: <Widget>[
//
createFirstNameHeader(
user, ref, userData),
Padding(
padding: const EdgeInsets.only(
right: 16.0, bottom: 16, top: 16),
child: Material(
elevation: 4,
borderRadius:
const BorderRadius.all(
Radius.circular(12)),
child: Padding(
padding: const EdgeInsets.only(
left: 16.0,
right: 16.0,
top: 16.0,
bottom: 32.0),
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: <Widget>[
Row(
children: <Widget>[
Text(
"TOTAL TALES PLAYED",
style:
hoursPlayedLabelTextStyle,
),
],
),
SizedBox(
height: 4,
),
Text(
"${books.length.toString()} ${books.length > 1 ? "Tales" : "Tale"}",
style: hoursPlayedTextStyle
.copyWith(
color: Color(
0xff5E17EB)),
)
],
),
),
),
),
ContentHeadingWidget(
heading: "Continue listening"),
for (var i = books.length - 1;
i >= 0;
i--)
books.length > 0
? Slidable(
actionExtentRatio: 0.25,
actionPane:
SlidableDrawerActionPane(),
secondaryActions: <Widget>[
IconSlideAction(
caption: 'Delete',
color: Colors.red,
icon: Icons.delete,
onTap: () => {
_deletePressed(
user,
books.elementAt(
i)[
'audio_id']),
}),
],
child: LastReadBook(
audioId: books.elementAt(
i)['audio_id'],
audio_index: int.parse(
books.elementAt(i)[
'audio_index']),
audioSeek: books.elementAt(
i)['audio_seek'],
total: books.elementAt(
i)['total'],
progress: int.parse(books.elementAt(i)['audio_index']) /
books.elementAt(
i)["totalIndex"],
description:
"${books.elementAt(i)["audio_index"]} of ${books.elementAt(i)["totalIndex"]} episodes",
image: books
.elementAt(i)['image']),
)
: Loading(
size: 15,
),
],
),
),
],
),
)
],
),
);
} else {
return Loading(
size: 15,
);
}
});
} else {
return Loading(
size: 15,
);
}
}),
);
}
Padding createFirstNameHeader(
User user, StorageService ref, DocumentSnapshot userData) {
return Padding(
padding: const EdgeInsets.symmetric(
vertical: 16.0,
),
child: Row(
children: <Widget>[
createProfileImage(user, ref),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 10.0),
child: RichText(
text: TextSpan(
children: [
TextSpan(
text: 'Hello',
style: userNameTextStyle,
),
TextSpan(text: '\n'),
TextSpan(
text: userData['firstname'], style: userNameTextStyle),
],
),
),
),
],
),
);
}
createProfileImage(User user, StorageService ref) {
return StreamBuilder(
stream: Firestore.instance
.collection("Users")
.document(user.uid)
.snapshots(),
builder: (context, AsyncSnapshot<DocumentSnapshot> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
// return Center(
// child: CircularProgressIndicator(),
// );
return Loading(
size: 15,
);
}
if (snapshot.data == null) {
return Loading(
size: 15,
);
}
print(snapshot.data.data);
return GestureDetector(
onTap: () async {
if (user.uid != HomeScreen.defaultUID) {
dynamic imageFromUser = await ref.getImage();
await ref.addImageToFirebase(user.uid, imageFromUser);
} else {
createAccountDialouge(context);
}
},
child: RoundedImageWidget(
imagePath: snapshot.data["profile_image"],
icon: Icons.photo_camera,
showIcon: true),
);
});
}
createAccountDialouge(BuildContext context) {
return showDialog(
context: context,
child: CupertinoAlertDialog(
title: Text('Avid Tale Would Like to Enable Full Access'),
content: Text('Creating an account will enable access to this feature'),
actions: <Widget>[
CupertinoDialogAction(
child: Text('Cancel'),
onPressed: () {
Navigator.pop(context);
},
),
CupertinoDialogAction(
child: Text('Register'),
onPressed: () {
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) {
return RegisterScreen();
},
),
);
},
)
],
),
);
}
void _deletePressed(user, bookId) async {
DatabaseService userService = DatabaseService(uid: user.uid);
DocumentSnapshot documentSnapshot =
await Firestore.instance.collection("Users").document(user.uid).get();
var data = documentSnapshot.data["audio_read"];
data.retainWhere((element) => element["audio_id"] != bookId);
await userService.updateUserData({'audio_read': FieldValue.delete()});
await userService
.updateUserData({'audio_read': FieldValue.arrayUnion(data)});
}
}
Every time you delete an item, it triggers a new event in the Stream. As the Stream is retrieving/processing the new data it goes into this if block of code as the connectionState changes to waiting:
if (snapshot.connectionState == ConnectionState.waiting) {
return Loading(
size: 15,
);
}
Simply removing this block of code will should stop the "flickering". You may need to include other checks of data availability if necessary for your application.