当前位置: 首页 > 知识库问答 >
问题:

颤振错误:列表不是类型Map

林龙野
2023-03-14

如果有人知道如何修复这个错误,我会非常感激!我只是想使用API访问网站,saleTitle和saleCode然后显示它。所有的代码都在下面,希望这只是一个我忽略的简单修复

任何想要查看数据结构的人都可以使用API

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

或者这里的Json数据

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

模型

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

屏幕文件

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

共有1个答案

程和蔼
2023-03-14

您可以尝试使用此代码这是您的API调用方法

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

这是您的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...',

            );
            ;
          },
        ),

并从initState()中删除这一行

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

我希望你正在寻找这个答案

 类似资料: