I am trying to create notebook with sqlite database in flutter 3.1.0 .
I have problem with initialing my NoteEntityData
with late
and initState()
.
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:samsung_note/Database/database.dart';
import 'package:samsung_note/Screens/edit_screen.dart';
import 'package:samsung_note/app_style.dart';
class DetailsScreen extends StatefulWidget {
final int id;
const DetailsScreen({Key? key, required this.id}) : super(key: key);
@override
State<DetailsScreen> createState() => _DetailsScreenState();
}
class _DetailsScreenState extends State<DetailsScreen> {
late Database _database;
late NoteEntityData _noteData;
@override
void initState() {
super.initState();
_database = Database();
getSingleNote();
}
@override
void dispose() {
_database.close();
super.dispose();
}
@override
Widget build(BuildContext context) {
final time = DateFormat.Hm().format(_noteData.createdTime);
final dateTime = DateFormat.yMMMd().format(_noteData.createdTime);
return Scaffold(
appBar: AppBar(
elevation: 1,
leading: IconButton(
onPressed: () => Get.back(),
icon: const Icon(Icons.arrow_back_ios)),
actions: [
IconButton(
onPressed: () => Get.to(() => const EditScreen()),
icon: const Icon(Icons.edit)),
const SizedBox(width: 10),
_noteData.isImportant
? const Icon(Icons.star, color: Colors.orange)
: const Icon(Icons.star_border),
const SizedBox(width: 10),
IconButton(onPressed: () {}, icon: const Icon(Icons.delete)),
]),
body: Padding(
padding: const EdgeInsets.symmetric(vertical: 32, horizontal: 16),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
_noteData.title,
style: AppStyle.titleTextStyle,
),
const SizedBox(height: 25),
Text(_noteData.description, style: AppStyle.descriptionTextStyle),
const SizedBox(height: 50),
Text(
"Created time: $time",
style: AppStyle.smallTextStyle
.copyWith(fontSize: 16, color: Colors.grey.shade500),
textAlign: TextAlign.end,
),
const SizedBox(height: 10),
Text(
"Created Datetime: $dateTime",
style: AppStyle.smallTextStyle
.copyWith(fontSize: 16, color: Colors.grey.shade500),
textAlign: TextAlign.end,
),
],
),
),
);
}
getSingleNote() async {
_noteData = await _database.getSingleNote(widget.id);
}
}
I know that we can't use async
in initState()
, so I create a Future method to initial my noteData
. but when I run my code , compiler can't understand initialing noteData
and I got this error :
======== Exception caught by widgets library =======================================================
The following LateError was thrown building DetailsScreen(dirty, state: _DetailsScreenState#e1c83):
LateInitializationError: Field '_noteData@861302000' has not been initialized.
The relevant error-causing widget was:
DetailsScreen DetailsScreen:file:///C:/Users/Hp/AndroidStudioProjects/samsung_note/lib/Screens/home_screen.dart:72:51
When the exception was thrown, this was the stack:
#0 _DetailsScreenState._noteData (package:samsung_note/Screens/details_screen.dart)
#1 _DetailsScreenState.build (package:samsung_note/Screens/details_screen.dart:36:41)
#2 StatefulElement.build (package:flutter/src/widgets/framework.dart:4919:27)
#3 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4806:15)
#4 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4977:11)
#5 Element.rebuild (package:flutter/src/widgets/framework.dart:4529:5)
#6 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4787:5)
#7 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4968:11)
#8 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4781:5)
... Normal element mounting (275 frames)
===================================================================================================
here is where I got one note id in HomeScreen
:
Scaffold(
backgroundColor: Colors.grey.shade200,
drawer: const Drawer(),
appBar: AppBar(
elevation: 0,
backgroundColor: Colors.grey.shade200,
title: Text(
"All notes",
style: AppStyle.normalTextStyle.copyWith(fontWeight: FontWeight.w600),
),
actions: [
IconButton(onPressed: () {}, icon: const Icon(Icons.search)),
IconButton(
onPressed: () {}, icon: const Icon(Icons.more_vert_outlined))
],
),
body: FutureBuilder<List<NoteEntityData>>(
future: _database.getAllNotes(),
builder: (context, snapshot) {
final List<NoteEntityData>? notes = snapshot.data;
if (snapshot.connectionState != ConnectionState.done) {
return Center(
child: LoadingAnimationWidget.inkDrop(
color: Colors.deepOrange, size: 200),
);
} else if (snapshot.hasError) {
return Center(
child: Text(snapshot.error.toString()),
);
} else if (notes!.isNotEmpty) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 16),
child: GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2),
itemCount: notes.length,
itemBuilder: (context, index) {
final note = notes[index];
return GestureDetector(
onTap: () => Get.to(() => DetailsScreen(id: note.id)),
child: BaseContainer(note: note));
},
));
}
and I have to mention ALL THIS CODE is for some course and it's Same as teacher Code.. That code it's work just fine but mine has this ERROR .
CodePudding user response:
Try to add setState((){})
to your getSingleNote method
like this :
getSingleNote() async {
setState((){
_noteData = await _database.getSingleNote(widget.id);
});
}
CodePudding user response:
that because getSingleNote
is an async function and when Flutter framwork call build function of your class _noteData
is not initialized.
I think you can use a FutureBuilder
in build function for initialize _noteData
before use it