Flutter -GetX:无法从另一页上使用类的方法

发布于 2025-01-18 03:55:20 字数 12764 浏览 0 评论 0原文

我是DART的新手,一般而言。在YouTube上观看教程后,我制作了此代码。在大多数情况下,我能够自己解决大多数问题,在这里我觉得我需要一些帮助。我已经编写了代码来上传照片,并尝试在另一页上使用该功能,但它不起作用。我需要帮助

这里是我的代码: -

        import 'dart:io';
    
    import 'package:flutter/services.dart';
    
    import '';
    
    import 'package:flutter/material.dart';
    import 'package:image_picker/image_picker.dart';
    import 'package:lms_definer/controllers/profileController.dart';
    import 'package:lms_definer/controllers/textController.dart';
    import 'package:get/get.dart';
    import 'package:lms_definer/model/profileModel.dart';
    import 'package:lms_definer/constants/constants.dart';
    import 'package:cloud_firestore/cloud_firestore.dart';
    import 'package:lms_definer/screens/screens.dart';
    import '../helper/firestore_db.dart';
    import 'package:lms_definer/widgets/photo.dart';
    
    class EditProfile extends StatefulWidget {
      EditProfile({Key? key}) : super(key: key);
    
      @override
      State<EditProfile> createState() => _EditProfileState();
    }
    
    class _EditProfileState extends State<EditProfile> {
     
    
      @override
      Widget build(BuildContext context) {
        var _textController = ProfileEdit();
        final PhotoUpload photo = PhotoUpload();
    
        return Scaffold(
            body: GetX<ProfileController>(
          init: Get.put<ProfileController>(ProfileController()),
          builder: (ProfileController profileController) {
            return Container(
              child: ListView.builder(
                  itemCount: profileController.profiles.length,
                  itemBuilder: (BuildContext context, int i) {
                    final _profileModel = profileController.profiles[i];
                    setTextEditControllerValue(_textController, _profileModel);
    
                    return SafeArea(
                      child: Container(
                        padding: EdgeInsets.all(20),
                        child: Form(
                          child: Column(
                            children: [
                              const SizedBox(
                                height: 20,
                              ),
                              GestureDetector(
                                onTap: () {
                                  photo.photoBottomSheet();
                                },
                                child: CircleAvatar(
                                  radius: 100,
                                  backgroundImage: NetworkImage(
                                      'https://www.alchinlong.com/wp-content/uploads/2015/09/sample-profile.png'),
                                ),
                              ),
                              const SizedBox(
                                height: 40,
                              ),
                              TextFormField(
                                  decoration: const InputDecoration(
                                    labelText: 'First Name',
                                    border: OutlineInputBorder(
                                        borderSide: BorderSide()),
                                  ),
                                  controller: _textController.fNameController),
                              SizedBox(
                                height: 10,
                              ),
                              TextFormField(
                                decoration: const InputDecoration(
                                  labelText: 'First Name',
                                  border:
                                      OutlineInputBorder(borderSide: BorderSide()),
                                ),
                                controller: _textController.lNameController,
                              ),
                              SizedBox(
                                height: 10,
                              ),
                              TextFormField(
                                decoration: const InputDecoration(
                                  labelText: 'Address',
                                  border:
                                      OutlineInputBorder(borderSide: BorderSide()),
                                ),
                                controller: _textController.adressController,
                              ),
                              SizedBox(
                                height: 10,
                              ),
                              TextFormField(
                                decoration: const InputDecoration(
                                  labelText: 'Phone Numbaer',
                                  border:
                                      OutlineInputBorder(borderSide: BorderSide()),
                                ),
                                controller: _textController.phoneController,
                              ),
                              SizedBox(
                                height: 10,
                              ),
                              TextFormField(
                                decoration: const InputDecoration(
                                  labelText: 'School Name',
                                  border:
                                      OutlineInputBorder(borderSide: BorderSide()),
                                ),
                                controller: _textController.sclNameController,
                              ),
                              SizedBox(
                                height: 10,
                              ),
                              TextFormField(
                                decoration: const InputDecoration(
                                  labelText: 'Student Class',
                                  border:
                                      OutlineInputBorder(borderSide: BorderSide()),
                                ),
                                controller: _textController.stdClassController,
                              ),
                              SizedBox(
                                height: 10,
                              ),
                              ElevatedButton(
                                  onPressed: () async {
                                    CircularProgressIndicator();
    
                                    ProfileModel profileModel =
                                        profileModelVal(_textController);
                                    await FirestoreDb.updateProfile(profileModel);
                                    Get.offAll(ProfileScreen());
                                  },
                                  child: Text('Update'))
                            ],
                          ),
                        ),
                      ),
                    );
                  }),
            );
          },
        ));
      }
    
     
    
      ProfileModel profileModelVal(ProfileEdit _textController) {
        final profileModel = ProfileModel(
            firstName: _textController.fNameController.text.trim(),
            lastName: _textController.lNameController.text.trim(),
            parentName: _textController.fatherNameController.text.trim(),
            phoneNumber: _textController.phoneController.text.trim(),
            address: _textController.adressController.text.trim(),
            schoolName: _textController.sclNameController.text.trim(),
            stdClass: _textController.stdClassController.text.trim());
        return profileModel;
      }
    
      void setTextEditControllerValue(
          ProfileEdit _textController, ProfileModel _profileModel) {
        _textController.fNameController.value =
            TextEditingValue(text: _profileModel.firstName);
        _textController.lNameController.value =
            TextEditingValue(text: _profileModel.lastName);
        _textController.fatherNameController.value =
            TextEditingValue(text: _profileModel.parentName);
        _textController.adressController.value =
            TextEditingValue(text: _profileModel.address);
        _textController.phoneController.value =
            TextEditingValue(text: _profileModel.phoneNumber);
        _textController.sclNameController.value =
            TextEditingValue(text: _profileModel.schoolName);
        _textController.stdClassController.value =
            TextEditingValue(text: _profileModel.stdClass);
      }
    
      void clearTextController(ProfileEdit _textController) {
        _textController.fNameController.clear();
        _textController.lNameController.clear();
        _textController.fatherNameController.clear();
        _textController.adressController.clear();
        _textController.phoneController.clear();
        _textController.sclNameController.clear();
        _textController.stdClassController.clear();
      }
    }
    

