Fetch Data from a Wix Database through http request

Issue

I created a database with Wix that has several different types of content like Strings, images, addresses and more.I want to use the information from the WIX database for an app(made with Flutter and Dart); simply portraying the information in a ListView but it seems the data doesnt reach the app.

I created the necessary function on Wix to make the database accessible for third parties and tested it with Postman. When i make the request with this Url (https://daudadmin.editorx.io/acteeventpage/_functions/regions) it works fine and Postman returns the items with all the information as JSON.

Now when i use the Url in my app code; it just returns a blank page. That is the code i use currently:

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final url = 'https://daudadmin.editorx.io/acteeventpage/_functions/regions';
  var _postsJson = [];

  void fetchData() async {
    try {
      final response = await get(Uri.parse(url));
      final jsonData = jsonDecode(response.body) as List;

      setState(() {
        _postsJson = jsonData;
      });
    } catch (err) {
      //handle error here with error message
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    fetchData();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: ListView.builder(
            itemCount: _postsJson.length,
            itemBuilder: (context, i) {
              final post = _postsJson[i];
              return Text("Title: ${post["title"]}");
            }),
      ),
    );
  }
}

Solution

This is the line causing your error

final jsonData = jsonDecode(response.body) as List;

The data being returned from the endpoint is a Map and not a List.

{
  "items": [
    {},
    ...
  ],
}

To access the list, try accessing the items property of the map by changing the declaration to

final jsonData = jsonDecode(response.body)["items"] as List;

Answered By – developerjamiu

Answer Checked By – Senaida (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *