flutter open_file 包中出现延迟初始化错误

问题描述 投票:0回答:1

我正在尝试使用 open_file 包在 flutter 中读取 docx/xlsx 文件。在 Debian 12 中运行 flutter 应用程序。

import 'package:flutter/material.dart';
import 'package:open_file/open_file.dart';

class WordViewerPage extends StatelessWidget {
  final String filePath;

  WordViewerPage({required this.filePath});

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<OpenResult>(
      future: OpenFile.open(filePath),
      builder: (BuildContext context, AsyncSnapshot<OpenResult> snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Center(child: CircularProgressIndicator());
        } else if (snapshot.hasError) {
          print('Error occurred: ${snapshot.error}'); // Log the error
          return Center(child: Text("Error: ${snapshot.error}"));
        } else if (snapshot.hasData) {
          // Check if the file opened successfully
          if (snapshot.data?.type == ResultType.done) {
            return const SingleChildScrollView(
              padding: EdgeInsets.all(16.0),
              child: Text("File opened successfully!"),
            );
          } else {
            return Center(
                child: Text("Could not open file: ${snapshot.data?.message}"));
          }
        }
        return const Center(child: Text("Unexpected state."));
      },
    );
  }
}

这是我的完整代码。 这是错误信息


flutter: Error occurred: LateInitializationError: Field '_instance@1198239922' has not been initialized.
flutter dart
1个回答
0
投票
You encounter a LateInitializationError while your flutter app and trying to open docx .xlsx files with the open_file. This problem often occurs when the demanded dependency is not initialized properly or there is some null value that is being accessed too early.

Problem:
You are seeing an error message something like the following, which shows a problem with initializing something, maybe in the open_file package or how the file path is being treated in your application: LateInitializationError: Field '_instance@1198239922' has no

Possible Solutions:
Check File Path and Existence: If it is found that the passed filePath given to OpenFile.open(filePath) does not exist or is inaccessible, then ideally, this check should be done on the file path before passing the same to the open method.

Example:

if (await File(filePath).exists()) {
  return OpenFile.open(filePath);
} else {
  print("File does not exist at: $filePath");
END return OpenResult(type: ResultType.error, message: "File not found"); }


2. **Verify Package Compatibility:**
`open_file` is likely broken on most platforms, at least Debian 12-based Linux. Internally, the package uses platform-dependent mechanisms to open files. You may wish to check whether the package entirely supports Debian or Linux.

Try the file-opening functionality using another file type, or test running the app on another platform (such as Android or Windows) to verify that it is working with the expected behavior of the package.

3. **Alternate Package:**
Sometimes, if `open_file` is not working correctly, there are alternative packages like [https://pub.dev/packages/file_picker](file_picker ), even though they may require more logic for opening the file content.

4. **Initialization Debugging:**
The `LateInitializationError` is probably due to a misunderstanding in the handling of asynchronous code. Refactor your `FutureBuilder` to deal better with asynchronous states.

```dart
Future<OpenResult> openFile() async {
  try {
    return await OpenFile.open(filePath);
  } catch (e) {
    print("Error opening file: $e");
end
return OpenResult(type: ResultType.error, message: e.toString());
   }
 }

 @override
 Widget build(BuildContext context) {
   return FutureBuilder<OpenResult>(
     future: openFile(),
     builder: (context, snapshot) {
       if (snapshot.connectionState == ConnectionState.waiting
return const Center(child: CircularProgressIndicator());
      } else if (snapshot.hasError) {
        return Center(child: Text("Error: ${snapshot.error}"));
      } else if (snapshot.hasData && snapshot.data?.type == ResultType.done)
return const SingleChildScrollView(
          padding: EdgeInsets.all(16.0),
          child: Text("File opened successfully!"),
        );
      } else {
return Center(child: Text("Could not open file: ${snapshot.data?.message}"));
      }
    },
  );
}
Ensure the File Is Not Locked: Keep an eye open for not being in use or locked by another process, otherwise it might not even open.
© www.soinside.com 2019 - 2024. All rights reserved.