我在我的项目(https://randomuser.me/api/?results=10)中使用rest API,没有使用模型,我想获取和显示Json的数据。我得到了错误“预期类型为'List'的值,但得到了类型为'Null'的值”,我在项目中没有使用模型。给予我不使用模型的解决方案。
项目代码为:
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 ');
}
}
1条答案
按热度按时间ldioqlga1#
您将“results”拼写为“result”,错误拼写为
s
:)