I have I think a simple problem but I cannot find the solution for that ...
I use library supabase_flutter
All elements are configured like anonKey
and url
.
I have this code:
import 'package:flutter/material.dart';
class HomeScreen extends StatefulWidget {
const HomeScreen({super.key});
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
List<String> categoryNames = [];
@override
void initState() {
super.initState();
fetchCategories();
}
Future<void> fetchCategories() async {
// Perform the Supabase query
final response = await supabase.from('main_categories').select('name');
print(response);
}
@override
Widget build(BuildContext context) {
print(categoryNames.toString());
return Scaffold(
body: Center(
child: Text(''),
),
);
}
}
So as you can see very simple code. My idea is to add elements from response to my list categoryNames.
I try to use Gemini
& ChatGPT
to help me but all this AI give me code that didn't works.
For example Gemini
say:
Future<void> fetchCategories() async {
try {
// Perform the Supabase query
final response = await supabase.from('main_categories').select('name');
// Access data based on your Supabase version (refer to previous responses)
final List<dynamic> decodedData = response.data; // Or appropriate method
// Extract category names
categoryNames.clear(); // Clear existing categories (optional)
for (final item in decodedData as List<Map<String, dynamic>>) {
categoryNames.add(item['name'] as String);
}
// Update UI (explained in step 2 of previous response)
setState(() {});
} catch (error) {
// Handle database or connection errors here
print("Error fetching categories: $error");
// Show an error message in the UI (explained in step 2)
}
}
my debugger say:
The getter 'data' isn't defined for the type 'List<Map<String, dynamic>>'.
Try importing the library that defines 'data', correcting the name to the name of an existing getter, or defining a getter or field named 'data'.dartundefined_getter
Type: InvalidType
I try to use .read
, .data
etc and I don't know how to do this ...
Please help or explain me where is the problem
Thank you for your help
You can do it like this :
Future<void> fetchCategories() async {
// Perform the Supabase query
final categoriesFetched = await supabase
.from('main_categories')
.select('name')
.withConverter((list) {
return list.map((data) => data['name'] as String).toList();
});
WidgetsBinding.instance.addPostFrameCallback((timeStamp) { // Perform setState safely
setState(() {
categoryNames = List.from(categoriesFetched);
});
});
}
Consider using FutureBuilder
, in this case you can replace :
WidgetsBinding.instance.addPostFrameCallback((timeStamp) { // Perform setState safely
setState(() {
categoryNames = List.from(categoriesFetched);
});
});
to :
setState(() {
categoryNames = List.from(categoriesFetched);
});