我使用 getx 作为我的 flutter 应用程序的状态管理。但我在更新列表中的值时遇到困难。所以我有一个参数为 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;
}
}
}
Model
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"],
);
View
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
))
);
}
}