skip to Main Content

In Dart/Flutter, using the supabase package, I’m trying to decode the data I receive for example from the following code:

final data = await supabase
  .from('countries')
  .select('''
    name,
    cities (
      name
    )
  ''');

How do I do that? Can anyone provide me with an example how I get the resulting Dart objects out of data? How would I e.g. print the table that I get as result?

Code taken from the documentation: https://supabase.com/docs/reference/dart/select

I tried to decode it as if I would decode json but it did not work.

2

Answers


  1. Chosen as BEST ANSWER

    I solved it as follows (see notes below):

       PostgrestTransformBuilder<List<Map<String, dynamic>>> get _future =>
             Supabase.instance.client
                 .from('saved')
                 .select()
                 .eq('profile_id', supabase.auth.currentUser!.id)
                 .order('importance', ascending: false)
                 .limit(2);
       
         void fetchData() async {
           try {
             final data = supabase
                 .from('saved')
                 .select()
                 .eq('profile_id', supabase.auth.currentUser!.id)
                 .order('importance', ascending: false)
                 .limit(2);
             print(data);
             print(jsonDecode(data.toString()));
           } catch (e) {
             print('Fetch error: $e');
           }
         }
       
         @override
         Widget build(BuildContext context) {
           return Scaffold(
             appBar: AppBar(
               title: const Text('Test'),
               actions: [
                 TextButton(
                     onPressed: () => setState(() {}),
                     child: const Text('Refresh')),
                 TextButton(
                     onPressed: () => fetchData(),
                     child: const Text('Fetch data')),
               ],
             ),
             body: FutureBuilder<List<Map<String, dynamic>>>(
               future: _future,
               builder: (context, snapshot) {
                 if (!snapshot.hasData) {
                   return const Center(child: CircularProgressIndicator());
                 }
                 final savedItems = snapshot.data!;
                 return ListView.builder(
                   itemCount: savedItems.length,
                   itemBuilder: ((context, index) {
                     final item = savedItems[index];
                     return ListTile(
                       title: Text(item['pos']),
                     );
                   }),
                 );
               },
             ),
           );
         }
    

    Please note:

    • The FutureBuilder builds the widget as intended. This solves my initial problem.
    • Hitting the 'Fetch' button just gets the data, which unfortunately, I still don't know how to decode. As output I get: "Instance of 'PostgrestTransformBuilder<List<Map<String, dynamic>>>'n Fetch error: FormatException: SyntaxError: Unexpected token 'I', "Instance o"... is not valid JSON"

  2. Here is little code that explain how to use supabase data

    class MyApp extends StatelessWidget {
      const MyApp({Key? key}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return const MaterialApp(
          title: 'Countries',
          home: HomePage(),
        );
      }
    }
    
    class HomePage extends StatefulWidget {
      const HomePage({super.key});
    
      @override
      State<HomePage> createState() => _HomePageState();
    }
    
    class _HomePageState extends State<HomePage> {
      final _future = Supabase.instance.client
          .from('countries')
          .select();
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: FutureBuilder<List<Map<String, dynamic>>>(
            future: _future,
            builder: (context, snapshot) {
              if (!snapshot.hasData) {
                return const Center(child: CircularProgressIndicator());
              }
              final countries = snapshot.data!;
              return ListView.builder(
                itemCount: countries.length,
                itemBuilder: ((context, index) {
                  final country = countries[index];
                  return ListTile(
                    title: Text(country['name']),
                  );
                }),
              );
            },
          ),
        );
      }
    }
    

    See Use Supabase with Flutter for details.

    For fetching data without future builder.
    Method 2.

    class MyApp extends StatelessWidget {
      const MyApp({Key? key}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return const MaterialApp(
          title: 'Countries',
          home: HomePage(),
        );
      }
    }
    
    class HomePage extends StatefulWidget {
      const HomePage({super.key});
    
      @override
      State<HomePage> createState() => _HomePageState();
    }
    
    class _HomePageState extends State<HomePage> {
    List countries = [];
    
    
    @override
    void initState(){
    getCountryData();
    super.initState();
    }
    
    
    void  getCountryData()async{
    List data = await Supabase.instance.client
          .from('countries')
          .select()
    setState((){
    countries.addAll(data);
    });
    
    
    }
    
    
      final _future = Supabase.instance.client
          .from('countries')
          .select();
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body:  countries.isNotEmpty ?ListView.builder(
                itemCount: countries.length,
                itemBuilder: ((context, index) {
                  final country = countries[index];
                  return ListTile(
                    title: Text(country['name']),
                  );
    ):const SizedBox.shrink()
    }       
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search