by runtime everything works fine but when I press on the button to send the data to the database firebase Firestore I get this error `
- this is my error [VERBOSE-2:ui_dart_state.cc(209)] Unhandled Exception: LateInitializationError: Field 'TaakBeschrijving' has not been initialized. #0 _TaakState.TaakBeschrijving (package:cameratest2/Taak.dart) #1 _TaakState.uploadText (package:cameratest2/Taak.dart:72:50) #2 _TaakState.afrondenbutton. (package: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,667&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?
CodePudding user response:
The problem comes from the late in this variable declaration:
late final String TaakBeschrijving;
By using late here you're saying: "I don't know the value of this variable now, but I promise to give it a value before I ever read from it". Then your code goes ahead and reads TaakBeschrijving before it has gotten a value, so Flutter tells you that you broke your promise.
There are a few possible solutions:
Initialize
TaakBeschrijvingbefore using it, as you promised by usinglateMake
TaakBeschrijvingnullable (as Yeasin also commented):String? TaakBeschrijving;So now you're telling Flutter that
TaakBeschrijvingmay either be a string or it may be null, and Flutter will help you deal with the possible null in all of your code.Give
TaakBeschrijvingan initial value:var TaakBeschrijving = "default value";Now if you read
TaakBeschrijvingbefore changing its value, it'll have its default value.
Which of these solutions is best depends on your situation.
