我在我的项目(https://randomuser.me/api/?results=10)中使用rest api,不使用我想获取和显示Json数据的模型。我得到了错误&;期望类型"列表"的值,但得到了类型"空"之一,我没有在项目中使用模型。给我解决方案,不用模型。
项目代码:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: HomeScreen(),
);
}
}
class HomeScreen extends StatefulWidget {
const HomeScreen({super.key});
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
List<dynamic> users = [];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Rest API Call'),
centerTitle: true,
),
floatingActionButton: FloatingActionButton(
onPressed: fetchUsers,
),
body: ListView.builder(
itemCount: users.length,
itemBuilder: (context, index) {
final user = users[index];
final name = user['name']['first'];
final email = user['email'];
return ListTile(
leading: CircleAvatar(
child: Text('$index+1'),
),
title: Text(name.toString()),
subtitle: Text(email),
);
},
),
);
}
void fetchUsers() async {
print('fetchUsers called');
const url = "https://randomuser.me/api/?results=10";
final uri = Uri.parse(url);
final response = await http.get(uri);
final bodys = response.body;
final json = jsonDecode(bodys);
setState(() {
users = json['result'];
});
print('fetchUser completed ');
}
}
你拼错了" result"用s
:)