Home > Software design >  Supabase on flutter did not return correctly the response
Supabase on flutter did not return correctly the response

Time:06-29

I have several problems with supabase on flutter. I'm trying to get the username of the one who is connected via his id.

Here is what I did:

getUsername() async {
    final user = supabase.auth.currentUser;
    print(user!.id);
    var response = await supabase
        .from("profiles")
        .select("username")
        .eq("id", user!.id)
        .execute();
    print(response.data);
    return response.data.toString();
  }

the print(response.data) returne me : [{username: test}]

When I try to display it on my app, this is what I get [screenshot][1]

My code for print it :

child: Text(
                '$getUsername',

I would like to have only the username (so "test") and not the [{username: ...}] in addition to correcting the problem of displaying weird code in my text

Thank you! [1]: https://i.stack.imgur.com/AEp5O.png

CodePudding user response:

you're giving the Text widget a function reference itself not the function result.

Edit: Preload the username

make a variable in the class (HomePage) and it needs to be a StatefulWidget

late Future<String> username;

@override
void initState() {
  // now use this in the FutureBuilder
  username = getUsername();
  super.initState();
}

first update getUsername to this:

Future<String> getUsername() async {
  final user = supabase.auth.currentUser;
  final response = await supabase.from("profiles")
                   .select("username")
                   .eq("id", user!.id)
                   .execute();
  return response.data![0]['username'];
}

try this:

child: FutureBuilder<String>(
  future: username,
  builder: (context, snapshot) {
    if (snapshot.ConnectionState != ConnectionState.done) {
      return const CircularProgressIndicator();
    } else if (!snapshot.hasError && snapshot.hasData) {
      return Text(snapshot.data!);
    } else {
      return Text('error');
    }
  }
)
  • Related