如何在Dart/Flutter中解码从供应商接收的数据?

elcex8rz  于 12个月前  发布在  Flutter
关注(0)|答案(2)|浏览(132)

在Dart/Flutter中,我使用supplies包,尝试解码我收到的数据,例如从以下代码:

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

字符串
我该怎么做呢?谁能给我一个例子,我如何从数据中得到结果Dart对象?我如何打印我得到的结果表?
代码取自文档:https://supabase.com/docs/reference/dart/select
我试着像解码json那样解码它,但它没有工作。

35g0bw71

35g0bw711#

下面是一些解释如何使用供应商数据的代码

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']),
              );
            }),
          );
        },
      ),
    );
  }
}

字符串
详情请参见Use Supabase with Flutter
方法2:使用future builder来获取数据。

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()
}       
}

jslywgbw

jslywgbw2#

我解决了它如下(见下面的注解):

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']),
                 );
               }),
             );
           },
         ),
       );
     }

字符串
请注意:

  • FutureBuilder按预期构建了小部件,这解决了我最初的问题。
  • 点击'Fetch'按钮只是获取数据,不幸的是,我仍然不知道如何解码。作为输出,我得到:“'PostgrestTransformBuilder<List<Map<String,dynamic>>的示例”\n Fetch error:Exception:SyntaxError:Unexpected token ' I ',“Instance o”. is not valid JSON”

相关问题