9

I am developing an app that has a bottomnavitaionbar with five pages. I use getx. In first page, i am listing data. My problem is that, when i changed data(first page in bottomnavigationbar) manually from database and thn i pass over pages, came back to first page i could not see changes.

Controller;

class ExploreController extends GetxController {
  var isLoading = true.obs;
  var articleList = List<ExploreModel>().obs;

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

  void fetchArticles() async {
    try {
      isLoading(true);
      var articles = await ApiService.fetchArticles();
      if (articles != null) {
        //articleList.clear();
        articleList.assignAll(articles);
      }
    } finally {
      isLoading(false);
    }
    update();
  }
}

and my UI;

body: SafeArea(
        child: Column(
        children: <Widget>[
          Header(),
          Expanded(
            child: GetX<ExploreController>(builder: (exploreController) {
              if (exploreController.isLoading.value) {
                return Center(
                  child: SpinKitChasingDots(
                      color: Colors.deepPurple[600], size: 40),
                );
              }
              return ListView.separated(
                padding: EdgeInsets.all(12),
                itemCount: exploreController.articleList.length,
                separatorBuilder: (BuildContext context, int index) {
4

7 回答 7

11

thanks to @Baker for the right answer. However, if you have a list and in viewModel and want to update that list, just use the list.refresh() when the list updated

RxList<Models> myList = <Models>[].obs;

when add or insert data act like this:

myList.add(newItem);
myList.refresh();
于 2021-04-12T04:36:17.237 回答
9

GetX doesn't know / can't see when database data has changed / been updated.

You need to tell GetX to rebuild when appropriate.

If you use GetX observables with GetX or Obx widgets, then you just assign a new value to your observable field. Rebuilds will happen when the obs value changes.

If you use GetX with GetBuilder<MyController>, then you need to call update() method inside MyController, to rebuild GetBuilder<MyController> widgets.


The solution below uses a GetX Controller (i.e. TabX) to:

  1. hold application state:

    1. list of all tabs (tabPages)
    2. which Tab is active (selectedIndex)
  2. expose a method to change the active/visible tab (onItemTapped())

OnItemTapped()

This method is inside TabX, the GetXController.

When called, it will:

  1. set which tab is visible
  2. save the viewed tab to the database (FakeDB)
  3. rebuild any GetBuilder widgets using update()
  void onItemTapped(int index) {
    selectedIndex = index;
    db.insertViewedPage(index); // simulate database update while tabs change
    update(); // ← rebuilds any GetBuilder<TabX> widget
  }

Complete Example

Copy/paste this entire code into a dart page in your app to see a working BottomNavigationBar page.

This tabbed / BottomNavigationBar example is taken from https://api.flutter.dev/flutter/material/BottomNavigationBar-class.html but edited to use GetX.

import 'package:flutter/material.dart';
import 'package:get/get.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyTabHomePage(),
    );
  }
}

class FakeDB {
  List<int> viewedPages = [0];

  void insertViewedPage(int page) {
    viewedPages.add(page);
  }
}

/// BottomNavigationBar page converted to GetX. Original StatefulWidget version:
/// https://api.flutter.dev/flutter/material/BottomNavigationBar-class.html
class TabX extends GetxController {

  TabX({this.db});

  final FakeDB db;
  int selectedIndex = 0;
  static const TextStyle optionStyle =
  TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
  List<Widget> tabPages;

  @override
  void onInit() {
    super.onInit();
    tabPages = <Widget>[
      ListViewTab(db),
      Text(
        'Index 1: Business',
        style: optionStyle,
      ),
      Text(
        'Index 2: School',
        style: optionStyle,
      ),
    ];
  }

  /// INTERESTING PART HERE ↓ ************************************
  void onItemTapped(int index) {
    selectedIndex = index;
    db.insertViewedPage(index); // simulate database update while tabs change
    update(); // ← rebuilds any GetBuilder<TabX> widget
    // ↑ update() is like setState() to anything inside a GetBuilder using *this*
    // controller, i.e. GetBuilder<TabX>
    // Other GetX controllers are not affected. e.g. GetBuilder<BlahX>, not affected
    // by this update()
    // Use async/await above if data writes are slow & must complete before updating widget. 
    // This example does not.
  }
}

/// REBUILT when Tab Page changes, rebuilt by GetBuilder in MyTabHomePage
class ListViewTab extends StatelessWidget {
  final FakeDB db;

  ListViewTab(this.db);

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: db.viewedPages.length,
      itemBuilder: (context, index) =>
          ListTile(
            title: Text('Page Viewed: ${db.viewedPages[index]}'),
          ),
    );
  }
}


class MyTabHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    Get.put(TabX(db: FakeDB()));

    return Scaffold(
      appBar: AppBar(
        title: const Text('BottomNavigationBar Sample'),
      ),
      body: Center(
        /// ↓ Tab Page currently visible - rebuilt by GetBuilder when 
        /// ↓ TabX.onItemTapped() called
        child: GetBuilder<TabX>(
            builder: (tx) => tx.tabPages.elementAt(tx.selectedIndex)
        ),
      ),
      /// ↓ BottomNavBar's highlighted/active item, rebuilt by GetBuilder when
      /// ↓ TabX.onItemTapped() called
      bottomNavigationBar: GetBuilder<TabX>(
        builder: (tx) => BottomNavigationBar(
          items: const <BottomNavigationBarItem>[
            BottomNavigationBarItem(
              icon: Icon(Icons.home),
              label: 'Home',
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.business),
              label: 'Business',
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.school),
              label: 'School',
            ),
          ],
          currentIndex: tx.selectedIndex,
          selectedItemColor: Colors.amber[800],
          onTap: tx.onItemTapped,
        ),
      ),
    );
  }
}

