预期为“List<dynamic>”类型的值,但得到了“Null”类型的值

问题描述 投票:0回答:1

我在我的项目中使用rest api(https://randomuser.me/api/?results=10),不使用模型我想获取和显示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 ');
  }
}

json flutter dart http
1个回答
0
投票

您拼错了“结果”而不是“结果”,带有

s
:)

© www.soinside.com 2019 - 2024. All rights reserved.