Flutter 返回 Future 的实例<dynamic>尽管使用 async、await 关键字

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

我正在尝试使用 flutter 制作一个基本的银行系统应用程序。我启动了数据库,它正确打印了数据。但是当它在 UI 中显示时,出现了问题,整个应用程序停止并向我显示错误屏幕,显示 Receiver:Instance of Future。我真的尝试了我所知道的一切,但没有任何效果。这是整个项目的 github 链接 https://github.com/YossefAhmed9/Flutter-Projects/tree/bankApp

这是用户界面

    class viewAllcustomers extends StatelessWidget {
     const viewAllcustomers({Key? key});

      @override
    Widget build(BuildContext context) {
   return BlocProvider(
  create: (BuildContext context) => AppCubit()..createDatabase,
  child: BlocConsumer<AppCubit, AppStates>(
    bloc: AppCubit(),
    listener: (context, state) {},
    builder: (context, state) {
      AppCubit cubit = AppCubit.get(context);

      return Scaffold(
        appBar: AppBar(
          title: const Text(
            'All Customers',
            style: TextStyle(fontWeight: FontWeight.w600),
          ),
        ),
        body: SingleChildScrollView(
          child: Column(
            mainAxisSize: MainAxisSize.max,
            children: [
              ListView.separated(
                scrollDirection: Axis.vertical,
                itemCount: 10,
                physics: NeverScrollableScrollPhysics(),
                shrinkWrap: true,
                itemBuilder: (context, index) => GestureDetector(
                  onTap: () {
                    navigateTo(context, transaction());
                  },
                  child: Row(
                    mainAxisSize: MainAxisSize.max,
                    children: [
                      Expanded(
                        child: Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                'Name: ${cubit.createDatabase(index, 'name')}',
                                style: const TextStyle(
                                  overflow: TextOverflow.ellipsis,
                                ),
                              ),
                              Text(
                                'Email: ${cubit.createDatabase(index, 'email')}',
                                style: const TextStyle(
                                  overflow: TextOverflow.ellipsis,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              'Age: ${cubit.createDatabase(index, 'age')}',
                              style: const TextStyle(
                                overflow: TextOverflow.ellipsis,
                              ),
                            ),
                            Text(
                              'Account balance: ${cubit.createDatabase(index, 'balance')}',
                              style: const TextStyle(
                                overflow: TextOverflow.ellipsis,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
                separatorBuilder: (context, index) => separate(),
              ),
            ],
          ),
        ),
      );
    },
  ),
);
 }
}

这是数据库功能

    createDatabase(int index, String key) async {
       database = await openDatabase(
       'task.db',
       version: 1,
     onOpen: (database) async {
    await getDataFromDatabase(database).then((value) {
      print(value[index]['$key']);
    });
    // print('Database opened');
  },
).then((value) async {
  // print('INSERT DONE');
  return database = value;
});
   }

这是从数据库返回数据的函数

       Future<List<Map>> getDataFromDatabase(Database database) async {
emit(GetDataLoading());
final result = await database.rawQuery('SELECT * FROM tasks').then((value) {
  print(value);
  return value;
});
emit(GetDataDone());
return result;
   }




 
flutter dart flutter-dependencies dart-pub sqflite
1个回答
0
投票

您遇到的错误“接收者:Future 的实例”通常发生在您尝试直接在 UI 代码中访问 future 的结果时。在您的代码中,您直接在 UI 中调用 cubit.createDatabase 函数,该函数返回 Future,这导致了错误。

要解决此问题,您应该使用 FutureBuilder 来处理异步操作并在数据可用时更新您的 UI。以下是修改代码的方法:

ListView.separated(
scrollDirection: Axis.vertical,
itemCount: 10, // Replace with the actual number of items
physics: NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemBuilder: (context, index) {
return FutureBuilder(
  future: cubit.getDataFromDatabase(cubit.database),
  builder: (context, snapshot) {
    if (snapshot.connectionState == ConnectionState.waiting) {
      return CircularProgressIndicator(); // Show a loading 
     indicator while waiting for data.
    } else if (snapshot.hasError) {
      return Text('Error: ${snapshot.error}');
    } else {
      final data = snapshot.data as List<Map>;
      final name = data[index]['name'];
      final email = data[index]['email'];
      final age = data[index]['age'];
      final balance = data[index]['balance'];

      return GestureDetector(
        onTap: () {
          navigateTo(context, transaction());
        },
        child: Row(
          mainAxisSize: MainAxisSize.max,
          children: [
            Expanded(
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      'Name: $name',
                      style: const TextStyle(
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                    Text(
                      'Email: $email',
                      style: const TextStyle(
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                  ],
                ),
              ),
            ),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    'Age: $age',
                    style: const TextStyle(
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  Text(
                    'Account balance: $balance',
                    style: const TextStyle(
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      );
    }
  },
);
  },
    separatorBuilder: (context, index) => separate(),
  ),

在此代码中,FutureBuilder 用于处理异步数据库操作并在数据可用时更新 UI。它在等待数据时显示加载指示器,并在发生错误时显示错误消息。一旦数据可用,它就会提取值并将其显示在 UI 中。

© www.soinside.com 2019 - 2024. All rights reserved.