【问题标题】:How to access class method from another class in flutter?如何从flutter中的另一个类访问类方法?
【发布时间】:2019-09-24 05:16:55
【问题描述】:

大家好,我是新来的飞镖

我做了图片上传功能

但我在制作过程中遇到了麻烦。

'class pictureBox()' 无法识别 'getImage()' ,,

这是我的全部代码:

class writeprofile extends StatefulWidget {
  @override
  _writeprofileState createState() => _writeprofileState();
}

class _writeprofileState extends State<writeprofile> {
  File _image;


  @override
  Widget build(BuildContext context) {
    Future getImage() async{
      var image= await ImagePicker.pickImage(source: ImageSource.gallery);
      setState(() {
        _image = image;
        print('Image Path $_image');
      });
    }

    Future uploadPic(BuildContext context) async{
      String filName = basename(_image.path);
      StorageReference firebaseStorageRef = FirebaseStorage.instance.ref().child(filName);
      StorageUploadTask uploadTask = firebaseStorageRef.putFile(_image);
      StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
      setState(() {
        print("Profile pic upload !!");
        Scaffold.of(context).showSnackBar(SnackBar(content: Text('Profile pic Upload !!')));
      });
    }


    return Scaffold(
      body: Builder(
        builder: (context)=> Center(
          child: Container(
            child: Container(
              child: Column(
                children: <Widget>[
                  Padding(
                    padding: EdgeInsets.only(top: 70),
                    child: Text(
                      '사진 선택',
                      style: TextStyle(
                        fontSize: 30,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.only(top: 10, bottom: 50),
                    child: Container(
                      height: 1,
                      width: MediaQuery.of(context).size.width / 1.4,
                      color: Colors.black26,
                    ),
                  ),
                  Container(
                    width: MediaQuery.of(context).size.width / 1.5,
                    height: MediaQuery.of(context).size.height / 15,
                    alignment: FractionalOffset.center,
                    decoration: BoxDecoration(
                      color: const Color.fromRGBO(250, 80, 120, 1),
                      borderRadius: BorderRadius.all(const Radius.circular(30)),
                    ),
                    child: Text(
                      "가이드 라인을 읽어주세요 !",
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 20,
                        fontWeight: FontWeight.w300,
                        letterSpacing: 0.3,
                      ),
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(top: 100),
                    child: Row(
                      children: <Widget>[
                        PictureBox(),
                        PictureBox(),
                        PictureBox(),
                      ],
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(top: 10),
                    child: Row(
                      children: <Widget>[
                        PictureBox(),
                        PictureBox(),
                        PictureBox(),
                      ],
                    ),
                  ),
                  InkWell(
                    onTap: (){uploadPic(context);},
                    child: Padding(
                      padding: EdgeInsets.only(top: 50),
                      child: Container(
                        width: MediaQuery.of(context).size.width / 3,
                        height: MediaQuery.of(context).size.height /20,
                        alignment: FractionalOffset.center,
                        decoration: BoxDecoration(
                          color: const Color.fromRGBO(250, 80, 100, 1),
                          borderRadius: BorderRadius.all(const Radius.circular(30)),
                        ),
                        child: Text(
                          "Next",
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 20,
                            fontWeight: FontWeight.w500,
                            letterSpacing: 0.3,
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}

class PictureBox extends StatefulWidget {
  @override
  _PictureBoxState createState() => _PictureBoxState();
}

class _PictureBoxState extends State<PictureBox>{
  @override
  Widget build(BuildContext context) {
    return Container(
      child: InkWell(
        onTap: (){getImage(context);},
        child: Padding(
          padding: EdgeInsets.only(left: 10),
          child:Container(
            width: MediaQuery.of(context).size.width / 3.3,
            height: MediaQuery.of(context).size.height / 7,
            color: Colors.black12,
            child: Center(
              child: (_image!=null)? Image.file(_image, fit:BoxFit.fill)
                  :Icon(
                Icons.camera_alt,
                color: Colors.black26,
              ),
            ),
          ),
        ),
      ),
    );
  }
}

这是我的代码,我想在 PictureBox 中使用'Future getImage()' 如何在 PictureBox 中运行 getImage()?

如何在图片类中使用 getImage?

我有点理解全局键,我尝试了很多方法,但我仍然无法修复我的代码。

【问题讨论】:

    标签: class flutter key global


    【解决方案1】:

    试试这个,我刚刚调整了你的代码。还可以查看用于命名类的 CamelCase 约定。

    class WriteProfile extends StatefulWidget {
     @override
      _WriteProfileState createState() => _WriteProfileState();
    }
    
    class _WriteProfileState extends State< WriteProfile > {
      File _image;
    
    Future getImage(BuildContext context) async {
        var image = await ImagePicker.pickImage(source: ImageSource.gallery);
        setState(() {
          _image = image;
          print('Image Path $_image');
        });
      }
    
    Future uploadPic(BuildContext context) async {
        String filName = basename(_image.path);
        StorageReference firebaseStorageRef =
            FirebaseStorage.instance.ref().child(filName);
        StorageUploadTask uploadTask = firebaseStorageRef.putFile(_image);
        StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
        setState(() {
          print("Profile pic upload !!");
          Scaffold.of(context)
              .showSnackBar(SnackBar(content: Text('Profile pic Upload !!')));
        });
      }
    
    
    
     @override
      Widget build(BuildContext context) {
    
        return Scaffold(
          body: Builder(
            builder: (context) => Center(
              child: Container(
                child: Container(
                  child: Column(
                    children: <Widget>[
    Padding(
                        padding: EdgeInsets.only(top: 70),
                        child: Text(
                          '사진 선택',
                          style: TextStyle(
                            fontSize: 30,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ),
    
                      Padding(
                        padding: EdgeInsets.only(top: 10, bottom: 50),
                        child: Container(
                          height: 1,
                          width: MediaQuery.of(context).size.width / 1.4,
                          color: Colors.black26,
                        ),
                      ),
    
                      Container(
                        width: MediaQuery.of(context).size.width / 1.5,
                        height: MediaQuery.of(context).size.height / 15,
                        alignment: FractionalOffset.center,
                        decoration: BoxDecoration(
                          color: const Color.fromRGBO(250, 80, 120, 1),
                          borderRadius: BorderRadius.all(const Radius.circular(30)),
                        ),
                        child: Text(
                          "가이드 라인을 읽어주세요 !",
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 20,
                            fontWeight: FontWeight.w300,
                            letterSpacing: 0.3,
                          ),
                        ),
                      ),
    
                      Padding(
                        padding: const EdgeInsets.only(top: 100),
                        child: Row(
                          children: <Widget>[
                            _buildPictureBox(),
                            _buildPictureBox(),
                            _buildPictureBox(),
                          ],
                        ),
                      ),
    
                      Padding(
                        padding: const EdgeInsets.only(top: 10),
                        child: Row(
                          children: <Widget>[
                            _buildPictureBox(),
                            _buildPictureBox(),
                            _buildPictureBox(),
                          ],
                        ),
                      ),
    
                      InkWell(
                        onTap: () {
                          uploadPic(context);
                        },
                        child: Padding(
                          padding: EdgeInsets.only(top: 50),
                          child: Container(
                            width: MediaQuery.of(context).size.width / 3,
                            height: MediaQuery.of(context).size.height / 20,
                            alignment: FractionalOffset.center,
                            decoration: BoxDecoration(
                              color: const Color.fromRGBO(250, 80, 100, 1),
                              borderRadius:
                                  BorderRadius.all(const Radius.circular(30)),
                            ),
                            child: Text(
                              "Next",
                              style: TextStyle(
                                color: const Colors.white,
                                fontSize: 20,
                                fontWeight: FontWeight.w500,
                                letterSpacing: 0.3,
                              ),
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),
        );
      }
    
    
      Widget _buildPictureBox() {
        return Container(
          child: InkWell(
            onTap: () {
              getImage(context);
            },
            child: Padding(
              padding: EdgeInsets.only(left: 10),
              child: Container(
                width: MediaQuery.of(context).size.width / 3.3,
                height: MediaQuery.of(context).size.height / 7,
                color: Colors.black12,
                child: Center(
                  child: (_image != null)
                      ? Image.file(_image, fit: BoxFit.fill)
                      : Icon(
                          Icons.camera_alt,
                          color: Colors.black26,
                        ),
                ),
              ),
            ),
          ),
        );
      }
    }
    

    【讨论】:

      【解决方案2】:
       Padding(
                  padding: const EdgeInsets.only(top: 30.0, bottom: 30),
                  child: ClipRRect(
                      borderRadius: new BorderRadius.circular(100.0),
                      child: sampleImage == null
                          ? Container(
                              width: 150.0,
                              height: 150.0,
                              decoration: new BoxDecoration(
                                  color: Colors.white,
                                  border: Border.all(
                                      color: Color.fromRGBO(197, 214, 226, 1.0),
                                      width: 3,
                                      style: BorderStyle.solid),
                                  shape: BoxShape.circle,
                                  image: DecorationImage(
                                      image: AssetImage(
                                        "images/profile.png",
                                      ),
                                      fit: BoxFit.cover,
                                      colorFilter:
                                          ColorFilter.srgbToLinearGamma())))
                          : Container(
                              width: 150.0,
                              height: 150.0,
                              decoration: BoxDecoration(
                                  border: Border.all(
                                      color: Color.fromRGBO(197, 214, 226, 1.0),
                                      width: 3,
                                      style: BorderStyle.solid),
                                  shape: BoxShape.circle,
                                  image: DecorationImage(
                                    image: FileImage(sampleImage),
                                    fit: BoxFit.cover,
                                  )),
                            )),
                ),
                Positioned(
                  bottom: 25,
                  right: 0,
                  child: CircleAvatar(
                    backgroundColor: Colors.white,
                    maxRadius: 25,
                    child: Container(
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        border: Border.all(
                            color: Color.fromRGBO(197, 214, 226, 1.0),
                            width: 3,
                            style: BorderStyle.solid),
                      ),
                      child: IconButton(
                        icon: Icon(
                          Icons.photo_camera,
                          color: Colors.blue,
                          size: 30,
                        ),
                        hoverColor: Colors.blue,
                        onPressed: () {
                          showDialog(
                              context: context,
                              builder: (context) {
                                return AlertDialog(
                                  title: Column(
                                    children: <Widget>[
                                      ListTile(
                                        title: Text('Camera'),
                                        onTap: () async {
                                          Navigator.pop(context);
                                          var tempImage =
                                              await ImagePicker.pickImage(
                                                  source: ImageSource.camera);
      
                                          setState(() {
                                            sampleImage = tempImage;
                                          });
                                        },
                                      ),
                                      ListTile(
                                        title: Text('Gallery'),
                                        onTap: () async {
                                          Navigator.pop(context);
                                          var tempImage =
                                              await ImagePicker.pickImage(
                                                  source: ImageSource.gallery);
      
                                          setState(() {
                                            sampleImage = tempImage;
                                          });
                                        },
                                      ),
                                    ],
                                  ),
                                );
                              });
                        },
                      ),
                    ),
                  ),
                ),
              ],
            ),
      

      请根据您的要求使用以下库

      import 'package:flutter/material.dart';
      import 'package:flutter/services.dart';
      import 'dart:io';
      import 'package:image_picker/image_picker.dart';
      import 'util/CustomIcon.dart';
      

      上传图片代码

      onTap: () async {
                                              Navigator.pop(context);
                                              var tempImage =
                                                  await ImagePicker.pickImage(
                                                      source: ImageSource.gallery,
                                                      imageQuality: 50);
      
                                              sampleImage = tempImage;
                                              StorageReference storageReference =
                                                  FirebaseStorage.instance
                                                      .ref()
                                                      .child("Chatbox")
                                                      .child(
                                                          "$userId${widget.name.userId}${DateTime.now()}");
                                              if (sampleImage != null) {
                                                // Navigator.push(context,MaterialPageRoute(builder: (context)=>PhotoFather(abc: tempImage,)));
                                                StorageUploadTask uploadTask =
                                                    storageReference
                                                        .putFile(sampleImage);
      

      【讨论】:

        猜你喜欢
        • 2017-01-03
        • 1970-01-01
        • 2022-12-05
        • 1970-01-01
        • 2018-10-18
        • 1970-01-01
        • 2021-11-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多