类型“String”不是flutter dart中类型“Widget”的子类型

icomxhvb  于 2022-12-30  发布在  Flutter
关注(0)|答案(4)|浏览(211)

我是Flutter的新手,我做了一个flutter项目,从API获取数据并在列表视图中显示。如果快照中没有数据,则显示一个加载屏幕。
当我修复了一些小错误后运行程序时,我得到了一个错误。
错误:**类型'String'不是类型'Widget?**的子类型

我的代码:

import 'dart:convert';

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

class DataFromAPI extends StatefulWidget {
  const DataFromAPI({Key? key}) : super(key: key);

  @override
  State<DataFromAPI> createState() => _DataFromAPIState();
}

class _DataFromAPIState extends State<DataFromAPI> {

  getUserData() async{
    var response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/users'));
    var jsonData = jsonDecode(response.body);
    print(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('Get Data From API'),
      ),
      body: Container(
        child: Card(
          child: FutureBuilder(
            future: getUserData(),
            builder: (context, AsyncSnapshot 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: snapShot.data[i].name);
                    });
              }
            },
          ),
    ))
    );
  }
}

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

控制台输出:

Syncing files to device sdk gphone64 x86 64...
Reloaded 0 libraries in 506ms (compile: 12 ms, reload: 0 ms, reassemble: 433 ms).
D/EGL_emulation( 6751): app_time_stats: avg=8895.54ms min=975.35ms max=16815.74ms count=2

======== Exception caught by widgets library =======================================================
The following _TypeError was thrown building:
type 'String' is not a subtype of type 'Widget?'
lmvvr0a8

lmvvr0a81#

您的错误是由于您尝试创建一个***ListTile***小部件,并且您传入了一个***String***作为标题。
但是,如果您查看ListTile的documentation,您会发现它期望标题是一个***文本小部件***:

Container(
  color: Colors.green,
  child: const Material(
    child: ListTile(
      title: Text('ListTile with red background'),
      tileColor: Colors.red,
    ),
  ),
)

因此,您需要将代码更改为:

@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Get Data From API'),
      ),
      body: Container(
        child: Card(
          child: FutureBuilder(
            future: getUserData(),
            builder: (context, AsyncSnapshot 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: const Text(snapShot.data[i].name)); //// <---------------------
                    });
              }
            },
          ),
    ))
    );
  }
7dl7o3gd

7dl7o3gd2#

你必须添加小部件到ListTile标题,根据您的要求,比你可以分配文本值给它。
在这里,对于字符串,您可以使用Text小部件

itemBuilder: (context, i) {
     return ListTile(title: Text(snapShot.data[i].name));
}
lp0sw83n

lp0sw83n3#

列表视图标题需要一个小部件,你需要传递一个小部件,而不是你现在正在做的字符串。
只需将标题字符串 Package 在Text小部件中。

itemBuilder: (context, i){
                  return ListTile(title: Text(snapShot.data[i].name??''));
                });
p5fdfcr1

p5fdfcr14#

更改列表磁贴

return ListView.builder(
                itemCount: snapShot.data.length,
                itemBuilder: (context, i){
                  return ListTile(title: snapShot.data[i].name);
                });
          }

return ListView.builder(
                itemCount: snapShot.data.length,
                itemBuilder: (context, i){
                  return ListTile(title: Text(snapShot.data[i].name));
                });
          }

相关问题