以异步方式显示来自Firebase的数据-Flutter

q35jwt9p  于 2023-01-05  发布在  Flutter
关注(0)|答案(3)|浏览(113)

我想创建一个配置文件页面,只显示来自用户的信息,但我很难访问数据。当我想使用变量用户时,它显示“未来示例〈Map〈字符串,动态〉〉”
如果我把'小部件构建'在异步我有一个错误消息谁告诉我:“ProfileScreen.build”(“未来函数(BuildContext)”)不是“StatelessWidget.build”(“小部件函数(BuildContext)”)的有效重写。

class ProfileScreen extends StatelessWidget {
  ProfileScreen({super.key});

  @override
  Widget build(BuildContext context) {
    final user = displayUser();
    return Scaffold(
        appBar: AppBar(
          title: Text('Profile'),
        ),
        body: Align(
          alignment: Alignment.topLeft,
          child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Align(
                  alignment: Alignment.topLeft,
                  child: Column(children: [
                    Text('Prénom :${user}\nNom :\nEmail :',
                        textWidthBasis: TextWidthBasis.longestLine),
                  ]),
                )
              ]),
        ),
        persistentFooterButtons: [
          SignOutButton(),
          BottomNavBar(),
        ]);
  }

  // Get user informations
  Future<Map<String, dynamic>> displayUser() async {
    final User? currentUser = FirebaseAuth.instance.currentUser;
    late final userUid = currentUser?.uid;
    late final ref = FirebaseDatabase.instance.ref();
    final resSnapshot = await ref.child('/utilisateur/' + userUid!).get();
    final Map<String, dynamic> user = {};

    if (resSnapshot.exists) {
      user['id'] = userUid;
      for (var value in resSnapshot.children) {
        String key = value.key as String;
        var val = value.value;
        user[key] = val;
      }
    } else {
      print('No data available.');
    }
    print(user); // This print display exactly the informations I want.
    return user;
  }
}

谢谢你的帮助。

zvokhttg

zvokhttg1#

你的displayUserasync函数,你不能在build方法中调用它,你需要像这样使用FutureBuilder

@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Profile'),
      ),
      body: FutureBuilder<Map<String, dynamic>>(
        future: displayUser(),
        builder: (context, snapshot) {
          switch (snapshot.connectionState) {
            case ConnectionState.waiting:
              return Text('Loading....');
            default:
              if (snapshot.hasError) {
                return Text('Error: ${snapshot.error}');
              } else {
                Map<String, dynamic> user = snapshot.data ?? {};

                return Align(
                  alignment: Alignment.topLeft,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Align(
                        alignment: Alignment.topLeft,
                        child: Column(
                          children: [
                            Text(
                              'Prénom :${user}\nNom :\nEmail :',
                              textWidthBasis: TextWidthBasis.longestLine,
                            ),
                          ],
                        ),
                      )
                    ],
                  ),
                );
              }
          }
        },
      ),
      persistentFooterButtons: [
        SignOutButton(),
        BottomNavBar(),
      ],
    );
  }

您可以根据需要自定义加载和错误状态。

bmp9r5qi

bmp9r5qi2#

您可以在initstate中加载user,然后使用setstate设置用户

class ProfileScreen extends StatefulWidget {
  const ProfileScreen({super.key});

  @override
  State<ProfileScreen> createState() => _ProfileScreenState();
}

class _ProfileScreenState extends State<ProfileScreen> {
  Map<String, dynamic>? user;

  @override
  void initState() {
   final User? currentUser = FirebaseAuth.instance.currentUser;
    late final userUid = currentUser?.uid;
    late final ref = FirebaseDatabase.instance.ref();
    final resSnapshot = await ref.child('/utilisateur/' + userUid!).get();
    Map<String, dynamic> temp = {};

    if (resSnapshot.exists) {
      temp['id'] = userUid;
      for (var value in resSnapshot.children) {
        String key = value.key as String;
        var val = value.value;
        temp[key] = val;
      }
    } else {
      print('No data available.');
    }
    print(temp);
    setState((){
    user =temp 
});
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
          child:
              user != {} ? Text(user.toString()!) : const CircularProgressIndicator()),
    );
  }
}
dldeef67

dldeef673#

StatelessWidget更改为StatefulWidget,因为userInteract在配置文件屏幕上,UserInteraction更改将显示在firebase上。

class ProfileScreen extends StatefulWidget{
  ProfileScreen({super.key});

相关问题