flutter 错误:无法使用文件头检测图像文件格式,文件头为[0x3c 0x68 0x74 0x6d 0x6c 0x3e 0x0a 0x20 0x20 0x20]

s3fp2yjn  于 2023-02-05  发布在  Flutter
关注(0)|答案(1)|浏览(158)

我尝试将Firestore中的图像显示到我的UI中。但是它返回了上面的错误,并且当我在Edge上运行它时(而不是在物理设备或Emulator上),文件格式也发生了变化。我不知道是如何做到的。以下是我的代码。

class ViewPola extends StatefulWidget {
  const ViewPola({Key? key}) : super(key: key);

  static String id = 'view_pola';

  @override
  State<ViewPola> createState() => _ViewPolaState();
}

class _ViewPolaState extends State<ViewPola> {
  Function getSnaps = () async {
    final polaMap = {
      'Kode Pola': '',
      'Bagian Pola': '',
      'image_url': '',
    };
    FirebaseFirestore.instance
        .collection('PolaWillyJKT')
        .limit(1)
        .get()
        .then((snapshot) {
      if (snapshot.size == 0) {
        FirebaseFirestore.instance.collection('PolaWillyJKT').add(polaMap);
        FirebaseFirestore.instance.collection('PolaWillyJKT');
        print('add');
      } else {
        print('disini nge get');
        var a = FirebaseFirestore.instance.collection('PolaWillyJKT').get();
        Map<String, dynamic> data = a as Map<String, dynamic>;

        print(data);
      }
    });
  };

  var _selectedItem;
  var _showList = false;

  @override
  void initState() {
    getSnaps();
    super.initState();
  }

  final Stream<QuerySnapshot> _polaWilly =
  FirebaseFirestore.instance.collection('PolaWillyJKT').snapshots();

  @override
  Widget build(BuildContext context) {
    final screenHeight = ScreenInfo.screenHeight(context);
    final screenWidth = ScreenInfo.screenWidth(context);
    return StreamBuilder<QuerySnapshot>(
      stream: _polaWilly,
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (snapshot.hasError) {
          return Text('Something went wrong');
        }

        if (snapshot.connectionState == ConnectionState.waiting) {
          return Text("Loading");
        }

        return SafeArea(
          child: Scaffold(
            body: Padding(
              padding: EdgeInsets.all(25),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  const Text(
                    'Pilih Bagian Pola',
                    style: TextStyle(fontSize: 25),
                  ),
                  const SizedBox(
                    height: 20,
                  ),
                  DropdownButton(
                      isExpanded: true,
                      value: _selectedItem,
                      items: snapshot.data?.docs
                          .map(
                            (value) => DropdownMenuItem(
                          value: value.get("Bagian Pola"),
                          child: Text('${value.get("Bagian Pola")}'),
                        ),
                      )
                          .toList(),
                      onChanged: (newValue) {
                        setState(() {
                          _selectedItem = newValue.toString();
                          _showList = true;
                        });
                      }),
                  Padding(
                    padding: const EdgeInsets.all(25),
                    child: Visibility(
                      visible: _showList,
                      child: Container(
                        height: screenHeight * 0.4,
                        child: ListView(
                          children: snapshot.data!.docs
                              .where(
                                  (e) => e.get("Bagian Pola") == _selectedItem)
                              .map((DocumentSnapshot document) {
                            Map<String, dynamic> data =
                            document.data()! as Map<String, dynamic>;
                            return Center(
                              child: Column(
                                children: [
                                  Text(
                                    'Bagian Pola: ${data["Bagian Pola"]}',
                                    style: TextStyle(fontSize: 15),
                                  ),
                                  const SizedBox(
                                    height: 15,
                                  ),
                                  Text(
                                    'Kode Pola : ${data["Kode Pola"]}',
                                    style: TextStyle(fontSize: 15),
                                  ),
                                  const SizedBox(
                                    height: 15,
                                  ),
                                  Image(
                                    image:
                                    NetworkImage(document.get("Foto Pola")),
                                    height: 200,
                                    width: 200,
                                  ), // this is the Image widget where I tried to put the image from firestore
                                  Text(document.get('Foto Pola').toString()),
                                ],
                              ),
                            );
                          }).toList(),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }
}

下面是将图像上传到Firestore的类

class Input_Pola extends StatefulWidget {
  const Input_Pola({Key? key}) : super(key: key);

  static String id = 'input_pola';

  @override
  State<Input_Pola> createState() => _Input_PolaState();
}

class _Input_PolaState extends State<Input_Pola> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  void _checkDuplicate() {
    if (options.contains(_textfieldValue.text)) {
      // Display bottom sheet that says item already exists
      _scaffoldKey.currentState?.showBottomSheet((context) => Container(
            height: 300,
            child: Column(
              children: [
                const Text('Item already exists'),
                TextButton(
                    onPressed: () {
                      Navigator.pop(context);
                    },
                    child: Text('Dismiss'))
              ],
            ),
          ));
    } else {
      // Add item to options list
      setState(() {
        options.add(_textfieldValue.text);
      });
    }
  }

  XFile? image;

  final ImagePicker picker = ImagePicker();
  String _image_url = '';
  void _addToFirebase(String dropdownValue, String _kodePolaController) {
    var imageFile = File(image!.path);
    String fileName = pth.basename(imageFile.path);
    FirebaseStorage storage = FirebaseStorage.instance;
    Reference ref = storage.ref().child("WillyJKT/polaWillyJKT");
    UploadTask uploadTask = ref.putFile(imageFile);
    uploadTask.whenComplete(() async {
      var url = await ref.getDownloadURL();
      _image_url = url.toString();
    });

    FirebaseFirestore.instance
        .collection('PolaWillyJKT')
        .doc(_selectedOption)
        .set({
      'Bagian Pola': _selectedOption,
      'Kode Pola': _kodePolaController,
      'Foto Pola': _image_url
    });
  }

  String _dropdownValue = 'kg';
  String _property1 = '';
  String _property2 = '';
  String _property3 = '';
  bool _isOptionSelected = false;

  final TextEditingController _kodePolaController = TextEditingController();

  var _selectedOption;
  final TextEditingController _textfieldValue = TextEditingController();
  final List<String> options = [];

  @override
  void initState() {
    super.initState();
    _selectedOption = options.isNotEmpty ? options[0] : null;
  }

  //we can upload image from camera or from gallery based on parameter
  Future getImage(ImageSource media) async {
    var img = await picker.pickImage(source: media);

    setState(() {
      image = img;
    });
  }

  void myAlert() {
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            shape:
                RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
            title: Text('Please choose media to select'),
            content: Container(
              height: MediaQuery.of(context).size.height / 6,
              child: Column(
                children: [
                  ElevatedButton(
                    //if user click this button, user can upload image from gallery
                    onPressed: () {
                      Navigator.pop(context);
                      getImage(ImageSource.gallery);
                    },
                    child: Row(
                      children: [
                        Icon(Icons.image),
                        Text('From Gallery'),
                      ],
                    ),
                  ),
                  ElevatedButton(
                    //if user click this button. user can upload image from camera
                    onPressed: () {
                      Navigator.pop(context);
                      getImage(ImageSource.camera);
                    },
                    child: Row(
                      children: [
                        Icon(Icons.camera),
                        Text('From Camera'),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          );
        });
  }

  @override
  Widget build(BuildContext context) {
    final screenHeight = ScreenInfo.screenHeight(context);
    final screenWidth = ScreenInfo.screenWidth(context);

    return SafeArea(
      child: Scaffold(
        key: _scaffoldKey,
        floatingActionButton: FloatingActionButton(
          child: const Icon(Icons.add),
          onPressed: () {
            _addToFirebase(_dropdownValue, _kodePolaController.text);
          },
        ),
        body: SingleChildScrollView(
          child: Padding(
            padding: const EdgeInsets.all(25),
            child: Container(
              height: screenHeight,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  TextFormField(
                    decoration: const InputDecoration(
                      hintText: 'Input Pola',
                      border: UnderlineInputBorder(),
                    ),
                    onChanged: (value) {
                      setState(() {
                        _textfieldValue.text = value;
                      });
                    },
                  ),
                  DropdownButton<String>(
                    value: _selectedOption,
                    onChanged: (value) {
                      setState(() {
                        _selectedOption = value!;
                        _isOptionSelected = true;
                        _kodePolaController.clear();
                      });
                    },
                    hint: const Text('Input from Text Field Above'),
                    items: options.map((option) {
                      return DropdownMenuItem<String>(
                        value: option,
                        child: Text(option),
                      );
                    }).toList(),
                  ),
                  TextButton(
                    onPressed: _checkDuplicate,
                    child: const Text("Add Option"),
                  ),
                  Visibility(
                    visible: _isOptionSelected,
                    child: Expanded(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: <Widget>[
                          TextField(
                            controller: _kodePolaController,
                            decoration: const InputDecoration(
                                labelText: "Kode Pola"),
                            onChanged: (value) {
                              setState(() {
                                _property1 = value;
                              });
                            },
                          ),
                          const SizedBox(height: 20,),
                          ElevatedButton(
                            onPressed: () {
                              myAlert();
                            },
                            child: Text('Upload Photo'),
                          ),
                          SizedBox(
                            height: 10,
                          ),
                          //if image not null show the image
                          //if image null show text
                          image != null
                              ? Padding(
                                  padding:
                                      const EdgeInsets.symmetric(horizontal: 20),
                                  child: ClipRRect(
                                    borderRadius: BorderRadius.circular(8),
                                    child: Image.file(
                                      //to show image, you type like this.
                                      File(image!.path),
                                      fit: BoxFit.cover,
                                      width: MediaQuery.of(context).size.width,
                                      height: 300,
                                    ),
                                  ),
                                )
                              : const Text(
                                  "No Image",
                                  style: TextStyle(fontSize: 20),
                                ),
                        ],
                      ),
                    ),
                  )
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}

它也会在Edge上显示错误,但当我构建APK并在我的物理设备上运行它时,除了上面的数据外,屏幕上什么也不显示。有什么想法可以解决这个问题吗?

iqjalb3h

iqjalb3h1#

var a = FirebaseFirestore.instance.collection('PolaWillyJKT').get();
这将返回一个promise而不是实际的数据。实际上,当您试图将数据转换为Map时,它仍然可以获取数据。
你可以await

var a = await FirebaseFirestore.instance.collection('PolaWillyJKT').get();
myDoc = a.docs.first();

或者使用一个回调函数,该函数将在集合提取完成后运行:

FirebaseFirestore.instance.collection('PolaWillyJKT').get().then((response) => {
  print(response);
});

相关问题