我是Flutter的新手,并且出现此错误:pattern_content=[]
flag=False
with open(<filename>) as sourcefile:
for pattern in sourcefile:
if pattern.startswith('begin'):
flag=True
elif pattern.strip().endswith('end'):
flag=False
elif flag:
pattern_content.append(pattern)
print '\n'.join(pattern_content)
。我试图修复它,但是没有。 api响应良好,这里是URL:https://appiconmakers.com/demoMusicPlayer/API/getallcategories
这是我编写的代码,
A non-null String must be provided to a Text widget
debug部分也给了我这个结果:
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);
}
答案 0 :(得分:1)
只需检查答案
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())),
};
}
用户界面:
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});
}
让我知道它是否有效。
答案 1 :(得分:0)
只需执行以下更新:
title: Text(snapshot.data[index].categoryName ?? '',
// subtitle: Text(snapshot.data[index].categoryId
),
现在,如果snapsho.data [index] .categoryName为null,则将空字符串分配给文本小部件。
如果您想查看数据是否存在,则只需打印snapshot.data即可查明数据是否存在。
答案 2 :(得分:0)
替换
title: Text(snapshot.data[index].categoryName,
与
title: Text(snapshot.data[index].categoryName ?? “Some Text To Display if Null”
应该这样做。 ??
之后的值(如果为空)将替换之前的值
检查this answer以获得有关??
运算符的更多信息
答案 3 :(得分:0)
替换此代码
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"]);