【发布时间】:2019-04-16 11:44:10
【问题描述】:
我对 Flutter 比较陌生。这是我第一次在 Dart 中实现 API 调用。我需要使用回调编写 API 调用。我没有编程背景,所以请帮我写一下。我在下面添加了一个链接,我需要列出标题并添加一个点击监听器。请帮帮我。
【问题讨论】:
-
这个问题太笼统了。请阅读如何提问的规则。 stackoverflow.com/help/how-to-ask
我对 Flutter 比较陌生。这是我第一次在 Dart 中实现 API 调用。我需要使用回调编写 API 调用。我没有编程背景,所以请帮我写一下。我在下面添加了一个链接,我需要列出标题并添加一个点击监听器。请帮帮我。
【问题讨论】:
在您的 pubspec.yaml 文件中添加以下内容:
dependencies:
flutter:
sdk: flutter
http: 0.12.0+1
在您的代码中:
import 'package:http/http.dart' as http;
const String url = 'https://www.redzoc.com/api/youtube/show/v2/get_trending.php?limit=50&offset=0';
final http.Request request = http.Request('GET', Uri.parse(url));
final http.StreamedResponse response = await http.Client().send(request);
final int statusCode = response.statusCode;
final String responseData =
await response.stream.transform(utf8.decoder).join();
if(statusCode == 200) {
print(responseData);
} else {
print('error: code $statusCode');
}
【讨论】:
您可以使用 futurebuilder 来调用 api。在这里,我已经完整演示了如何使用 loader 和 update view 调用 api。
dependencies:
flutter:
sdk: flutter
http: "^0.12.0"
添加依赖后导入
import 'package:http/http.dart' as http;
class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
body: ListView(
children:[
updateTopratedMovie(context),
]
),
);
}
Future<dynamic> getTopratedMovie() async {
String url =
'https://api.themoviedb.org/3/movie/top_rated';
http.Response response = await http.get(url);
return json.decode(response.body);
}
Widget updateTopratedMovie(context) {
return FutureBuilder(
future: getTopratedMovie(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
if (snapshot.data != null) {
dynamic content = snapshot.data;
return SizedBox(
height: 500.0,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 0.0),
child: Container(
// elevation: 2.0,
child: ListView.builder(
// scrollDirection: Axis.horizontal,
itemCount: content['results'].length,
itemBuilder: (context, i) =>
Container(
height:100.0,
color:Colors.red
child:Text(i);
),
),
),
);
}
} else {
return Container(
height: 120.0,
width: MediaQuery.of(context).size.width,
child: Center(
child: CircularProgressIndicator(
backgroundColor: Color(0xff00d2ff),
),
),
);
}
},
);
}
}
【讨论】:
void fetchData() async {
final response =
await get('https://www.redzoc.com/api/youtube/show/v2/get_trending.php?limit=50&offset=0');
final imageModel = YourModelClass.fromJson(json.decode(response.body));
}
【讨论】:
使用 Future API 的函数注册回调来处理完成 Future 的值。例如:
import 'package:http/http.dart' as http;
final future = http.get("https://yourapiurl.com");
future.then((response) {
if (response.statusCode == 200) {
print("Response received.");
}
});
【讨论】: