错误:未为类“Object?”定义 getter“length”

时间:2021-07-22 06:27:04

标签: flutter dart

这是我完整的颤振代码请帮助我 唯一的问题是 listViewBulleder 上指定的长度

我的错误:

没有为“Object?”类定义 getter 'length'。

  • 'Object' 来自 'dart:core'。尝试将名称更正为现有 getter 的名称,
  • 或者定义一个名为“length”的 getter 或字段。

小工具

import 'package:flutter/material.dart';
import 'package:http/http.dart'as http;
import 'dart:convert';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(

        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Api testing'),
    );
  }
}

class MyHomePage extends StatefulWidget {

  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  Future getUserData() async{
    var response= await http.get(Uri.https('http://jsonplaceholder.typicode.com/', 'users'));
    var jsonData = jsonDecode(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(widget.title),
      ),
      body: Center(

        child:
          Card(
            child: FutureBuilder(
              future: getUserData(),
              builder: (context, 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: Text((snapshot.data as dynamic)[i].name),
                          subtitle: Text((snapshot.data as dynamic)[i].userName),
                          trailing: Text((snapshot.data as dynamic)[i].email),

                        );
                      });
              },
            ),
          ),
      ),
    );
  }
}

class User {
  final String name, email, userName;
  User(this.name, this.email, this.userName);
}

1 个答案:

答案 0 :(得分:0)

试试:

FutureBuilder<List<User>>(

而不仅仅是FutureBuilder。也仅在 snapshot.hasData 之后返回您的列表视图构建器。显示加载微调器为 snapshot.connectionStatus = waiting