页面上的文件上传代码是: -

        import 'package:flutter/material.dart';
    import 'package:flutter/services.dart';
    import 'package:image_picker/image_picker.dart';
    import 'dart:io';
    import 'package:get/get.dart';
    import 'package:lms_definer/screens/editProfile.dart';
    
    class PhotoUpload{
    
      Future PickedImage(ImageSource source) async {
        try {
          final image = await ImagePicker()
              .pickImage(source: source, maxWidth: 160, maxHeight: 160);
          if (image == null) return;
    
          final _imgTemp = File(image.path);
        } on PlatformException catch (e) {
          print('failed to Upload $e');
        }
    
    
         photoBottomSheet() {
          Get.bottomSheet(
            Container(
              //color: Colors.white,
              height: 150,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment:
                CrossAxisAlignment.center,
                children: [
                  //Text('Select from source'),
                  GestureDetector(
                    onTap: () =>
                        PickedImage(ImageSource.camera),
                    child: Row(
                      mainAxisAlignment:
                      MainAxisAlignment.center,
                      children: [
                        Icon(
                          Icons.camera,
                          size: 25,
                          color: Colors.white,
                        ),
                        SizedBox(
                          width: 10,
                        ),
                        Text(
                          'Camera',
                          style: TextStyle(fontSize: 25, color: Colors.white),
                        ),
                      ],
                    ),
                  ),
                  SizedBox(
                    height: 10,
                  ),
                  Divider(
                    thickness: 0.5, color: Colors.white,
                  ),
                  SizedBox(
                    height: 10,
                  ),
                  GestureDetector(
                    onTap: () =>
                        PickedImage(ImageSource.gallery),
                    child: Row(
                      mainAxisAlignment:
                      MainAxisAlignment.center,
                      children: [
                        Icon(
                          Icons.image,
                          size: 25,
                          color: Colors.white,
                        ),
                        SizedBox(
                          width: 10,
                        ),
                        Text(
                          'Gallery',
                          style: TextStyle(fontSize: 25, color: Colors.white),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            backgroundColor: Color(0xff2AA8A1),
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
    
          );
        }
      }
    
    }

我遇到的错误是: -

Syncing files to device Android SDK built for x86...
lib/screens/editProfile.dart:69:45: Error: The method 'photoBottomSheet' isn't defined for the class 'PhotoUpload'.
- 'PhotoUpload' is from 'package:lms_definer/widgets/photo.dart' 
('lib/widgets/photo.dart').
Try correcting the name to the name of an existing method, or defining a method named 
'photoBottomSheet'.
                                  photo.photoBottomSheet();
                                        ^^^^^^^^^^^^^^^^

想法是将此功能用作小部件,并且可以在多个位置使用相同的代码。但是我无法以有限的知识自己解决这个问题。请帮忙。

I am very new to Dart, and coding in general. I have produced this code after watching tutorials on YouTube. For the most part, I have been able to troubleshoot most of my problems on my own, here I feel I need some help. I have written code to upload photographs, and trying to use the functionality on another page, but it is not working. I need Help

Here is my Code:-

        import 'dart:io';
    
    import 'package:flutter/services.dart';
    
    import '';
    
    import 'package:flutter/material.dart';
    import 'package:image_picker/image_picker.dart';
    import 'package:lms_definer/controllers/profileController.dart';
    import 'package:lms_definer/controllers/textController.dart';
    import 'package:get/get.dart';
    import 'package:lms_definer/model/profileModel.dart';
    import 'package:lms_definer/constants/constants.dart';
    import 'package:cloud_firestore/cloud_firestore.dart';
    import 'package:lms_definer/screens/screens.dart';
    import '../helper/firestore_db.dart';
    import 'package:lms_definer/widgets/photo.dart';
    
    class EditProfile extends StatefulWidget {
      EditProfile({Key? key}) : super(key: key);
    
      @override
      State<EditProfile> createState() => _EditProfileState();
    }
    
    class _EditProfileState extends State<EditProfile> {
     
    
      @override
      Widget build(BuildContext context) {
        var _textController = ProfileEdit();
        final PhotoUpload photo = PhotoUpload();
    
        return Scaffold(
            body: GetX<ProfileController>(
          init: Get.put<ProfileController>(ProfileController()),
          builder: (ProfileController profileController) {
            return Container(
              child: ListView.builder(
                  itemCount: profileController.profiles.length,
                  itemBuilder: (BuildContext context, int i) {
                    final _profileModel = profileController.profiles[i];
                    setTextEditControllerValue(_textController, _profileModel);
    
                    return SafeArea(
                      child: Container(
                        padding: EdgeInsets.all(20),
                        child: Form(
                          child: Column(
                            children: [
                              const SizedBox(
                                height: 20,
                              ),
                              GestureDetector(
                                onTap: () {
                                  photo.photoBottomSheet();
                                },
                                child: CircleAvatar(
                                  radius: 100,
                                  backgroundImage: NetworkImage(
                                      'https://www.alchinlong.com/wp-content/uploads/2015/09/sample-profile.png'),
                                ),
                              ),
                              const SizedBox(
                                height: 40,
                              ),
                              TextFormField(
                                  decoration: const InputDecoration(
                                    labelText: 'First Name',
                                    border: OutlineInputBorder(
                                        borderSide: BorderSide()),
                                  ),
                                  controller: _textController.fNameController),
                              SizedBox(
                                height: 10,
                              ),
                              TextFormField(
                                decoration: const InputDecoration(
                                  labelText: 'First Name',
                                  border:
                                      OutlineInputBorder(borderSide: BorderSide()),
                                ),
                                controller: _textController.lNameController,
                              ),
                              SizedBox(
                                height: 10,
                              ),
                              TextFormField(
                                decoration: const InputDecoration(
                                  labelText: 'Address',
                                  border:
                                      OutlineInputBorder(borderSide: BorderSide()),
                                ),
                                controller: _textController.adressController,
                              ),
                              SizedBox(
                                height: 10,
                              ),
                              TextFormField(
                                decoration: const InputDecoration(
                                  labelText: 'Phone Numbaer',
                                  border:
                                      OutlineInputBorder(borderSide: BorderSide()),
                                ),
                                controller: _textController.phoneController,
                              ),
                              SizedBox(
                                height: 10,
                              ),
                              TextFormField(
                                decoration: const InputDecoration(
                                  labelText: 'School Name',
                                  border:
                                      OutlineInputBorder(borderSide: BorderSide()),
                                ),
                                controller: _textController.sclNameController,
                              ),
                              SizedBox(
                                height: 10,
                              ),
                              TextFormField(
                                decoration: const InputDecoration(
                                  labelText: 'Student Class',
                                  border:
                                      OutlineInputBorder(borderSide: BorderSide()),
                                ),
                                controller: _textController.stdClassController,
                              ),
                              SizedBox(
                                height: 10,
                              ),
                              ElevatedButton(
                                  onPressed: () async {
                                    CircularProgressIndicator();
    
                                    ProfileModel profileModel =
                                        profileModelVal(_textController);
                                    await FirestoreDb.updateProfile(profileModel);
                                    Get.offAll(ProfileScreen());
                                  },
                                  child: Text('Update'))
                            ],
                          ),
                        ),
                      ),
                    );
                  }),
            );
          },
        ));
      }
    
     
    
      ProfileModel profileModelVal(ProfileEdit _textController) {
        final profileModel = ProfileModel(
            firstName: _textController.fNameController.text.trim(),
            lastName: _textController.lNameController.text.trim(),
            parentName: _textController.fatherNameController.text.trim(),
            phoneNumber: _textController.phoneController.text.trim(),
            address: _textController.adressController.text.trim(),
            schoolName: _textController.sclNameController.text.trim(),
            stdClass: _textController.stdClassController.text.trim());
        return profileModel;
      }
    
      void setTextEditControllerValue(
          ProfileEdit _textController, ProfileModel _profileModel) {
        _textController.fNameController.value =
            TextEditingValue(text: _profileModel.firstName);
        _textController.lNameController.value =
            TextEditingValue(text: _profileModel.lastName);
        _textController.fatherNameController.value =
            TextEditingValue(text: _profileModel.parentName);
        _textController.adressController.value =
            TextEditingValue(text: _profileModel.address);
        _textController.phoneController.value =
            TextEditingValue(text: _profileModel.phoneNumber);
        _textController.sclNameController.value =
            TextEditingValue(text: _profileModel.schoolName);
        _textController.stdClassController.value =
            TextEditingValue(text: _profileModel.stdClass);
      }
    
      void clearTextController(ProfileEdit _textController) {
        _textController.fNameController.clear();
        _textController.lNameController.clear();
        _textController.fatherNameController.clear();
        _textController.adressController.clear();
        _textController.phoneController.clear();
        _textController.sclNameController.clear();
        _textController.stdClassController.clear();
      }
    }
    

The file Upload Code on there page is :-

        import 'package:flutter/material.dart';
    import 'package:flutter/services.dart';
    import 'package:image_picker/image_picker.dart';
    import 'dart:io';
    import 'package:get/get.dart';
    import 'package:lms_definer/screens/editProfile.dart';
    
    class PhotoUpload{
    
      Future PickedImage(ImageSource source) async {
        try {
          final image = await ImagePicker()
              .pickImage(source: source, maxWidth: 160, maxHeight: 160);
          if (image == null) return;
    
          final _imgTemp = File(image.path);
        } on PlatformException catch (e) {
          print('failed to Upload $e');
        }
    
    
         photoBottomSheet() {
          Get.bottomSheet(
            Container(
              //color: Colors.white,
              height: 150,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment:
                CrossAxisAlignment.center,
                children: [
                  //Text('Select from source'),
                  GestureDetector(
                    onTap: () =>
                        PickedImage(ImageSource.camera),
                    child: Row(
                      mainAxisAlignment:
                      MainAxisAlignment.center,
                      children: [
                        Icon(
                          Icons.camera,
                          size: 25,
                          color: Colors.white,
                        ),
                        SizedBox(
                          width: 10,
                        ),
                        Text(
                          'Camera',
                          style: TextStyle(fontSize: 25, color: Colors.white),
                        ),
                      ],
                    ),
                  ),
                  SizedBox(
                    height: 10,
                  ),
                  Divider(
                    thickness: 0.5, color: Colors.white,
                  ),
                  SizedBox(
                    height: 10,
                  ),
                  GestureDetector(
                    onTap: () =>
                        PickedImage(ImageSource.gallery),
                    child: Row(
                      mainAxisAlignment:
                      MainAxisAlignment.center,
                      children: [
                        Icon(
                          Icons.image,
                          size: 25,
                          color: Colors.white,
                        ),
                        SizedBox(
                          width: 10,
                        ),
                        Text(
                          'Gallery',
                          style: TextStyle(fontSize: 25, color: Colors.white),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            backgroundColor: Color(0xff2AA8A1),
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
    
          );
        }
      }
    
    }

The error I am getting is:-

Syncing files to device Android SDK built for x86...
lib/screens/editProfile.dart:69:45: Error: The method 'photoBottomSheet' isn't defined for the class 'PhotoUpload'.
- 'PhotoUpload' is from 'package:lms_definer/widgets/photo.dart' 
('lib/widgets/photo.dart').
Try correcting the name to the name of an existing method, or defining a method named 
'photoBottomSheet'.
                                  photo.photoBottomSheet();
                                        ^^^^^^^^^^^^^^^^

The idea is to use this functionality as a widget and the same code can be used in multiple places. But I am unable to solve the issue by myself with my limited knowledge. Please help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

愛上了 2025-01-25 03:55:20

您可以使用状态管理包。 Provider是flutter推荐的,非常简单易学。

  1. 从 pub.dev 获取最新版本的提供程序(提供程序:^6.0.2)并将其放入您的 pubspec.yaml 中,
dependencies:
  flutter:
    sdk: flutter
provider: ^6.0.2
  1. 扩展该类来创建提供程序类
class MyModel extends ChangeNotifier{
//put your method here
}
  1. 通过在需要的地方使用方法
Provider.of<MyModel>(context,listen: false).yourMethod();
  1. :确保注册main 中的提供程序类:
void main() {
  runApp(
      MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (context) => MyModel()),
    ],
      child:MyApp()),
  );
}

在此处获取更多信息: https://docs.flutter.dev/development/data-and-backend/state-mgmt/simple

You could use a state-management-package. Provider is recommended by flutter and very simple to learn.

  1. get the latest version of provider from pub.dev (provider: ^6.0.2) and put it into your pubspec.yaml
dependencies:
  flutter:
    sdk: flutter
provider: ^6.0.2
  1. create a provider class by extending the class with
class MyModel extends ChangeNotifier{
//put your method here
}
  1. use the method at the place you need it with:
Provider.of<MyModel>(context,listen: false).yourMethod();
  1. make sure to register the provider-class in your main:
void main() {
  runApp(
      MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (context) => MyModel()),
    ],
      child:MyApp()),
  );
}

get more information here: https://docs.flutter.dev/development/data-and-backend/state-mgmt/simple

春风十里 2025-01-25 03:55:20

发生这种情况是因为 photoBottomSheet() 位于 PickedImage() 中。像这样改变你的代码。

class PhotoUpload {
  Future pickedImage() async {
    // Your code
  }

  photoBottomSheet() {
    // Your code
  }
}

It happens because photoBottomSheet() is in the PickedImage(). Change your code like this.

class PhotoUpload {
  Future pickedImage() async {
    // Your code
  }

  photoBottomSheet() {
    // Your code
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文