0

If anyone knows how to fix this error I'm getting would really appreciate it! I just want to use the API to access the website, saleTitle and saleCode then display it. All the code is below, hopefully, it is just a simple fix that I'm overlooking

The API for anyone wanting to see the structure of the data is at

https://script.googleusercontent.com/macros/echo?user_content_key=Y_qRVeSoWYVdwEEUjYAO42F6aIaQNXocQEXoTFW6doAyqKv5l-_jMLFTVLh40To9roCT2UfJUuF3FYokjPQiYV6f8jDWRg7rm5_BxDlH2jW0nuo2oDemN9CCS2h10ox_1xSncGQajx_ryfhECjZEnIn1TJCxqQfxEAsJc2lSbT1MZbMO8nPyQvnvJosQEZ3HULcKeoNsyQ2_x4lfmdk2Asxlkl-knPMyGGaU2pP6Ntk&lib=MJriFg5Yjkb5Wmz0onstjG7LH4UjpOLQo

or the Json data here

[{"Website":"www.google.com","SaleTitle":"Up to 50% Off On All Tests!","SaleCode":"No Code Required!"},{"Website":"Website","SaleTitle":"SaleTitle","SaleCode":"SaleCode"}]

Model

/// SaleAlert is a data class which stores data fields of Sale.
class SaleAlert {
  final String website;
  final String saleTitle;
  final String saleCode;

  SaleAlert({this.website, this.saleTitle, this.saleCode});

  factory SaleAlert.fromJson(Map<String, dynamic> json) {
    return SaleAlert(
      website: json['Website'],
      saleTitle: json['SaleTitle'],
      saleCode: json['SaleCode'],
    );
  }
}

Screen File

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:healthy_start_app/models/sale.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:http/http.dart' as http;

Future<SaleAlert> fetchAlert() async {
  String url =
      'https://script.google.com/macros/s/AKfycbwMcc8DHjHavJayNNJJGdfs0JNkClt3_tanyZ4p91DgcfRO58fi-5yK/exec';
  
  final response = await http.get(url);

  if (response.statusCode == 200) {
    return SaleAlert.fromJson(jsonDecode(response.body));
  } else {
    throw Exception('Failed to find latest allergy alert');
  }
}

class SaleTile extends StatefulWidget {
  @override
  _SaleTileState createState() => _SaleTileState();
}

class _SaleTileState extends State<SaleTile> {
  Future<SaleAlert> futureSaleAlert;

  @override
  void initState() {
    super.initState();
    futureSaleAlert = fetchAlert();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
      },
      child: Container(
        width: MediaQuery.of(context).size.width * 0.95,
        height: 100.0,
        child: Padding(
          padding: const EdgeInsets.all(15.0),
          child: Column(
            children: [
              FutureBuilder<SaleAlert>(
                future: futureSaleAlert,
                builder: (context, snapshot) {
                  if (snapshot.hasData) {
                    return Text(
                      snapshot.data.saleTitle,
                 
                    );
                  } else if (snapshot.hasError) {
                    return Text(
                      snapshot.error.toString(),
                     
                    );
                  }

                  return Text(
                    'Loading...',
                   
                  );
                  ;
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
}

3
  • Can you post some JSON data? Commented Jan 20, 2021 at 14:47
  • @fartem updated the post thanks bro Commented Jan 20, 2021 at 14:48
  • @BillyNoyes please check my answer Commented Jan 20, 2021 at 14:53

1 Answer 1

1

You can try with this code this is your API call method

  Future<List<SaleAlert>> fetchAlert() async {
    String url =
        'https://script.google.com/macros/s/AKfycbwMcc8DHjHavJayNNJJGdfs0JNkClt3_tanyZ4p91DgcfRO58fi-5yK/exec';
    final response = await http.get(url);
    if (response.statusCode == 200) {
      final parsed = json.decode(response.body).cast<Map<String, dynamic>>();
      return parsed.map<SaleAlert>((json) => SaleAlert.fromJson(json)).toList();
    } else {
      throw Exception('Failed to find latest allergy alert');
    }
  }

and this is your FutureBuilder

FutureBuilder<List<SaleAlert>>(
          future: fetchAlert(),
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              return Text(
                snapshot.data[0].saleTitle,

              );
            } else if (snapshot.hasError) {
              return Text(
                snapshot.error.toString(),

              );
            }

            return Text(
              'Loading...',

            );
            ;
          },
        ),

and remove this line from your initState()

  @override
  void initState() {
    super.initState();
   // futureSaleAlert = fetchAlert();  <-- remove
  }

I hope you are looking for this answer

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! Solved it for me, really appreciate your time helping me out
@BillyNoyes if this is worked for you please do upvote and mark it as true for this answer. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.