English 中文(简体)
Flu Flu Flu Flu app
原标题:Facing an error in retrieving or opening the Hive Box in Flutter app

因此,作为项目的一部分,我试图建立一个Hive数据库,储存用户交易的下列细节(除2个用户外,所有用户都将投入)

  1. _userID (uid generated by firebase)
  2. amount (value of transaction - user)
  3. type (Selected value from dropdown box - user)
  4. categoryValue (Selected value from dropdown box - user)
  5. DescriptionValue (String given by user)
  6. DateTime (DateTime.now())

the code associated is as follows

OutlinedButton(
  onPressed: () {
     saveTransaction(
       _userID,
       amount,
       type,
       categoryValue,
       descriptionValue,
       DateTime.now(),
     );
                 

这是一条单独的智能文件界定的相关法典。

void main() async {
  await Hive.initFlutter();
  Hive.registerAdapter(TransactionModelAdapter());
}

void saveTransaction(String userId, double amount, String type, String category, String description, DateTime dateTime) async {
  // Open the Hive box for transactions
  final transactionsBox = await Hive.openBox<TransactionModel>( transactions );

  // Create a new transaction object
  final transaction = TransactionModel()
    ..userId = userId
    ..amount = amount
    ..type = type
    ..category = category
    ..description = description
    ..dateTime = dateTime;

  // Save the transaction to the box
  await transactionsBox.add(transaction);
}

The following is the 方框 model in a seraparate dart file

import  package:hive/hive.dart ;

part  transaction_model.g.dart ; // Generated file name

@HiveType(typeId: 0) // HiveType annotation with typeId
class TransactionModel extends HiveObject {
  @HiveField(0) // HiveField annotation with index
  late String userId; // Unique user ID associated with the transaction

  @HiveField(1) // HiveField annotation with index
  late double amount;

  @HiveField(2)
  late String type; // Type of transaction (e.g., expense, income)

  @HiveField(3)
  late String category; // Category of the transaction

  @HiveField(4)
  late String description; // Description of the transaction

  @HiveField(5)
  late DateTime dateTime; // Date and time of the transaction
}

并且现在,在出现错误的地方,最终实施

void main() async {
  runApp(transactionApp());
  Hive.registerAdapter(TransactionModelAdapter());
  await Hive.initFlutter();
}

class transactionApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: AllTransactionsPage(),
    );
  }
}

class AllTransactionsPage extends StatefulWidget {
  @override
  _AllTransactionsPageState createState() => _AllTransactionsPageState();
}

class _AllTransactionsPageState extends State<AllTransactionsPage> {
  late Box<TransactionModel> transact_box;

  @override
  void initState() {
    super.initState();
    _openBox();
  }

  Future<void> _openBox() async {
    transact_box = await Hive.openBox<TransactionModel>( transactions );
    setState(() {}); // Trigger rebuild after box is initialized
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text( All Transactions Page ),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            // Button onPressed action
            print( Button Pressed );
            print("Number of entries are ${transact_box.length}");
          },
          child: Text( Press Me ),
        ),
      ),
    );
  }
}

This above code was written to check if the entries are being added to the box as desired.

在我点击纽子时,我收到以下错误信息:

error message

问题回答
transact_box = await Hive.openBox<TransactionModel>( transactions );

初始化可能需要一些时间,因为其是一种“合成”操作,这意味着如果你能够进入<条码>翻译_箱<>/代码>,则可能尚未开始。

Dart offers no way to tell if a late variable has been initialized or assigned to. If you access it, it either immediately runs the initializer (if it has one) or throws an exception.

一种可行的解决办法是包装-箱式接触,并尝试捕获:

try {
  print("Number of entries are ${transact_box.length}");
} on Exception catch (e) {
  print("transact_box not initialized");
}

最好的解决办法是完善你的逻辑。 您必须保证在查阅该文本之前先启动transact_ Box





相关问题
Android - ListView fling gesture triggers context menu

I m relatively new to Android development. I m developing an app with a ListView. I ve followed the info in #1338475 and have my app recognizing the fling gesture, but after the gesture is complete, ...

AsyncTask and error handling on Android

I m converting my code from using Handler to AsyncTask. The latter is great at what it does - asynchronous updates and handling of results in the main UI thread. What s unclear to me is how to handle ...

Android intent filter for a particular file extension?

I want to be able to download a file with a particular extension from the net, and have it passed to my application to deal with it, but I haven t been able to figure out the intent filter. The ...

Android & Web: What is the equivalent style for the web?

I am quite impressed by the workflow I follow when developing Android applications: Define a layout in an xml file and then write all the code in a code-behind style. Is there an equivalent style for ...

TiledLayer equivalent in Android [duplicate]

To draw landscapes, backgrounds with patterns etc, we used TiledLayer in J2ME. Is there an android counterpart for that. Does android provide an option to set such tiled patterns in the layout XML?

Using Repo with Msysgit

When following the Android Open Source Project instructions on installing repo for use with Git, after running the repo init command, I run into this error: /c/Users/Andrew Rabon/bin/repo: line ...

Android "single top" launch mode and onNewIntent method

I read in the Android documentation that by setting my Activity s launchMode property to singleTop OR by adding the FLAG_ACTIVITY_SINGLE_TOP flag to my Intent, that calling startActivity(intent) would ...

From Web Development to Android Development

I have pretty good skills in PHP , Mysql and Javascript for a junior developer. If I wanted to try my hand as Android Development do you think I might find it tough ? Also what new languages would I ...

热门标签