简体   繁体   English

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

[英]type 'String' is not a subtype of type 'Widget? in flutter dart

I am new to Flutter. I made a flutter project that gets data from an API and displays them in a ListView.我是 Flutter 的新手。我做了一个 flutter 项目,它从 API 获取数据并将它们显示在 ListView 中。 And if no data in snapShot then shows a loading screen.如果 snapShot 中没有数据,则会显示加载屏幕。

I got an error when I ran the program after fixing some small errors.修复了一些小错误后运行程序时出现错误。

Error: type 'String' is not a subtype of type 'Widget?错误: “String”类型不是“Widget”类型的子类型?

在此处输入图像描述

My Code:我的代码:

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);
}

Console Output:控制台 Output:

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?'

Your error comes from the fact that you are trying to create a ListTile widget and as the title you are passing in a String .您的错误来自于您正在尝试创建一个ListTile小部件,并且作为您传递的标题String

But if you look at the documentation for ListTile, you can see that it expects the title to be a Text widget :但是如果您查看 ListTile 的文档,您会发现它期望标题是一个文本小部件

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

So you need to change your code to this:因此,您需要将代码更改为:

 @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)); //// <---------------------
                    });
              }
            },
          ),
    ))
    );
  }

You have to add widget to ListTile title, based on your requirements than you can assign text value to it.您必须根据您的要求将小部件添加到ListTile标题,然后才能为其分配文本值。

Here for string you can use Text widget对于字符串,您可以在此处使用Text小部件

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

List view title takes a widget, you need to pass a widget not a string that what you are doing right now.列表视图标题需要一个小部件,您需要传递一个小部件而不是您现在正在做的字符串。

just wrap your title string in a Text widget.只需将您的标题字符串包装在文本小部件中。

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

Change your ListTile更改您的 ListTile

From

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

To

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 “字符串”类型不是 FLUTTER 中“小部件”类型的子类型 - Type 'String' is not a subtype of type 'Widget' in FLUTTER Flutter/Dart:类型“int”不是类型转换中“String”类型的子类型 - Flutter/Dart: Type 'int' is not a subtype of type 'String' in type cast 颤动映射错误:类型'String'不是类型转换中类型'Widget'的子类型 - flutter Mapping error: type 'String' is not a subtype of type 'Widget' in type cast Flutter - Dart 未处理的异常:“Blob”类型不是“String”类型的子类型 - Flutter - Dart Unhandled Exception: type 'Blob' is not a subtype of type 'String' Flutter/Dart - 未处理的异常:“String”类型不是“index”的“int”类型的子类型 - Flutter/Dart - Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index' Flutter Dart http 类型响应不是字符串错误类型的子类型 - Flutter Dart http Type Response is not a subtype of type String error 在黑客新闻的颤振小部件测试中,类型“int”不是“String”类型的子类型 - type 'int' is not a subtype of type 'String' in flutter widget test in hacker news 如何修复类型字符串不是 flutter 代码下方类型小部件的子类型 - how to fix type string is not a subtype of type widget in below flutter code Flutter:输入“列表”<widget> ' 不是 'Widget' 类型的子类型</widget> - Flutter: type 'List<Widget>' is not a subtype of type 'Widget' Flutter:小部件不是“ObstructingPreferredSizeWidget”类型的子类型 - Flutter: Widget is not a subtype of type 'ObstructingPreferredSizeWidget'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM