How to usage Obx() with getx in flutter?

Issue

On my UI screen, I have 2 textfields in a column. If textFormFieldEntr is empty, hide textFormFiel. If there is a value in the textFormFieldEntr, let the other textfield be visible. After I set the bool active variable to false in the Controller class, I checked the value in the textFormFieldEntr in the showText class. I’m wrong using obx on the UI screen. The textfields are listed in the _formTextField method. Can you answer by explaining the correct obx usage on the code I shared?

class WordController extends GetxController {
  TextEditingController controllerInput1 = TextEditingController();
  TextEditingController controllerInput2 = TextEditingController();
  bool active = false.obs();

  final translator = GoogleTranslator();
  RxList data = [].obs;

  @override
  void onInit() {
    getir();
    super.onInit();
  }

  void showText() {
    if (!controllerInput1.text.isEmpty) {
      active = true;
    }
  }

  ekle(Word word) async {
    var val = await WordRepo().add(word);
    showDilog("Kayıt Başarılı");
    update();
    return val;
  }

  updateWord(Word word) async {
    var val = await WordRepo().update(word);
    showDilog("Kayıt Başarılı");
    return val;
  }

  deleteWord(int? id) async {
    var val = await WordRepo().deleteById(id!);
    return val;
  }

  getir() async {
    //here read all data from database
    data.value = await WordRepo().getAll();
    print(data);
    return data;
  }

  translateLanguage(String newValue) async {
    if (newValue == null || newValue.length == 0) {
      return;
    }
    List list = ["I", "i"];
    if (newValue.length == 1 && !list.contains(newValue)) {
      return;
    }

    var translate = await translator.translate(newValue, from: 'en', to: 'tr');

    controllerInput2.text = translate.toString();
    //addNote();
    return translate;
  }

  showDilog(String message) {
    Get.defaultDialog(title: "Bilgi", middleText: message);
  }

  addNote() async {
    var word =
    Word(wordEn: controllerInput1.text, wordTr: controllerInput2.text);
    await ekle(word);
    getir();
    clear();
  }

  clear() {
    controllerInput2.clear();
    controllerInput1.clear();
  }

  updateNote() async {
    var word =
    Word(wordEn: controllerInput1.text, wordTr: controllerInput2.text);
    await updateWord(word);
    await getir();
    update();
  }
}

UI:

