Thursday, March 7, 2024

Make custom class Observable or Reactive with Constructure (GET X)

Make custom class Observable or Reactive without Constructure (GET X) 


{

Class Variable Access Without Constructure : 

Cteate Instance of class: final student=Student(name: "Avi",age: 26).obs;

Access : student.value.name

                Obx(() => Text(
"Name is ${student.value.name}",
style: TextStyle(fontSize:
24),
)),

}

1. Create Class

import 'package:get/get.dart';
class Student {

// with constructor
RxString name="".obs;
RxInt age=0.obs;

Student({required String name, required int age}) {
this.name.value = name;
this.age.value = age;
}
}

2. Calling

import 'package:flutter/material.dart';
import
'package:get/get.dart';
import
'package:getx/model/student.dart';
import
'package:getx/page/student_page.dart';

void main() {
runApp(GetMaterialApp(
debugShowCheckedModeBanner:
false,
home: MyApp(),
));
}

class MyApp extends StatelessWidget {
MyApp({
super.key});
  final student=Student(name: "Avi",age: 26).obs;

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
"Get X"),
backgroundColor: Colors.redAccent,
),
body: SafeArea(
child: SingleChildScrollView(
child: Column(
children: [
Text(
"Welcome Avinash in Get X Tutorials"),
Obx(() => Text(
"Name is ${student.value.name}",
style: TextStyle(fontSize:
24),
)),
SizedBox(
height:
10,
),
Obx(() => Text(
"Age = ${student.value.age}",
style: TextStyle(fontSize:
20),
)),

ElevatedButton(
child: Text(
"Upper Name"),
onPressed: () {
tudent.update((student) {
                 student?.name.value = student.name.value ==student.name.value.toUpperCase()
            ? student.name.value.toLowerCase()
            : student.name.value.toUpperCase();
              });
                or
            student.refresh(): // for update value
; },
),
],
),
),
),
);
}
}

No comments:

Post a Comment

Featured post

Compress Image With Show File Size & Resolution in Flutter

 Compress Image With Show File Size & Resolution  1.Multiple File Image Compress with file Size import 'dart:io' ; import 'p...

LightBlog