繁体   English   中英

getx obx 不更新头像图像 - Flutter GetX

[英]getx obx not updating avatar image - Flutter GetX

我想要实现的是在选择图像时更改CircleAvatar中的图像,这是代码:

ProfileController

class ProfileController extends GetxController {
  final TextEditingController emailController = TextEditingController();
  final ImagePicker _picker = ImagePicker();
  Rx<String?> avatarPath = null.obs;


  avatarFromCamera() async {
    var localAvatar = await _picker.pickImage(
        source: ImageSource.camera, imageQuality: 50
    );

    if (localAvatar != null) {
      avatarPath = localAvatar.path.obs;
      update();
    }
  }

  avatarFromGallery() async {
    var localAvatar = await  _picker.pickImage(
        source: ImageSource.gallery, imageQuality: 50
    );

    if (localAvatar != null) {
      avatarPath = localAvatar.path.obs;
      update();
    }
  }

 String? emailValidator(String? value) {
    if (value == null || value.isEmpty) {
      return null;
    }

    if (!EmailValidator.validate(value, false)) {
      return 'Invalid email address';
    }
  }

  @override
  void onClose() {
    emailController.dispose();
    super.onClose();
  }

  String? emailValidator(String? value) {
    if (value == null || value.isEmpty) {
      return null;
    }

    if (!EmailValidator.validate(value, false)) {
      return 'Invalid email address';
    }
  }

 void save(GlobalKey<FormState> profileFormKey) {
    if (profileFormKey.currentState!.validate()) {
      print('valid');
    }
  }
}

这是ProfileScreen小部件:

lass ProfileScreen extends StatelessWidget {
  final ProfileController _profileController = Get.put<ProfileController>(ProfileController());
  GlobalKey<FormState> profileFormKey = GlobalKey<FormState>();

  ProfileScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Update user details'),
      ),
      body: SingleChildScrollView(
        child: Form(
          key: profileFormKey,
          child: Column(
          children: [
            Padding(
              padding: const EdgeInsets.all(30.0),
              child: TextFormField(
                keyboardType: TextInputType.text,
                controller: _profileController.emailController,
                decoration: const InputDecoration(
                  labelText: 'Enter email',
                ),
                validator: _profileController.emailValidator,
              ),
            ),
            Center(
              child: GestureDetector(
                onTap: () {
                  showModalBottomSheet(
                      context: context,
                      builder: (BuildContext bc) {
                        return SafeArea(
                          child: Wrap(
                            children: <Widget>[
                               ListTile(
                                  leading: const Icon(Icons.photo_library),
                                  title: const Text('Photo Library'),
                                  onTap: () {
                                    _profileController.avatarFromGallery();
                                    Navigator.of(context).pop();
                                  }),
                               ListTile(
                                leading: const Icon(Icons.photo_camera),
                                title: const Text('Camera'),
                                onTap: () {
                                  _profileController.avatarFromCamera();
                                  Navigator.of(context).pop();
                                },
                              ),
                            ],
                          ),
                        );
                      }
                  );
                },
                child:  CircleAvatar(
                  radius: 55,
                  backgroundColor: Colors.pink,
                  child: Obx(() =>(_profileController.avatarPath.value != null)
                      ? ClipRRect(
                    borderRadius: BorderRadius.circular(50),
                    child: Image.file(
                      File(_profileController.avatarPath.value!),
                      width: 100,
                      height: 100,
                      fit: BoxFit.fitHeight
                    ),
                  )
                      : Container(
                    decoration: BoxDecoration(
                        color: Colors.grey[200],
                        borderRadius: BorderRadius.circular(50)),
                    width: 100,
                    height: 100,
                    child: Icon(
                      Icons.camera_alt,
                      color: Colors.grey[800],
                    ),
                  ),
                ),
              ),
            )),
            Container(
              margin: const EdgeInsets.all(10),
              width: double.infinity,
              child: MaterialButton(
                color: Colors.blue,
                onPressed: () => _profileController.save(profileFormKey),
                child: const Text(
                  'Submit',
                  style: TextStyle(color: Colors.white),
                ),
              ),
            ),
          ],
        ),
        ),
      ),
    );
  }
}

如您所见,我有Obx和我的avatarPath响应式,并且在我更改它的任何地方我都在运行update ,但它没有更新。 我还尝试使用空字符串作为imagePath的初始值,例如Rx<String> avatarPath = ''.obs; 它不工作。 我做错了什么??? 谢谢指教!!!

有两点需要修改。 首先,更改avatarPath = localAvatar.path.obs; with avatarPath.value = localAvatar.path; . 因为localAvatar.path.obs创建了新的 observable 并且更改不会反映给以前的观察者。

其次,创建一个新的无状态小部件,该小部件具有底部工作表构建器的小部件树,例如

showModalBottomSheet(
  context: context,
  builder: (BuildContext bc) {
        return CustomBottomView();
  }
);

然后在CustomBottomView复制您的底部工作表小部件树。

class CustomBottomView extends GetView<ProfileController> {
  return YourBottomSheetWidgetTreeHere();
}

不要担心 ProfileController 在这里。 您已经在之前的路线中将其放入 DI 中。 如果您仍然遇到问题,请先执行第一步,第二步肯定会解决它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM