Flutter:读取文件第一次失败但在热重载后有效

Flutter: Read File fails at the first time but works after Hot reload

我尝试读取存储数据的文件并将其显示在屏幕上。当我第一次加载我的应用程序时,出现如下错误。热重载后,我的信息将毫无错误地显示出来。您知道为什么会发生这种情况吗?我如何确保我的数据在第一时间就已加载?

可能和调用状态有关,但我不知道。 导致问题的是底部的代码:

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!)),
      ),
    );
  }
}

这是错误:

Null check operator used on a null value

The relevant error-causing widget was: 
  MyApp file:///C:/Projekte/Flutter%20Projects/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)

当您的变量最初为 null 但稍后收到该值时,可能会发生这种情况。将运算符更改为空检查运算符:

controller.text ?? ''

这将解决您收到的空异常。