calculate discount of prices in flutter - math

I want to try define below formula to calculate between old price and new price and show it on text widget but when i want to use it in an double variable i've got this error : "Only static members can be accessed in initializers"
and this is what i want to do:
class ProductDetails extends StatefulWidget {
final prod_fullName;
final prod_pic;
final prod_old_price;
final prod_price;
double percent=(prod_old_price - prod_price)/prod_old_price*100;
ProductDetails({
this.prod_fullName,
this.prod_pic,
this.prod_old_price,
this.prod_price,
});
#override
_ProductDetailsState createState() => _ProductDetailsState();
}
class _ProductDetailsState extends State<ProductDetails> {
Row{
child:new Text("$percent%");
}

class ProductDetails extends StatefulWidget {
final String prod_fullName;
final String prod_pic;
final double prod_old_price;
final double prod_price;
const ProductDetails({Key key, this.prod_fullName, this.prod_pic, this.prod_old_price, this.prod_price}) : super(key: key);
#override
_ProductDetailsState createState() => _ProductDetailsState();
}
class _ProductDetailsState extends State<ProductDetails> {
double percent;
#override
void initState() {
percent=(widget.prod_old_price - widget.prod_price)/widget.prod_old_price*100;
super.initState();
}
#override
Widget build(BuildContext context) {
return Text("$percent%");
}
}

Related

unable to pass data to a different class

My main class MainScreenState has a function saveRideRequest that saves a node to firebase where I need to get a key from, I need to pass this key to another class TipTop but every time my code runs the value sent and obtained is null. How can I fix it ? In short, I want to pass rideRequestRef.key from mainScreen to class TipTop as rideReqKey
class MainScreen extends StatefulWidget {
const MainScreen({Key key}) : super(key: key);
#override
_MainScreenState createState() => _MainScreenState();
}
class _MainScreenState extends State<MainScreen> {
DatabaseReference rideRequestRef;
void saveRideRequest() {
rideRequestRef =
FirebaseDatabase.instance.reference().child("Ride Requests").push();
///some code
print (rideRequestRef.key); //gets correct value
}
#override
Widget build(BuildContext context) {
return Container(child: TipTop(
saveRiderAndSearchNearRidecallback: (rideReqKey, listDriver) async {
saveRideRequest();
rideReqKey = rideRequestRef.key;
}));
}
}
class TipTop extends StatefulWidget {
final Function(String, List) saveRiderAndSearchNearRidecallback;
const TipTop({Key key, this.saveRiderAndSearchNearRidecallback})
: super(key: key);
#override
State<StatefulWidget> createState() => _StateTipTop();
}
class _StateTipTop extends State<TipTop> {
#override
Widget build(BuildContext context) {
return Container(child: GestureDetector(
onTap: () {
String rideReqKey;
List tempList;
widget.saveRiderAndSearchNearRidecallback(rideReqKey, tempList);
print(rideReqKey); //Null here
},
));
}
}
Try this:
class MainScreen extends StatefulWidget {
const MainScreen({Key key}) : super(key: key);
#override
_MainScreenState createState() => _MainScreenState();
}
class _MainScreenState extends State<MainScreen> {
DatabaseReference rideRequestRef;
void saveRideRequest() {
rideRequestRef =
FirebaseDatabase.instance.reference().child("Ride Requests").push();
///some code
print (rideRequestRef.key); //gets correct value
}
#override
Widget build(BuildContext context) {
return Container(child: TipTop(
saveRiderAndSearchNearRidecallback: (rideReqKey, listDriver) async {
saveRideRequest();
rideReqKey = rideRequestRef.key;
},
rideReqKey:rideRequestRef.key
));
}
}
class TipTop extends StatefulWidget {
final String rideReqKey;
final Function(String, List) saveRiderAndSearchNearRidecallback;
const TipTop({Key key, this.saveRiderAndSearchNearRidecallback, this. rideReqKey})
: super(key: key);
#override
State<StatefulWidget> createState() => _StateTipTop();
}
class _StateTipTop extends State<TipTop> {
#override
Widget build(BuildContext context) {
return Container(child: GestureDetector(
onTap: () {
List tempList;
widget.saveRiderAndSearchNearRidecallback(rideReqKey, tempList);
print(rideReqKey); //No longer null.
},
));
}
}

The listener runs again every time the widget rebuild

i want to listen if there is a constant change in my firestore db. But it runs when widget rebuild (idk
because of init state? but why listener dont prevent the fonc?)
class _ActivityScreen extends State<ActivityScreen> {
final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey();
#override
void initState(){
super.initState();
checkFocChanges();
}
checkFocChanges() async {
var reference = Firestore.instance.collection('etkinlikler').orderBy('sıra');
reference.snapshots().listen((querySnapshot) {
querySnapshot.documentChanges.forEach((change) {
resetDb(change.document.data);
});
});
}
void resetDb(documents){
print(documents['ad'].toString());}
#override
Widget build(BuildContext context) {
return BlocProvider(
builder:(BuildContext context ) => ActivitiesBloc(),
I really need help between the firestore and the flutter.

how to make 2 recyclerView beside each others using firebase UI?

hi I am using Firebase recyclerview UI and I succeed to perform one RecyclerView, but when I continue to add the second, the application creates error.
The question is how to add 2 recyclers in the same activity with very simple form? I just want them beside each others.
How can I do that?
this is my code
public class HarvestingActivity extends AppCompatActivity {
RecyclerView T;
RecyclerView S;
DatabaseReference mRefTot;
DatabaseReference mRefSin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setContentView(R.layout.activity_harvesting);
FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
assert currentUser != null;
T = (RecyclerView) findViewById(R.id.recyclerviewT);//this is for total
T.setLayoutManager(new LinearLayoutManager(this));
T.setHasFixedSize(true);
S = (RecyclerView) findViewById(R.id.recyclerviewS);//this is for single
S.setLayoutManager(new LinearLayoutManager(this));
S.setHasFixedSize(true);
mRefTot = FirebaseDatabase.getInstance().getReference()
.child("HarvestingActivity")
.child("TotalActivity");
FirebaseRecyclerAdapter<TotalUsers, TotalUsersHolder> T_Adapter = new FirebaseRecyclerAdapter<TotalUsers, TotalUsersHolder>(
TotalUsers.class,
R.layout.h_item_user_total,
TotalUsersHolder.class,
mRefTot
) {
#Override
protected void populateViewHolder(TotalUsersHolder viewHolder, TotalUsers model, int position) {
FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
assert currentUser != null;
viewHolder.setName(model.getName());
}
};
mRefSin=FirebaseDatabase.getInstance().getReference()
.child("HarvestingActivity")
.child("SingleActivity");
FirebaseRecyclerAdapter<SingleUser,SingleUserHolder>
S_Adapter=new
FirebaseRecyclerAdapter<SingleUser,SingleUserHolder>(
SingleUser.class,
R.layout.h_item_users_single,
SingleUserHolder.class,
mRefSin
) {
#Override
protected void populateViewHolder(SingleUserHolder viewHolder,
SingleUser model, int position) {
FirebaseUser currentUser =
FirebaseAuth.getInstance().getCurrentUser();
assert currentUser != null;
viewHolder.setName(model.getName());
}
};
T.setAdapter(T_Adapter);
S.setAdapter(S_Adapter);
}
public static class TotalUsersHolder extends RecyclerView.ViewHolder {
View view;
public TotalUsersHolder(View itemView) {
super(itemView);
view = itemView;
}
public void setName(String name) {
TextView Harvester_Name = (TextView) view.findViewById(R.id.HarvesterName);
Harvester_Name.setText(name);
}
}
private class SingleUserHolder extends RecyclerView.ViewHolder {
View sview;
public SingleUserHolder(View itemView) {
super(itemView);
sview=itemView;
}
public void setName(String name) {
TextView Answer_Name = (TextView)
sview.findViewById(R.id.AnswerName);
Answer_Name.setText(name);
}
}
}

Retrieving list of images from Firebase, using GenericTypeIndicator<Map<String, String>>() { }

I need help with this, I've been trying to show a list of images into a recycler view but seriously I can't.
This is my database in firebase, shows the images from different events with randoms ids
This is my class:
public class Imagenes {
GenericTypeIndicator<Map<String,String>> images = new GenericTypeIndicator<Map<String, String>>(){};
public Imagenes(GenericTypeIndicator<Map<String, String>> images) {
this.images = images;
}
public GenericTypeIndicator<Map<String, String>> getImages() {
return images;
}
public void setImages(GenericTypeIndicator<Map<String, String>> images) {
this.images = images;
}
}
And yes its seems very bad but I don't know how to do it, since its not like a normal class with
name
phone
images
I mean i don't know their names, it's just random. I been reading that I have to use this kind of map, but I don't know how to use it in a class
This is my code in EventSingle:
public class EventoSingleActivity extends AppCompatActivity {
DatabaseReference mDatabaseEvento;
TextView TituloEvento;
RecyclerView mListaImagenes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_evento_single);
mListaImagenes = (RecyclerView) findViewById(R.id.listaImagenes);
mListaImagenes.setHasFixedSize(true);
mListaImagenes.setLayoutManager(new LinearLayoutManager(this));
String Evento_key = getIntent().getExtras().getString("Evento_id");
Toast.makeText(this, Evento_key, Toast.LENGTH_SHORT).show();
mDatabaseEvento = FirebaseDatabase.getInstance().getReference().child("Evento").child(Evento_key).child("Imagenes");
System.out.println(mDatabaseEvento);
TituloEvento = (TextView) findViewById(R.id.tituloEventoField);
mDatabaseEvento.keepSynced(true);
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerAdapter<Imagenes, ImagenesEventoViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Imagenes, ImagenesEventoViewHolder>(
Imagenes.class,
R.layout.cardview_imagen,
ImagenesEventoViewHolder.class,
mDatabaseEvento
) {
#Override
protected void populateViewHolder(final ImagenesEventoViewHolder viewHolder, Imagenes model, int position) {
mDatabaseEvento.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
System.out.println("Estoy entrando aqui");
Log.i("gguwu", "Ayudaaaa");
GenericTypeIndicator<Map<String,String>> ImagenesType = new GenericTypeIndicator<Map<String, String>>() { };
Map<String,String> Imagenes = dataSnapshot.getValue(ImagenesType);
if (Imagenes!=null ) {
for (String imagen: Imagenes.values()) {
System.out.println(imagen);
viewHolder.setImagen(getApplicationContext(), imagen);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
};
mListaImagenes.setAdapter(firebaseRecyclerAdapter);
}
public static class ImagenesEventoViewHolder extends RecyclerView.ViewHolder{
View view;
public ImagenesEventoViewHolder(View itemView) {
super(itemView);
view = itemView;
}
public void setImagen(Context ctx, String imagen){
ImageView imagencita = (ImageView) view.findViewById(R.id.imagen_item);
Picasso.with(ctx).load(imagen).into(imagencita);
}
}
}
I don't know how to make this works.
I tried everything, but I just cant. Help me please. Thanks!.
try ChildEventLister class for this task.
mDatabaseEvento =
mDatabaseEvento.addChildEventListener(new ChildEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
System.out.println("Estoy entrando aqui");
Log.i("gguwu", "Ayudaaaa");
GenericTypeIndicator<Map<String,String>> ImagenesType = new GenericTypeIndicator<Map<String, String>>() { };
Map<String,String> Imagenes = dataSnapshot.getValue(ImagenesType);
if (Imagenes!=null ) {
for (String imagen: Imagenes.values()) {
System.out.println(imagen);
viewHolder.setImagen(getApplicationContext(), imagen);
}
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError)
}

FirebaseRecyclerAdapter - populateViewHolder is not populating the data for first time it runs?

FirebaseRecyclerAdapter - populateViewHolder is not populating the data for the first time it runs but when I closed the app and opened it, the data is binded in RecyclerView View Holder.
I am not getting why data is not populating for first time, it is showing blank screen
Here's my MainActivity
mDatabase = FirebaseDatabase.getInstance().getReference();
// [END create_database_reference]
mRecycler = (RecyclerView) findViewById(R.id.recycler_view);
mRecycler.setHasFixedSize(true);
setSupportActionBar(toolbar);
final LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
mRecycler.setLayoutManager(layoutManager);
// Set up FirebaseRecyclerAdapter with the Query
//Query postsQuery = mDatabase.child("EN").child("Courses") ;
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("EN").child("Courses");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Toast.makeText(MainActivity.this, dataSnapshot.toString(), Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(MainActivity.this, databaseError.toString(), Toast.LENGTH_SHORT).show();
}
});
Log.d("ref", String.valueOf(ref));
// Log.d("Query", String.valueOf(postsQuery));
mAdapter = new FirebaseRecyclerAdapter<Course, CourseViewHolder>(Course.class, R.layout.item_home,
CourseViewHolder.class, ref) {
#Override
protected void populateViewHolder(final CourseViewHolder viewHolder, final Course model, final int position) {
viewHolder.bindToPost(model);
}
};
mRecycler.setAdapter(mAdapter);
And the ViewHolder
public class CourseViewHolder extends RecyclerView.ViewHolder {
public TextView titleView;
public TextView descriptionView;
public ImageView IconView;
public TextView lessonCountView;
public CourseViewHolder(View itemView) {
super(itemView);
titleView = (TextView) itemView.findViewById(R.id.title);
descriptionView = (TextView) itemView.findViewById(R.id.description);
//IconView = (ImageView) itemView.findViewById(R.id.star);
}
public void bindToPost(Course post) {
// Log.d("Post", String.valueOf(post));
titleView.setText(post.getName());
descriptionView.setText(post.getDescription());
}
}
My Model Pojo
public class Course {
public String description;
public String title;
public Course() {
// Default constructor required for calls to DataSnapshot.getValue(Post.class)
}
public Course(String title, String description) {
// this.description = author;
this.title = title;
this.description =description;
}
public String getName() {
return title;
}
public String getDescription() {
return description;
}
}
Found the Solution.
The Problem is RecyclerView had a height of wrap_content. So Please make sure your RecyclerView height is set to match_parent. This will fix this issue.
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical" />
If you don't want to use match_parent you shouldn't call mRecycler.setHasFixedSize(true);

Resources