于 2021-02-12T23:08:13.013 回答
1
 GetX< ExploreController >(builder: (controller) {
        if (controller.isLoading.value) {
          return Center(
            child: SpinKitChasingDots(
                color: Colors.deepPurple[600], size: 40),);
        }
        return ListView.separated(
            padding: EdgeInsets.all(12),
            itemCount: controller.articleList.length,
            separatorBuilder: (BuildContext context, int index) {});
      });
于 2021-02-08T14:26:36.737 回答
1

If you change the value in the database 'manually', you need a STREAM to listen to the change on the database. You can't do:

var articles = await ApiService.fetchArticles();

You need to do something like this:

var articles = await ApiService.listenToArticlesSnapshot();

The way you explained is like if you need the data to refresh after navigating to another page and clicking on a button, then navigating to first page (GetBuilder) OR automatically adds data from the within the first page (Obx). But your case is simple, just retrieve the articles SNAPSHOT, then in the controller onInit, subscribe to the snapshot with the bindStream method, and eventually use the function ever() to react to any change in the observable articleList. Something like this:

于 2021-02-09T07:22:34.053 回答
0

You don't need GetBuilder here, as its not meant for observable variables. Nor do you need to call update() in the fetchArticles function as that's only for use with GetBuilder and non observable variables.

So you had 2 widgets meant to update UI (GetBuilder and Obx) both following the same controller and all you need is just the OBX. So Rahuls answer works, or you can leave the Obx in place, get rid of of the GetBuilder and declare and initialize a controller in the beginning of your build method.

final exploreController = Get.put(ExploreController());

Then use that initialized controller in your OBX widget as the child of your Expanded.


Obx(() => exploreController.isLoading.value
          ? Center(
              child:
                  SpinKitChasingDots(color: Colors.deepPurple[600], size: 40),
            )
          : ListView.separated(
              padding: EdgeInsets.all(12),
              itemCount: exploreController.articleList.length,
              separatorBuilder: (BuildContext context, int index) {},
            ),
    )
于 2021-02-08T17:50:39.130 回答
0
  1. create final exploreController = Get.put(ExploreController());

  2. Add init: ExploreController();

body: SafeArea(
        child: Column(
        children: <Widget>[
          Header(),
          Expanded(
            child: GetX<ExploreController>(builder: (exploreController) {
                             *** here ***
             init: ExploreController();
              if (exploreController.isLoading.value) {
                return Center(
                  child: SpinKitChasingDots(
                      color: Colors.deepPurple[600], size: 40),
                );
              }
              return ListView.separated(
                padding: EdgeInsets.all(12),
                itemCount: exploreController.articleList.length,
                separatorBuilder: (BuildContext context, int index) {
于 2021-06-03T10:16:02.727 回答
0

using GetxBuilder approch on ui side and where you want update simple called built in function update();

于 2021-09-01T08:49:18.187 回答