フラッターアプリの状態管理として getx を使用しています。しかし、リストの値を更新するのに苦労しています。だから私はisFollowingのパラメータを持つユーザーモデルを持っています。ボタンをクリックすると、 isFollowing 変数が変更され、色が更新されます。しかし、それは起こっていません。最初に状態を注入したので、ウィジェットとして Obx を使用しています。データを取得してフロントエンドに表示することで、すべて正常に機能しています。しかし、リストの値を変更したいのですが、更新されていません。私の最小限の再現可能な例
ホームコントローラー
class HomeController extends GetxController {
var userslist = List<User>().obs;
@override
void onInit() {
fetchUsers();
super.onInit();
}
void fetchUsers() async {
var users= await ApiService().getapidata('${usersurl}feed');
if (users!= null) {
userslist.value= users;
}
}
}
モデル
class User {
User({
this.id,
this.user_name,
this.profile_picture,
this.isFollowing,
});
int id;
String user_name;
String profile_picture;
bool isFollowing;
factory User.fromJson(Map<String, dynamic> json) => User(
id: json["id"],
user_name: json["user_name"],
profile_picture: json["profile_picture"],
isFollowing: json["is_following"],
);
意見
class HomeScreen extends StatelessWidget {
final HomeController homeController = Get.put(HomeController());
@override
Widget build(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
physics: ScrollPhysics(),
child: Obx(
() => ListView.builder(
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
itemCount: homeController.usersList.length,
itemBuilder: (context, index) {
return UserWidget(homeController.usersList[index], index);
},
),
),
),
);
}
}
ユーザーウィジェット
class UserWidget extends StatelessWidget {
final User user;
final int index;
UserWidget (this.user, this.index);
@override
Widget build(BuildContext context) {
return InkWell(
onTap : ()=> user.isFollowing = true // When I click on this the container it shall be updated to yellow
child: Obx( () => Container(
decoration: const BoxDecoration(color: user.isFollowing ? Colors.yellow : Colors.black ), // Here is the update I wanna make
))
);
}
}