Api 数据!=null:必须向文本小部件提供非null字符串

Api 数据!=null:必须向文本小部件提供非null字符串,api,http,flutter,dart,Api,Http,Flutter,Dart,我是新来的flifter,我得到了这个错误:必须向文本小部件提供一个非空字符串。我想把它修好,但是修不好。api响应良好,以下是url: 这是我写的代码 import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'dart:async'; import 'dart:convert'; class CategoryTab extends StatefulWidget {

我是新来的flifter,我得到了这个错误:
必须向文本小部件提供一个非空字符串
。我想把它修好,但是修不好。api响应良好,以下是url:

这是我写的代码

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

class CategoryTab extends StatefulWidget {
     @override
     _CategoryTabState createState() => _CategoryTabState();
}

class _CategoryTabState extends State<CategoryTab> {
    @override
    void initState() {
        // TODO: implement initState
        super.initState();
    }

    Future<List<CategoryList>> _getUsers() async {

        var data = await http.get("https://appiconmakers.com/demoMusicPlayer/API/getallcategories");

        var jsonData = json.decode(data.body);

        List<CategoryList> cat = [];

        for (var u in jsonData) {

            CategoryList categoryList = CategoryList(u["categoryId"], u["categoryName"], u["parentCategoryId"], u["categoryStatus"], u["createdDate"]);

            cat.add(categoryList);

        }
        print("=================================");

        print(cat.length);

        return cat;

    }

    @override
    Widget build(BuildContext context) {
        return Scaffold(
            appBar: AppBar(
                title: Text("Categories", style: TextStyle(color:Colors.black)),
                backgroundColor: Colors.white,
        ), body: 
        Container(
            child: FutureBuilder(
                future: _getUsers(),
                builder: (BuildContext context, AsyncSnapshot snapshot) {
                    print(snapshot.data);
                    if (snapshot.data == null) {
                        return Container(
                            child: Center(child: Text("Loading..."))
                        );
                    } else {
                        return ListView.builder(
                            itemCount: snapshot.data.length,
                            itemBuilder: (BuildContext context, int index) {
                                return ListTile(
                                    leading: CircleAvatar(),
                                    title: Text(snapshot.data[index].categoryName,
                                    // subtitle: Text(snapshot.data[index].categoryId),
                                );
                            },
                        );
                    }
                ),
            ),
        );
    }
}

class CategoryList {
    String categoryId;
    String categoryName;
    String parentCategoryId;
    String categoryStatus;
    String createdDate;

    CategoryList(this.categoryId, this.categoryName, this.parentCategoryId, this.categoryStatus, this.createdDate);
}

只需执行以下更新:

title: Text(snapshot.data[index].categoryName ?? '',
              // subtitle: Text(snapshot.data[index].categoryId
              ),
现在,如果snapsho.data[index].categoryName为null,则空字符串将分配给文本小部件

如果您想查看数据是否存在,只需打印snapshot.data,就可以确定数据是否存在。

替换
标题:文本(快照.数据[索引].categoryName,


title:Text(snapshot.data[index].categoryName???“如果为空,则显示一些文本”

这样就可以了。
??
后面的值将替换以前的值(如果为空)


检查有关
??
操作员的更多信息

更换此代码

CategoryList CategoryList=CategoryList(u[“categoryId”]、u[“categoryName”]、u[“parentCategoryId”]、u[“categoryStatus”]、u[“createdDate”]);

CategoryList CategoryList=CategoryList(u[“category_id”]、u[“category_name”]、u[“parent_category_id”]、u[“category_status”]、u[“created_date”]);
只需检查答案

json的模型类:

// To parse this JSON data, do
//
//     final categoryList = categoryListFromJson(jsonString);

import 'dart:convert';

List<CategoryList> categoryListFromJson(String str) => List<CategoryList>.from(json.decode(str).map((x) => CategoryList.fromJson(x)));

String categoryListToJson(List<CategoryList> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class CategoryList {
    CategoryList({
        this.categoryId,
        this.categoryName,
        this.parentCategoryId,
        this.categoryStatus,
        this.createdDate,
        this.subcategory,
    });

    String categoryId;
    String categoryName;
    String parentCategoryId;
    String categoryStatus;
    DateTime createdDate;
    List<CategoryList> subcategory;

    factory CategoryList.fromJson(Map<String, dynamic> json) => CategoryList(
        categoryId: json["category_id"],
        categoryName: json["category_name"],
        parentCategoryId: json["parent_category_id"],
        categoryStatus: json["category_status"],
        createdDate: DateTime.parse(json["created_date"]),
        subcategory: List<CategoryList>.from(json["subcategory"].map((x) => CategoryList.fromJson(x))),
    );

    Map<String, dynamic> toJson() => {
        "category_id": categoryId,
        "category_name": categoryName,
        "parent_category_id": parentCategoryId,
        "category_status": categoryStatus,
        "created_date": createdDate.toIso8601String(),
        "subcategory": List<dynamic>.from(subcategory.map((x) => x.toJson())),
    };
}



//要解析此JSON数据,请执行以下操作
//
//final categoryList=categoryListFromJson(jsonString);
导入“dart:convert”;
List categoryListFromJson(String str)=>List.from(json.decode(str.map)(x)=>CategoryList.fromJson(x));
String categoryListToJson(List data)=>json.encode(List.from(data.map((x)=>x.toJson()));
类分类列表{
分类学家({
这个,分类号,
这个.categoryName,
这是parentCategoryId,
这是categoryStatus,
这个.createdDate,
这个子类别,
});
字符串类别;
字符串类别名称;
字符串parentCategoryId;
弦类;
创建日期时间;
列出子类别;
factory CategoryList.fromJson(映射json)=>CategoryList(
categoryId:json[“类别id”],
categoryName:json[“类别名称”],
parentCategoryId:json[“父类别id”],
类别状态:json[“类别状态”],
createdDate:DateTime.parse(json[“created_date”]),
子类别:List.from(json[“subcategory”].map((x)=>CategoryList.fromJson(x)),
);
映射到JSON()=>{
“类别id”:类别id,
“类别名称”:类别名称,
“父类别id”:父类别id,
“类别状态”:类别状态,
“created_date”:createdDate.toIso8601String(),
“subcategory”:List.from(subcategory.map((x)=>x.toJson()),
};
}
it的用户界面:

import 'dart:convert';

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

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: HomePage());
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  double value;
  @override
  void initState() {
    super.initState();
  }

  Future<List<CategoryList>> _getUsers() async {
    var data = await http
        .get("https://appiconmakers.com/demoMusicPlayer/API/getallcategories");

    final categoryList = categoryListFromJson(data.body);
    List<CategoryList> cat = [];

    categoryList.forEach((element) {
      cat.add(CategoryList(
          categoryId: element.categoryId,
          categoryName: element.categoryName,
          parentCategoryId: element.parentCategoryId,
          categoryStatus: element.categoryStatus,
          createdDate: element.createdDate.toString()));
    });

    print("=================================");

    print(cat.length);

    return cat;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          "Categories",
          style: TextStyle(color: Colors.black),
        ),
        backgroundColor: Colors.white,
      ),
      body: Container(
        child: FutureBuilder(
          future: _getUsers(),
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            print(snapshot.data);

            if (snapshot.data == null) {
              return Container(child: Center(child: Text("Loading...")));
            } else {
              return ListView.builder(
                itemCount: snapshot.data.length,
                itemBuilder: (BuildContext context, int index) {
                  return ListTile(
                    leading: CircleAvatar(),
                    title: Text(
                      snapshot.data[index].categoryName,
                      // subtitle: Text(snapshot.data[index].categoryId
                    ),
                  );
                },
              );
            }
          },
        ),
      ),
    );
  }
}

class CategoryList {
  String categoryId;
  String categoryName;
  String parentCategoryId;
  String categoryStatus;
  String createdDate;

  CategoryList(
      {this.categoryId,
      this.categoryName,
      this.parentCategoryId,
      this.categoryStatus,
      this.createdDate});
}

导入'dart:convert';
进口“包装:颤振/材料.省道”;
导入“package:json_parsing_example/models.dart”;
将“package:http/http.dart”导入为http;
void main()=>runApp(MyApp());
类MyApp扩展了无状态小部件{
@凌驾
小部件构建(构建上下文){
返回资料app(主页:HomePage());
}
}
类主页扩展了StatefulWidget{
@凌驾
_HomePageState createState()=>\u HomePageState();
}
类_HomePageState扩展状态{
双重价值;
@凌驾
void initState(){
super.initState();
}
Future\u getUsers()异步{
var data=wait http
.get(“https://appiconmakers.com/demoMusicPlayer/API/getallcategories");
final categoryList=categoryListFromJson(data.body);
列表类别=[];
类别列表forEach((元素){
目录添加(类别列表)(
categoryId:element.categoryId,
categoryName:element.categoryName,
parentCategoryId:element.parentCategoryId,
categoryStatus:element.categoryStatus,
createdDate:element.createdDate.toString());
});
打印(“=======================================================”);
打印(类别长度);
返回猫;
}
@凌驾
小部件构建(构建上下文){
返回脚手架(
appBar:appBar(
标题:正文(
“类别”,
样式:TextStyle(颜色:Colors.black),
),
背景颜色:Colors.white,
),
主体:容器(
孩子:未来建设者(
未来:_getUsers(),
生成器:(BuildContext上下文,异步快照){
打印(快照数据);
如果(snapshot.data==null){
返回容器(子:中心(子:文本(“加载…”));
}否则{
返回ListView.builder(
itemCount:snapshot.data.length,
itemBuilder:(构建上下文,int索引){
返回列表块(
前导:CircleAvatar(),
标题:正文(
snapshot.data[index].categoryName,
//字幕:文本(快照.数据[索引].类别ID
),
);
},
);
}
},
),
),
);
}
}
类分类列表{
字符串类别;
字符串类别名称;
字符串parentCategoryId;
弦类;
字符串创建数据;
分类学家(
{this.categoryId,
这个.categoryName,
这是parentCategoryId,
这是categoryStatus,
这是(createdDate});
}

让我知道它是否有效。

实际上这是最好的解决方案,谢谢@shubham chhimpa
import 'dart:convert';

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

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: HomePage());
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  double value;
  @override
  void initState() {
    super.initState();
  }

  Future<List<CategoryList>> _getUsers() async {
    var data = await http
        .get("https://appiconmakers.com/demoMusicPlayer/API/getallcategories");

    final categoryList = categoryListFromJson(data.body);
    List<CategoryList> cat = [];

    categoryList.forEach((element) {
      cat.add(CategoryList(
          categoryId: element.categoryId,
          categoryName: element.categoryName,
          parentCategoryId: element.parentCategoryId,
          categoryStatus: element.categoryStatus,
          createdDate: element.createdDate.toString()));
    });

    print("=================================");

    print(cat.length);

    return cat;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          "Categories",
          style: TextStyle(color: Colors.black),
        ),
        backgroundColor: Colors.white,
      ),
      body: Container(
        child: FutureBuilder(
          future: _getUsers(),
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            print(snapshot.data);

            if (snapshot.data == null) {
              return Container(child: Center(child: Text("Loading...")));
            } else {
              return ListView.builder(
                itemCount: snapshot.data.length,
                itemBuilder: (BuildContext context, int index) {
                  return ListTile(
                    leading: CircleAvatar(),
                    title: Text(
                      snapshot.data[index].categoryName,
                      // subtitle: Text(snapshot.data[index].categoryId
                    ),
                  );
                },
              );
            }
          },
        ),
      ),
    );
  }
}

class CategoryList {
  String categoryId;
  String categoryName;
  String parentCategoryId;
  String categoryStatus;
  String createdDate;

  CategoryList(
      {this.categoryId,
      this.categoryName,
      this.parentCategoryId,
      this.categoryStatus,
      this.createdDate});
}