json 应为“List”类型的值< dynamic>,但得到的是“Null”类型的值

wgeznvg7  于 2023-03-31  发布在  其他
关注(0)|答案(1)|浏览(88)

我在我的项目(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 ');
  }
}
ldioqlga

ldioqlga1#

您将“results”拼写为“result”,错误拼写为s:)

相关问题