flutter 如何显示来自API的数据,在提供程序中并调用它

hzbexzde  于 2022-12-14  发布在  Flutter
关注(0)|答案(1)|浏览(123)

如何显示来自API的数据,在提供程序中并调用它
Myapi配置

static Future<ListWisata?> getWisata() async {
    Response? result;
    try {
      result = await Dio().get('https://windramayu-api-default-rtdb.asia-southeast1.firebasedatabase.app/');
      print('getWisata: ${result.data}');
    } catch (e) {
      (e.toString());
    }
    if (result != null) {
      return ListWisata.fromJson(result.data);
    }
    return null;
  }

我的json代码包含旅游地点的数据Map

{
  "datawisata": [
    {
      "about": "Sebagai tempat wisata yang menarik dan unik, Wisata Pohon Randu Gede memiliki cerita tersendiri. Konon taman wisata yang satu ini merupakan pohon mistis yang seringkali dijadikan sebagai spot gambar yang kekinian. Karena pohon randu gede sudah ada sejak ribuan tahun lalu dengan ketinggian sekitar 100 meter dan diameter sekitar 20 meter.",
      "alamat": "Jl. Letnan Sutejo, Margadadi, Kec. Indramayu, Kab. Indramayu, Jawa Barat.",
      "hari": "Setiap Hari",
      "id": 1,
      "img": [
        "https://www.javatravel.net/wp-content/uploads/2019/08/Wisata-Pohon-Randu-Gede-1.jpg",
        "https://www.javatravel.net/wp-content/uploads/2019/08/Wisata-Pohon-Randu-Gede-1.jpg"
      ],
      "jam": "24 Jam",
      "kategori": "Wisata Alam",
      "lat": -6.324085360441674,
      "lng": 108.32296841478009,
      "nama": "Pohon Randu Gede",
      "tiket": "Gratis"
    },
    {
      "about": "Destinasi alam ini selalu ramai setiap akhir pekan dan musim liburan. Lokasinya yang tak jauh dari jantung kota sehingga mudah bagi wisatawan menemukannya. Di sisi lain pesona alam Pantai karangsong memang tidak bisa ditolak keindahannya. Anda akan menemukan keunikan wisata ini, yaitu pantai yang diselimuti hutan mangrov.",
      "alamat": "Jl. Wanasari, Karangsong, Kec. Indramayu, Kabupaten Indramayu, Jawa Barat",
      "hari": "Setiap Hari",
      "id": 2,
      "img": [
        "https://www.google.com/maps/place/Pantai+Karangsong/@-6.3057331,108.3685935,3a,75y,90t/data=!3m8!1e2!3m6!1sAF1QipNx8CI_LcVwFK-CGCTM5c-8ggyzAi3T_q7BjfPt!2e10!3e12!6shttps:%2F%2Flh5.googleusercontent.com%2Fp%2FAF1QipNx8CI_LcVwFK-CGCTM5c-8ggyzAi3T_q7BjfPt%3Dw396-h298-k-no!7i4624!8i3472!4m15!1m7!3m6!1s0x2e6ebc4872ce9051:0x488988f64087588f!2sPantai+Karangsong!8m2!3d-6.3057331!4d108.3685935!10e4!3m6!1s0x2e6ebc4872ce9051:0x488988f64087588f!8m2!3d-6.3057331!4d108.3685935!14m1!1BCgIgAQ#",
        "https://www.google.com/maps/place/Pantai+Karangsong/@-6.3057437,108.3686025,3a,75y,90t/data=!3m8!1e2!3m6!1sAF1QipPxkDxDXcfVdLxDh-GILyccKLwaQSFNbaqodws!2e10!3e12!6shttps:%2F%2Flh5.googleusercontent.com%2Fp%2FAF1QipPxkDxDXcfVdLxDh-GILyccKLwaQSFNbaqodws%3Dw203-h152-k-no!7i4624!8i3468!4m15!1m7!3m6!1s0x2e6ebc4872ce9051:0x488988f64087588f!2sPantai+Karangsong!8m2!3d-6.3057331!4d108.3685935!10e4!3m6!1s0x2e6ebc4872ce9051:0x488988f64087588f!8m2!3d-6.3057331!4d108.3685935!14m1!1BCgIgAQ#"
      ],
      "jam": "08:00 - 17:00 WIB Senin - Jumat\\n07:00 - 18:00 WIB Sabtu & Minggu",
      "kategori": "Wisata Alam",
      "lat": -6.305599800906916,
      "lng": 108.36857204218629,
      "nama": "Pantai Karangsong",
      "tiket": "'1000'"
    },
   ]
}

我用app.quicktype创建的模型数据

class ListWisata {
    ListWisata({
        this.datawisata,
    });

