简体   繁体   中英

Conver a stateLessWidget to function

I'm a new flutter developer. I have a code to read data from firebase for one time

this code:

class GetUserName extends StatelessWidget {
  final String documentId;

  GetUserName(this.documentId);

  @override
  Widget build(BuildContext context) {
    CollectionReference users = FirebaseFirestore.instance.collection('users');

    return FutureBuilder<DocumentSnapshot>(
      future: users.doc(documentId).get(),
      builder:
          (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {

        if (snapshot.hasError) {
          return Text("Something went wrong");
        }

        if (snapshot.hasData && !snapshot.data!.exists) {
          return Text("Document does not exist");
        }

        if (snapshot.connectionState == ConnectionState.done) {
          Map<String, dynamic> data = snapshot.data!.data() as Map<String, dynamic>;
          return Text("Full Name: ${data['full_name']} ${data['last_name']}");
        }

        return Text("loading");
      },
    );
  }
}

it's work fine but I want to put these method into my Provider as function like this

Future<DocumentSnapshot> getUserName(String uid) => _database.doc(uid).snapshots();

so I want to put a function into provider class when I call this function it return a field data of this documents... (Replace GetUserName class as shown app, to be a function method only)

so how to write this function and how to call it as a map of data?


Edit:

as shown in this image:

在此处输入图像描述

here I got data as StreamBuilder and its work fine

here the explained method for stream in my provider class

在此处输入图像描述

在此处输入图像描述

as shown in the Following Image

在此处输入图像描述

Map<String, dynamic> data

I use data like

data['username']

it works fine so I want to put in My Provider class a function and returns a String, has two parameters for Example:

Text(myfunction(uid, value)); and it returns a string from (uid), value = data[value]

add it before return HomePage();

auth.userData = data;
return HomePage();

add it in Auth provider

class Auth implements AuthBase {
    Map<String,dynamic>? userData;
    String  getUserName(String parameter) {
    return userData![parameter].toString(); 
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM