I try to read a file where i have stored data and to show it on my screen. When I load my App for the first time i get the error shown bellow. After a hot reload my information will be displayed without any error. Do you know why this happens and how I can ensure that my data will be loaded already at the first time?
Maybe it has something to do with calling the state but I don't know. It is the code at the bottom which causes the problem:
child: Text(context.select((FileController controller) => controller.text!)),
import 'package:flutter/material.dart';
import 'package:habit_changer/file-handling/file_controller.dart';
import 'package:habit_changer/main/AddHabitDialog.dart';
import 'package:provider/provider.dart';
import '../utils/Constants.dart';
import 'MainBody.dart';
import 'nav_bar.dart';
void main() {
runApp(MultiProvider(
providers: [ChangeNotifierProvider(create: (_) => FileController())],
child: MaterialApp(home: MyApp())
));
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
context.read<FileController>().readText();
return Scaffold(
appBar: AppBar(
title: const Text('Habits'),
backgroundColor: Constants.appBarColor,
leading: GestureDetector(
onTap: () {
openNavBar();
},
child: Icon(
Icons.menu, // add custom icons also
),
),
actions: <Widget>[
Padding(
padding: EdgeInsets.only(right: 20.0),
child: GestureDetector(
onTap: () {
showDialog(
context: context,
builder: (BuildContext context) =>
AddHabitDialog().buildPopupDialog(context),
);
},
child: Icon(Icons.add),
),
)
],
),
body: Container(
child: Text(context.select((FileController controller) => controller.text!)),
),
);
}
}
Here's the error:
Null check operator used on a null value
The relevant error-causing widget was:
MyApp file:///C:/Projekte/Flutter Projects/habit_changer/lib/main/main.dart:13:30
When the exception was thrown, this was the stack:
#0 MyApp.build.<anonymous closure> (package:habit_changer/main/main.dart:52:82)
#1 SelectContext.select (package:provider/src/inherited_provider.dart:283:32)
#2 MyApp.build (package:habit_changer/main/main.dart:52:29)
#3 StatelessElement.build (package:flutter/src/widgets/framework.dart:4648:28)
#4 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4574:15)
CodePudding user response:
This can happen when your variable is null initially but then receives the value later on. Change the operator to a null check operator:
controller.text ?? ''
This will solve the null exception that you are receiving.