class MainPage extends StatelessWidget {
  bool _active=false.obs();
  String _firstLanguage = "English";
  String _secondLanguage = "Turkish";
  WordController controller = Get.put(WordController());
  final _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    controller.getir();
    return Scaffold(
      drawer: _drawer,
      backgroundColor: Colors.blueAccent,
      appBar: _appbar,
      body: _bodyScaffold,
      floatingActionButton: _floattingActionButton,
    );
  }

  SingleChildScrollView get _bodyScaffold {
    return SingleChildScrollView(
      child: Column(
        children: [
          chooseLanguage,
          translateTextView,
        ],
      ),
    );
  }

  AppBar get _appbar {
    return AppBar(
      backgroundColor: Colors.blueAccent,
      centerTitle: true,
      title: Text("TRANSLATE"),
      elevation: 0.0,
    );
  }

  get chooseLanguage => Container(
        height: 55.0,
        decoration: buildBoxDecoration,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            firstChooseLanguage,
            changeLanguageButton,
            secondChooseLanguage,
          ],
        ),
      );

  get buildBoxDecoration {
    return BoxDecoration(
      color: Colors.white,
      border: Border(
        bottom: BorderSide(
          width: 3.5,
          color: Colors.grey,
        ),
      ),
    );
  }

  refreshList() {
    controller.getir();
  }

  get changeLanguageButton {
    return Material(
      color: Colors.white,
      child: IconButton(
        icon: Icon(
          Icons.wifi_protected_setup_rounded,
          color: Colors.indigo,
          size: 30.0,
        ),
        onPressed: () {},
      ),
    );
  }

  get secondChooseLanguage {
    return Expanded(
      child: Material(
        color: Colors.white,
        child: InkWell(
          onTap: () {},
          child: Center(
            child: Text(
              this._secondLanguage,
              style: TextStyle(
                color: Colors.blue[600],
                fontSize: 22.0,
              ),
            ),
          ),
        ),
      ),
    );
  }

  get firstChooseLanguage {
    return Expanded(
      child: Material(
        color: Colors.white,
        child: InkWell(
          onTap: () {},
          child: Center(
            child: Text(
              this._firstLanguage,
              style: TextStyle(
                color: Colors.blue[600],
                fontSize: 22.0,
              ),
            ),
          ),
        ),
      ),
    );
  }

  get translateTextView => Column(
        children: [
          Card(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.all(Radius.circular(8.0)),
            ),
            margin: EdgeInsets.only(left: 2.0, right: 2.0, top: 2.0),
            child: _formTextField,
          ),
          Container(
            height: Get.height/1.6,
            child: Obx(() {
              return ListView.builder(
                itemCount: controller.data.length,
                itemBuilder: (context, index) {
                  return Card(
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.all(Radius.circular(5.0)),
                    ),
                    margin: EdgeInsets.only(left: 2.0, right: 2.0, top: 0.8),
                    child: Container(
                      color: Colors.white30,
                      height: 70.0,
                      padding:
                          EdgeInsets.only(left: 8.0, top: 8.0, bottom: 8.0),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisAlignment: MainAxisAlignment.spaceAround,
                            children: [
                              firstText(controller.data, index),
                              secondText(controller.data, index),
                            ],
                          ),
                          historyIconbutton,
                        ],
                      ),
                    ),
                  );
                },
              );
            }),
          )
        ],
      );

  get _formTextField {
    return Form(
      key: _formKey,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(
            color: Colors.white30,
            height: 120.0,
            padding: EdgeInsets.only(left: 16.0, top: 8.0, bottom: 8.0),
            child: Row(

              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                textFormFieldEntr,
                favoriIconButton,
              ],
            ),
          ),
          textFormField //burası kapandı
        ],
      ),
    );
  }



  get textFormFieldEntr {
    return Flexible(
      child: Container(
        child: TextFormField(
          onTap: () {
            showMaterialBanner();
          },
          // onChanged: (text) {
          //   controller.translateLanguage(text);
          // },
          controller: controller.controllerInput1,
          maxLines: 6,
          validator: (controllerInput1) {
            if (controllerInput1!.isEmpty) {
              return "lütfen bir değer giriniz";
            } else if (controllerInput1.length > 22) {
              return "en fazla 22 karakter girebilirsiniz";
            }
            return null;
          },
          decoration: InputDecoration(
            hintText: "Enter",
            contentPadding: const EdgeInsets.symmetric(vertical: 5.0),
          ),
        ),
      ),
    );
  }

  void showMaterialBanner() {
    ScaffoldMessenger.of(Get.context!).showMaterialBanner(MaterialBanner(
        backgroundColor: Colors.red,
        content: Padding(
          padding: const EdgeInsets.only(top: 30.0),
          child: Column(
            children: [
              TextFormField(
                controller: controller.controllerInput1,
                maxLines: 6,

                onChanged: (text) {
                  controller.translateLanguage(text);
                  controller.showText();
                },
                validator: (controllerInput2) {
                  if (controllerInput2!.length > 22) {
                    return "en fazla 22 karakter girebilirsiniz";
                  }
                  return null;
                },
                decoration: InputDecoration(
                  suffixIcon: IconButton(onPressed: () {
                    FocusScope.of(Get.context!).unfocus();
                    closeBanner();
                  }, icon: Icon(Icons.clear),),
                  contentPadding: const EdgeInsets.symmetric(vertical: 5.0),
                ),
              ),
              SizedBox(height: 80.0),
              TextFormField(
                controller: controller.controllerInput2,
                maxLines: 6,
                validator: (controllerInput2) {
                  if (controllerInput2!.length > 22) {
                    return "en fazla 22 karakter girebilirsiniz";
                  }
                  return null;
                },
                decoration: InputDecoration(
                  contentPadding: const EdgeInsets.symmetric(vertical: 5.0),
                ),
              ),
            ],
          ),
        ),
        actions: [
          IconButton(
            onPressed: () {


              closeBanner();
            },
            icon: Icon(
              Icons.arrow_forward_outlined,
              color: Colors.indigo,
              size: 36,
            ),
          ),
        ]));
  }

  void closeBanner() {
    ScaffoldMessenger.of(Get.context!).hideCurrentMaterialBanner();
  }


