gpt4 book ai didi

flutter - 如何仅在 API 响应出现 flutter 时才加载 UI?

转载 作者:行者123 更新时间:2023-12-05 03:56:22 24 4
gpt4 key购买 nike

如何在创建 UI 之前调用 API 并仅在 API 响应到达时才加载 UI(在 flutter 中)。

基本上,我只想在 API 响应到达时加载 UI,否则我想显示一条错误消息。我怎样才能做到这一点?

最佳答案

使用FutureBuilder:

Widget that builds itself based on the latest snapshot of the interaction with a Future.

一个完整的例子:

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

import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;

// podo class
class ObjectClass {
String name;

ObjectClass({this.name});

ObjectClass.fromJson(Map<String, dynamic> json) {
name = json['name'];
}
}

class Demo extends StatefulWidget {
@override
_DemoState createState() => new _DemoState();
}

class _DemoState extends State<Demo> {
Future<List<ObjectClass>> fetchJson() async {
final response = await http.Client().get('your json url');
return compute(parseJson, response.body);
}

// A function that converts a response body into a List<ObjectClass>.
List<ObjectClass> parseJson(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
return parsed
.map<ObjectClass>((json) => ObjectClass.fromJson(json))
.toList();
}

Widget _bodyBuild({List<ObjectClass> data}) {
return Container(); // make your ui here and use the 'data' variable
}

Widget demoBody() {
return FutureBuilder<List<ObjectClass>>(
future: fetchJson(), // api call method here, to fetch json/data
builder: (context, snapshot) {
if (snapshot.hasError) {
return Container(); // widget to be shown on any error
}

return snapshot.hasData
? _bodyBuild(data: snapshot.data)
: Text("Loading"); // widget to be shown while data is being loaded from api call method
},
);
}

@override
Widget build(BuildContext context) {
return Scaffold(appBar: AppBar(title: Text("DEMO")), body: demoBody());
}
}

关于flutter - 如何仅在 API 响应出现 flutter 时才加载 UI?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59368288/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com