0

I am reading data from database in word controller class. Then I list the data in the UI with listview.builder. When you add data in the same page, it is not added to the list at the same time. I'm using getx, but I couldn't do this successfully. I do the add with controller.addNote() . I am listing data with historyWordList. I don't know how to use obx and obs. I am sharing the relevant codes here.

Can you help me?

code here : Controller class:

class WordController extends GetxController {
  TextEditingController controllerInput1 = TextEditingController();
  TextEditingController controllerInput2 = TextEditingController();
  var items = <Word>[].obs;
  final translator = GoogleTranslator();


  ekle(Word word) async {
    var val = await WordRepo().add(word);
    showDilog("Kayıt Başarılı");
    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 {
    var list = await WordRepo().getAll();
    print(list);
    // update();
    return list;

  }

  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);

      clear();

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

UI page:

class MainPage extends StatelessWidget {
  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,
          //futureBuilder,
        ],
      ),
    );
  }

  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: 4.0),
            child: _formTextField,
          ),
          Container(
            height: 300,
            child: historyWordList,
          )
        ],
      );
    
      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,
            ],
          ),
        );
      }
    
      get textFormFieldEntr {
        return Flexible(
          child: Container(
            child: TextFormField(
              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),
              ),
            ),
          ),
        );
      }
    
      get textFormField {
        return 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),
            ),
          ),
        );
      }
    }
Salih Balsever
  • 189
  • 1
  • 3
  • 11

1 Answers1

4

Obx is used to to tell the wrapped Widget to rebuild when the observed value (e.g. var items = <Word>[].obs;) being changed.

So, basicly you just need to wrap your ListView.builder with Obx, example:

Obx(
   () => ListView.builder(
      itemCount: controller.items.legth,
      itemBuilder: (context, index) {
           var wordItem = controller.items[index]; // here is your wordItem ready to be used 
      }
   );
)

Hence, your list ListView builder with having a new wordItems from your WordController

Wilyanto Liang
  • 169
  • 2
  • 8
  • I could not do it. Can you explain more ? I am reading the data with the "getir()" method in the controller. – Salih Balsever Sep 12 '21 at 16:33
  • You don't need to make your `getIr` method to return userList, just simply make your method to update your `items` variable, since you are using `obs` (observe) the `items`.. So whenever your `items` value being changed.. the ListView.builder that wrapped into `Obx` will rebuild – Wilyanto Liang Sep 12 '21 at 16:39
  • Okay, you are using WordRepo().getAll() to fetch list of Word right? then all you need to do just update your `items`.. `items.value = await WordRepo().getAll()` – Wilyanto Liang Sep 12 '21 at 16:42
  • After your `items` list being updated.. it will trigger all Obx's child to rebuild (in this case, your ListView.builder) – Wilyanto Liang Sep 12 '21 at 16:43
  • I will do item.value= await Wordrepo.getAll() in getir()? This is how I did it and got an error. – Salih Balsever Sep 12 '21 at 17:03
  • Error: A value of type 'List' can't be assigned to a variable of type 'List'. (Documentation) Try changing the type of the variable, or casting the right-hand type to 'List' code getir method: getir() async { var a= items.value; a= await WordRepo().getAll(); // print(list); update(); return a; } – Salih Balsever Sep 13 '21 at 03:04