// }  controller.controllerInput1.text==""?_active=false: _active=true;

  get textFormField {
    return Visibility(
      visible: controller.active,
      child: Container(
        color: Colors.white30,
        height: 120.0,
        padding: EdgeInsets.only(left: 16.0, right: 42.0, top: 8.0, bottom: 8.0),
        child: Container(
          child: TextFormField(
            controller: controller.controllerInput2,
            maxLines: 6,
            validator: (controllerInput2) {
              if (controllerInput2!.length > 22) {
                return "en fazla 22 karakter girebilirsiniz";
              }
              return null;
            },
            decoration: InputDecoration(
              contentPadding: const EdgeInsets.symmetric(vertical: 5.0),
            ),
          ),
        ),
      ),
    );
  }

  FutureBuilder<dynamic> get historyWordList {
    return FutureBuilder(
      future: controller.getir(),
      builder: (context, AsyncSnapshot snapShot) {
        if (snapShot.hasData) {
          var wordList = snapShot.data;
          return ListView.builder(
            itemCount: wordList.length,
            itemBuilder: (context, index) {
              return Card(
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.all(Radius.circular(5.0)),
                ),
                margin: EdgeInsets.only(left: 8.0, right: 8.0, top: 0.8),
                child: Container(
                  color: Colors.white30,
                  height: 70.0,
                  padding: EdgeInsets.only(left: 8.0, top: 8.0, bottom: 8.0),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        children: [
                          firstText(wordList, index),
                          secondText(wordList, index),
                        ],
                      ),
                      historyIconbutton,
                    ],
                  ),
                ),
              );
            },
          );
        } else {
          return Center();
        }
      },
    );
  }

  IconButton get historyIconbutton {
    return IconButton(
      onPressed: () {},
      icon: Icon(Icons.history),
      iconSize: 30.0,
    );
  }

  Text firstText(wordList, int index) {
    return Text(
      "İngilizce: ${wordList[index].wordEn ?? ""}",
      style: TextStyle(
        fontWeight: FontWeight.w600,
      ),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );
  }

  Text secondText(wordList, int index) {
    return Text(
      "Türkçe: ${wordList[index].wordTr ?? ""}",
      style: TextStyle(
        fontWeight: FontWeight.w400,
      ),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );
  }

  get favoriIconButton {
    return IconButton(
      alignment: Alignment.topRight,
      onPressed: () async {
        bool validatorKontrol = _formKey.currentState!.validate();
        if (validatorKontrol) {
          String val1 = controller.controllerInput1.text;
          String val2 = controller.controllerInput2.text;
          print("$val1 $val2");
          await controller.addNote();
          await refreshList();
        }
        await Obx(() => textFormField(
              controller: controller.controllerInput2,
            ));
        await Obx(() => textFormField(
              controller: controller.controllerInput1,
            ));
      },
      icon: Icon(
        Icons.forward,
        color: Colors.blueGrey,
        size: 36.0,
      ),
    );
  }

  FloatingActionButton get _floattingActionButton {
    return FloatingActionButton(
      onPressed: () {
        Get.to(WordListPage());
      },
      child: Icon(
        Icons.app_registration,
        size: 30,
      ),
    );
  }

  Drawer get _drawer {
    return Drawer(
      child: ListView(
        // Important: Remove any padding from the ListView.
        padding: EdgeInsets.zero,
        children: <Widget>[
          userAccountsDrawerHeader,
          drawerFavorilerim,
          drawersettings,
          drawerContacts,
        ],
      ),
    );
  }

  ListTile get drawerContacts {
    return ListTile(
      leading: Icon(Icons.contacts),
      title: Text("Contact Us"),
      onTap: () {
        Get.back();
      },
    );
  }

  ListTile get drawersettings {
    return ListTile(
      leading: Icon(Icons.settings),
      title: Text("Settings"),
      onTap: () {
        Get.back();
      },
    );
  }

  ListTile get drawerFavorilerim {
    return ListTile(
      leading: Icon(
        Icons.star,
        color: Colors.yellow,
      ),
      title: Text("Favorilerim"),
      onTap: () {
        Get.to(FavoriListPage());
      },
    );
  }

  UserAccountsDrawerHeader get userAccountsDrawerHeader {
    return UserAccountsDrawerHeader(
      accountName: Text("UserName"),
      accountEmail: Text("E-mail"),
      currentAccountPicture: CircleAvatar(
        backgroundColor: Colors.grey,
        child: Text(
          "",
          style: TextStyle(fontSize: 40.0),
        ),
      ),
    );
  }
}

Solution

You can simple do it like this

class ControllerSample extends GetxController{

 final active = false.obs

 functionPass(){
   active(!active.value);
  }

}

on page

 final sampleController = Get.put(ControllerSample());

 Obx(
 ()=> Form(
   key: yourkeyState,
   child: Column(
     children: [
       TextFormField(
        //some other needed
        //put the function on onChanged
        onChanged:(value){
              if(value.isEmpty){
                sampleController.functionPass(); 
              }else{
              sampleController.functionPass(); 
         }
             }
        ),
       Visibility(
        visible: sampleController.active.value,
        child: TextFormField(
          //some other info
          )
        ),
     ]
   )
  )
)

Answered By – Arbiter Chil

Answer Checked By – Katrina (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.