从 Flutter 中的 Future<bool> 函数返回 bool 值

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

我的问题有点类似于我如何从未来中获得我的布尔值但我无法从中得到我的问题的答案。我将该函数放在一个单独的文件中,因为我也想在代码中的其他地方使用它。我正在尝试创建一个函数来检查当前用户是否是文档的创建者。为此,我在函数中使用异步方法,因此它必须是 Future,但如果我运行我的应用程序,我会收到此错误:

我的数据库中的字段userId是定义好的,创建时保存的是作者的userId。

这是功能:

 Future<bool> isUserAuthor(documentId) async {
      var userId = '';
      String? currentUserId = FirebaseAuth.instance.currentUser?.uid;
      var collection = FirebaseFirestore.instance.collection('notes');
      var docSnapshot = await collection.doc(documentId).get();
      if (docSnapshot.exists) {
        userId = docSnapshot.data()?['userId'];
      } else {
        userId = 'no User available';
      }
      if (userId == currentUserId) {
        return true;
      } else {
        return false;
      }
    }

这就是我使用它的地方:

typedef NoteCallback = void Function(CloudNote note);

class NotesListView extends StatelessWidget {
  final Iterable<CloudNote> notes;
  final NoteCallback onDeleteNote;
  final NoteCallback onTap;


  const NotesListView({
    Key? key,
    required this.notes,
    required this.onDeleteNote,
    required this.onTap,
  }) : super(key: key);
  

  

  @override
  Widget build(BuildContext context) {
    
    return ListView.builder(
      itemCount: notes.length,
      itemBuilder: (context, index) {
        final note = notes.elementAt(index);
        bool isvisible = isUserAuthor(note.documentId) as bool;
        return ListTile(
          onTap: () {
            onTap(note);
          },
        
          title: Text(
            note.textJob,
            maxLines: 1,
            softWrap: true,
            overflow: TextOverflow.ellipsis,
          ),
          trailing: 
            Visibility(
              visible: isvisible,
            child:  IconButton(
            
            onPressed: () async {
              
              final shouldDelete = await showDeleteDialog(context);
              if (shouldDelete) {
                onDeleteNote(note);
              }
            },
            icon: const Icon(Icons.delete),
          ),)
           
          
        );
      },
    );
  }
}

如果您对我的代码的其余部分有任何其他疑问,请写信给我。我编程时间不长,因此不知道您还需要什么。

flutter boolean typeerror
1个回答
0
投票

在这种情况下,您需要使用 FutureBuilder

这里是一个链接:https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html

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