Thursday, March 7, 2024

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

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

{

Class Variable Access Without Constructure : 

Cteate Instance of class: var student = Student();

Access : student.name.value

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

}

1. Create Class

import 'package:get/get.dart';

class Student {
// without constructor
var name="Avinash".obs;
var age= 25.obs;
}

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});
  var student = Student();

@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.name.value}",
style: TextStyle(fontSize:
24),
)),
SizedBox(
height:
10,
),
Obx(() => Text(
"Age = ${student.age.value}",
style: TextStyle(fontSize:
20),
)),

ElevatedButton(
child: Text(
"Upper Name"),
onPressed: () {

student?.name.value = student.name.value ==student.name.value.toUpperCase()
? student.name.value.toLowerCase()
: student.name.value.toUpperCase();

},
),
],
),
),
),
);
}
}

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