我对Flutter 翼是新手. 我制作了一个从API获取数据并在ListView中显示它们的Ffltter项目. 如果快照中没有数据,则显示加载屏幕.
我在修复一些小错误后运行程序时遇到错误.
错误:type 'String' is not a subtype of type 'Widget?
我的代码:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class DataFromAPI extends StatefulWidget {
const DataFromAPI({Key? key}) : super(key: key);
@override
State<DataFromAPI> createState() => _DataFromAPIState();
}
class _DataFromAPIState extends State<DataFromAPI> {
getUserData() async{
var response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/users'));
var jsonData = jsonDecode(response.body);
print(response.body);
List<User> users = [];
for(var u in jsonData){
User user = User(u['name'],u['email'],u['username']);
users.add(user);
}
//print(users.length);
return users;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Get Data From API'),
),
body: Container(
child: Card(
child: FutureBuilder(
future: getUserData(),
builder: (context, AsyncSnapshot snapShot){
if(snapShot.data == null){
return Container(child: Center(child: Text('Loading'),),);
}else{
return ListView.builder(
itemCount: snapShot.data.length,
itemBuilder: (context, i){
return ListTile(title: snapShot.data[i].name);
});
}
},
),
))
);
}
}
class User{
final String name, email, userName;
User(this.name, this.email, this.userName);
}
输出控制台:
Syncing files to device sdk gphone64 x86 64...
Reloaded 0 libraries in 506ms (compile: 12 ms, reload: 0 ms, reassemble: 433 ms).
D/EGL_emulation( 6751): app_time_stats: avg=8895.54ms min=975.35ms max=16815.74ms count=2
======== Exception caught by widgets library =======================================================
The following _TypeError was thrown building:
type 'String' is not a subtype of type 'Widget?'