    List<Datawisata>? datawisata;

    factory ListWisata.fromRawJson(String str) => ListWisata.fromJson(json.decode(str));

    String toRawJson() => json.encode(toJson());

    factory ListWisata.fromJson(Map<String, dynamic> json) => ListWisata(
        datawisata: json["datawisata"] == null ? null : List<Datawisata>.from(json["datawisata"].map((x) => Datawisata.fromJson(x))),
    );

    Map<String, dynamic> toJson() => {
        "datawisata": datawisata == null ? null : List<dynamic>.from(datawisata!.map((x) => x.toJson())),
    };
}

class Datawisata {
  String? about;
  String? alamat;
  String? hari;
  int? id;
  List<String>? img;
  String? jam;
  String? kategori;
  double? lat;
  double? lng;
  String? nama;
  String? tiket;
  
  Datawisata({
    this.about,
    this.alamat,
    this.hari,
    this.id,
    this.img,
    this.jam,
    this.kategori,
    this.lat,
    this.lng,
    this.nama,
    this.tiket,
  });

  factory Datawisata.fromJson(Map<String, dynamic> json) => Datawisata(
        about: json["about"] == null ? null : json["about"],
        alamat: json["alamat"] == null ? null : json["alamat"],
        hari: json["hari"] == null ? null : json["hari"],
        id: json["id"] == null ? null : json["id"],
        img: json["img"] == null
            ? null
            : List<String>.from(json["img"].map((x) => x)),
        jam: json["jam"] == null ? null : json["jam"],
        kategori: json["kategori"] == null ? null : json["kategori"],
        lat: json["lat"] == null ? null : json["lat"].toDouble(),
        lng: json["lng"] == null ? null : json["lng"].toDouble(),
        nama: json["nama"] == null ? null : json["nama"],
        tiket: json["tiket"] == null ? null : json["tiket"],
      );

  Map<String, dynamic> toJson() => {
        "about": about == null ? null : about,
        "alamat": alamat == null ? null : alamat,
        "hari": hari == null ? null : hari,
        "id": id == null ? null : id,
        "img": img == null ? null : List<dynamic>.from(img!.map((x) => x)),
        "jam": jam == null ? null : jam,
        "kategori": kategori == null ? null : kategori,
        "lat": lat == null ? null : lat,
        "lng": lng == null ? null : lng,
        "nama": nama == null ? null : nama,
        "tiket": tiket == null ? null : tiket,
      };
}

我正在尝试从API调用取回数据列表并通过提供程序显示它

class HomeViewModel extends ChangeNotifier {
  List<ListWisata> _wisata = [];
  List get wisatalist => _wisata;

  Future<void> getWisatas() async {
    final c = await WisataApi.getWisata();
    _wisata = c!.datawisata!.cast<ListWisata>();
    notifyListeners();
  }
}

我这样称呼它

ListView.builder(
   itemCount: modelView.wisatalist.length,
   scrollDirection: Axis.horizontal,
   shrinkWrap: true,
   physics: const BouncingScrollPhysics(),
   itemBuilder: (context, index) {
     return GestureDetector(
        child: BoxWisata(
        h: 100.0,
        w: 100.0,
        fs: 13,
        title: modelview.wisatalist[index].nama,
        img:
        "https://picsum.photos/id/0/400/300",
          ),

IDK不知道如何调用API获取n

q8l4jmvw

q8l4jmvw1#

getWisata() 函数放入提供程序文件

class WisataProvider with ChangeNotifier {
Future<ListWisata?> getWisata() async {
Response? result;
try {
  result = await Dio().get(
      'https://windramayu-api-default-rtdb.asia-southeast1.firebasedatabase.app/');
  print('getWisata: ${result.data}');
} catch (e) {
  (e.toString());
}
if (result != null) {
  return ListWisata.fromJson(result.data);
}
return null;
}
}

然后在主页中调用它

class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
var provider = Provider.of<WisataProvider>(context);
return Scaffold(
  body: FutureBuilder(
    future: provider.getWisata(),
    builder: (context, snapshot) {
      if (snapshot.connectionState == ConnectionState.waiting) {
        return const CircularProgressIndicator();
      }
      
      return ListView.builder(
        itemCount: modelView.wisatalist.length,
        scrollDirection: Axis.horizontal,
        shrinkWrap: true,
        physics: const BouncingScrollPhysics(),
        itemBuilder: (context, index) {
          final data = modelview.wisatalist[index];
          return GestureDetector(
            child: BoxWisata(
              h: 100.0,
              w: 100.0,
              fs: 13,
              title: data.nama,
              img: "https://picsum.photos/id/0/400/300",
            ),
          );
        },
      );
    },
  ),
  );
 }
 }

我希望这对你有帮助:)

相关问题