【问题标题】:LateInitializationError: Field 'TaakBeschrijving' has not been initializedLateInitializationError:字段“TaakBeschrijving”尚未初始化
【发布时间】:2022-01-07 15:09:59
【问题描述】:

运行时一切正常,但是当我按下按钮将数据发送到数据库 firebase Firestore 时,我收到此错误 `

  1. 这是我的错误 [VERBOSE-2:ui_dart_state.cc(209)] 未处理的异常:LateInitializationError:字段“TaakBeschrijving”尚未初始化。 #0 _TaakState.TaakBeschrijving(包:cameratest2/Taak.dart) #1 _TaakState.uploadText(包:cameratest2/Taak.dart:72:50) #2 _TaakState.afronden 按钮。 (包:cameratest2/Taak.dart:333:13) #3 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:989:21) #4 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:198:24) #5 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:608:11) #6 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:296:5) #7 BaseTapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:267:7) `
2. this is my code
import 'dart:ui';
import 'package:cameratest2/Homedashboard.dart';
import 'package:cameratest2/model/user_model.dart';
import 'package:firebase_storage/firebase_storage.dart' as firebase_storage;
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/cupertino.dart';
import 'package:image_picker/image_picker.dart';
import 'package:multi_image_picker2/multi_image_picker2.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:firebase_core/firebase_core.dart' as firebase_core;
// import 'package:path_provider/path_provider.dart';


class Taak extends StatefulWidget{

  _TaakState createState() => _TaakState();

}

class _TaakState extends State<Taak> {

  firebase_storage.FirebaseStorage ref =
      firebase_storage.FirebaseStorage.instance;

 // //  late String filePath = uploadFile(filePath) as String;
 //  // String filePath = "IMG_7337.HEIC";
 //  String? downloadURL;
 //
 //    Future uploadfoto() async {
 //      try {
 //         Reference ref = FirebaseStorage.instance.ref("gs://cameratest2-41782.appspot.com");
 //            await ref.putFile(image!);
 //            downloadURL = await ref.getDownloadURL();
 //            print(downloadURL);
 //            //then((value) => print({('het is je gelukt')}));
 //        } on firebase_core.FirebaseException catch (e) {
 //          e.code == 'wat miss gegaan';
 //        }

    //     await firebase_storage.FirebaseStorage.instance.ref().child("fotos")".putFile(fileToUpload)";
    //         // .then((value) => print({('het is je gelukt')}));
    //     } on firebase_core.FirebaseException catch (e) {
    //       e.code == 'wat miss gegaan';
    //     }
    // // File file = File(filePath);
    // // assert(file.absolute.existsSync());
    //
    //   firebase_storage.FirebaseStorage.instance.ref().child("fotos").putFile(image!);
    //     // .then((value) => print({('het is je gelukt')}));
    //
    //   // uploadFile(filePath).then((value) => print({('het is je gelukt')}));

   String? downloadURL;
  
// methode for sending Pictures to to the data base 
   Future<void> uploadPhoto() async {
     firebase_storage.Reference ref = FirebaseStorage.instance.ref().child("images");
     await ref.putFile(image!);
     downloadURL = await ref.getDownloadURL();
     print(downloadURL);
   }

  late final String TaakBeschrijving;
  late final String TaakOplossing;

  // text string mothde to send text data to the database 
  Future<void> uploadText() async {
    String dataUrl = 'data:text/plain;base64,SGVsbG8sIFdvcmxkIQ==';

    try {
      await firebase_storage.FirebaseStorage.instance
          .ref('uploads/hello-world.text').child(TaakBeschrijving!).child(TaakOplossing!)
          .putString(dataUrl, format: firebase_storage.PutStringFormat.dataUrl);
    } on firebase_core.FirebaseException catch (e) {
      // e.g, e.code == 'canceled'
    }
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text('Taak'),),
        body: AnnotatedRegion<SystemUiOverlayStyle>(
            value: SystemUiOverlayStyle.light,
            child: GestureDetector(
                child: Stack(
                    children: <Widget>[Container(
                      height: double.infinity,
                      width: double.infinity,
                      decoration: BoxDecoration(
                          gradient: LinearGradient(
                              begin: Alignment.topCenter,
                              end: Alignment.bottomCenter,
                              colors: [
                                Color(0x66012e67),
                                Color(0x99012e67),
                                Color(0xcc012e67),
                                Color(0xff012e67),
                              ]

                          )),
                      child: SingleChildScrollView(
                        padding: EdgeInsets.symmetric(
                          horizontal: 25,
                          vertical: 10,
                        ),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          children: <Widget>[
                            SizedBox(height: 1,),
                            afrondenbutton(),
                            SizedBox(height: 20,),
                            taakbeschrijving(),
                            SizedBox(height: 30,),
                            taakoplossing(),
                            SizedBox(height: 20,),
                            bewijsmatriaal(),
                            SizedBox(height: 20,),
                            uploadbutton(context),
                            SizedBox(height: 50, width: 100,),
                            screen(context),
                            SizedBox(height: 200, width: 100,),
                            Column(
                              children: [
                                Row(

                                ),
                                Container(
                                  child: buildGridViewimages(
                                  ),
                                ),
                              ],
                            ),
                          ],
                          // Text('',
                          //   style: TextStyle(
                          //     color: Colors.white,
                          //     fontSize: 40,
                          //     fontWeight: FontWeight.bold,

                          // ),),


                          // ],
                        ),
                        // ),
                        // );

                      ),
                    ),
                    ])))

    );
  }


  // Future<void> loadAssets() async {
  //   List<Asset> resultList = <Asset>[];
  //   String error = 'No Error Detected';

  //   resultList = await MultiImagePicker.pickImages(
  //     maxImages: 10,
  //     materialOptions: MaterialOptions(
  //       actionBarColor: "#abcdef",
  //       actionBarTitle: "Example App",
  //       allViewTitle: "All Photos",
  //       useDetailsView: false,
  //       selectCircleStrokeColor: "#000000",
  //     ),
  //   );
  //
  //   setState(() =>
  //   {
  //     this.images = resultList as File?;
  //     error = error;
  //   });z
  // }
  //
  // File? image, images;
  //
  // Future<void> pickImage() async {
  //   final image = await ImagePicker().pickImage(source: ImageSource.gallery);
  //   if (image == null) return;
  //   if (image.path == null) return;
  //
  //   final imageFile = File(image.path);
  //   setState(() => this.image = imageFile);
  //
  // }
  //
  // Future getCamera() async {
  //   final pickedFile = await ImagePicker().pickImage(
  //       source: ImageSource.camera);
  //
  //   setState(() {
  //     if (pickedFile != null) {
  //       image = File(pickedFile.path);
  //     }
  //   });
  // }

//   Future<void> loadAssets() async {
//   List<Asset> resultList = <Asset>[];
//   String error = 'No Error Detected';
//
//   resultList = await MultiImagePicker.pickImages(
//     maxImages: 10,
//     materialOptions: MaterialOptions(
//       actionBarColor: "#abcdef",
//       actionBarTitle: "Example App",
//       allViewTitle: "All Photos",
//       useDetailsView: false,
//       selectCircleStrokeColor: "#000000",
//     ),
//   );
//
//   setState(() => {
//
//     this.images = resultList
//   }
//
//   );
// }

  File? image;
  List<Asset> images = <Asset>[];

  final imagePicker = ImagePicker();
// late List<File> images;

// <vooi>
  Future pickImage() async {
    final pick = await imagePicker.pickImage(source: ImageSource.gallery);

    setState(() {
      if (pick != null) {
        image = File(pick.path);
      }
      else {
        print(Error);
      }
    });

    // final image = await ImagePicker().pickImage(source: ImageSource.gallery);
    // if (image == null) return;
    // if (image.path == null) return;

    // final imageFile = File(image.path);
    // this.image = imageFile;
    // setState(() => this.image = imageFile);
  }

  Future getCamera() async {
    final pickedFile = await ImagePicker().pickImage(
        source: ImageSource.camera);

    setState(() {
      if (pickedFile != null) {
        image = File(pickedFile.path);
      }
    });
  }

  Future<void> loadAssets() async {
    List<Asset> resultList = <Asset>[];

    resultList = await MultiImagePicker.pickImages(
      maxImages: 20,
      enableCamera: true,
      selectedAssets: images,
      cupertinoOptions: CupertinoOptions(takePhotoIcon: "chat"),
      materialOptions: MaterialOptions(
        actionBarColor: "#abcdef",
        actionBarTitle: "Example App",
        allViewTitle: "All Photos",
        useDetailsView: false,
        selectCircleStrokeColor: "#000000",
      ),
    );
    setState(() {
      // uploadFile(filePath);
      images = resultList;
    });
  }

  Widget buildGridViewimages() {
    return Column(
      children: List.generate(images.length, (index) {
        Asset asset = images[index];
        return AssetThumb(
          asset: asset,
          width: 300,
          height: 300,
        );
      }),
    );
  }

  Widget screen(BuildContext context) {
    if (image != null) {
      return
        Image.file(image!);
    } else {
      loadAssets();
      return FlutterLogo();
    }
  }

  // final Winkel store = Winkel();


  Widget afrondenbutton() {
    final ButtonStyle raisedButtonStyle = ElevatedButton.styleFrom(
      onPrimary: Colors.white,
      primary: Colors.green[300],
      minimumSize: Size(260, 36),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.all(Radius.circular(15)),
      ),
    );
    return Container(
      alignment: Alignment.topCenter,
      padding: EdgeInsets.all(20),
      child: ElevatedButton(
        child: const Text('Afronden'),
        style: raisedButtonStyle,
        onPressed: () {
          // if(image != null) {
            uploadText();
          }

          // .store.uploadFile(filePath).then((value) => print('het is je gelukt'));
        ),
    );
  }

  Widget uploadbutton(BuildContext context) {
    final ButtonStyle raisedButtonStyle = ElevatedButton.styleFrom(
      onPrimary: Colors.white,
      primary: Colors.green[300],
      minimumSize: Size(180, 36),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.all(Radius.circular(15)),
      ),
    );
    return Container(
      alignment: Alignment.center,
      padding: EdgeInsets.all(20),
      child: ElevatedButton(
          child: const Text('Uploaden'),
          style: raisedButtonStyle,
          // FlutterLogo();
          onPressed: () {
            showImageSourceActionSheet(context);

            // Image.network(
            //   'https://i0.wp.com/www.joyfromjoyce.nl/wp-content/uploads/2017/07/shutterstock_642124366.jpg?fit=1000%2C667&ssl=1',
            //   width: 100, height: 50,);
            // //       // Image.file(File(imagePath)

          }

      ),

    );
  }

im trying to send data String and pictures to firebase database storage but im getting error with late initialization and null check what is going on so with both ways im getting error is there any other way to solve this please can any one help?

【问题讨论】:

  • 一个简单的技巧就是让它可以为空String? TaakBeschrijving 并在使用它时检查 null。而方法是future 使用FutureBuilder
  • @YeasinSheikh 两种方式都不起作用字符串?最后最后我尝试了这两种方式,我很困惑
  • 希望下面的答案能解决问题,我刚刚阅读了代码文本:D
  • @yeasinSheikh thnx 下面的答案帮助我修复了空字符串错误

标签: firebase flutter


【解决方案1】:

问题出在这个变量声明中的late

late final String TaakBeschrijving;

在这里使用late 是在说:“我现在不知道这个变量的值,但我保证在我读取它之前给它一个值”。然后您的代码继续执行并在获得值之前读取TaakBeschrijving,因此 Flutter 告诉您您违反了承诺。


有几种可能的解决方案:

  1. 在使用之前初始化TaakBeschrijving,正如你使用late所承诺的那样

  2. 使 TaakBeschrijving 可以为空(正如 Yeasin 也评论的那样):

    String? TaakBeschrijving;
    

    所以现在你告诉 Flutter TaakBeschrijving 可能是字符串也可能是 null,Flutter 将帮助你处理所有代码中可能出现的 null。

  3. TaakBeschrijving一个初始值:

    var TaakBeschrijving = "default value";
    

    现在,如果您在更改其值之前阅读TaakBeschrijving,它将具有其默认值。

哪种解决方案最好取决于您的情况。

【讨论】:

  • 我会试试这个 var TaakBeschrijving = "default value";
  • 非常感谢这个解决方案 Empty String 帮我解决了这个问题,我也会用照片尝试一下
猜你喜欢
  • 1970-01-01
  • 2022-07-27
  • 2021-10-27
  • 2021-12-29
  • 2022-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-31
相关资源
最近更新 更多