【发布时间】:2020-06-29 13:17:02
【问题描述】:
我有一个应用程序,想查看广告创建者的用户名,但是我在运行它时遇到了一点问题,我收到了这个错误:
A non-null String must be provided to a Text widget. 'package:flutter/src/widgets/text.dart': Failed assertion: line 298 pos 10: 'data != null'
The relevant error-causing widget was: AdView file:///Users/ahmedhussain/Downloads/khamsat/Client%20Apps/HPX-KSA/hpx_ksa/lib/Screens/custom_ad_tile.dart:23:79 When the exception was thrown, this was the stack:
#2 new Text (package:flutter/src/widgets/text.dart:298:10)
#3 _AdViewState.build (package:hpxksa/Screens/ad_view.dart:134:34)
虽然我检查了数据库并且文档中已经存在数据,如果我将值更改为文档中的任何其他值,它可以正常工作。
这是我的代码:
class AdView extends StatefulWidget {
final AdModel adModel;
final String submittedStr;
AdView({this.adModel, this.submittedStr});
@override
_AdViewState createState() => _AdViewState();
}
return StreamProvider<List<AdModel>>.value(
value: DatabaseService().ads,
child: Scaffold(
body: Column(
children: <Widget>[
Row(
children: <Widget>[
InkWell(
child: Text(widget.adModel.username , style: TextStyle(color: kPrimaryColor),),
onTap: (){},
),
InkWell(
child: Text(widget.adModel.location, style: TextStyle(color: kPrimaryColor),),
onTap: (){},
),
这里是 AdModel 类:
class AdModel{
String category;
String location;
String adName;
String adImage;
String userId;
String username;
AdModel({
this.category,
this.location,
this.adName,
this.adImage,
this.userId,
this.username,
});
这是我通过 AdView 传递 AdModel 的方式:
class CustomAdTile extends StatefulWidget {
final AdModel adModel;
CustomAdTile({this.adModel});
@override
_CustomAdTileState createState() => _CustomAdTileState();
}
class _CustomAdTileState extends State<CustomAdTile> {
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 5.0),
child: InkWell(
onTap: (){
print('card pressed');
Navigator.push(context, new MaterialPageRoute(builder: (context) => AdView(adModel: widget.adModel,)));
},
这里是在 Provider 中创建和使用 AdModel 的 AdList:
class _AdsListState extends State<AdsList> {
@override
Widget build(BuildContext context) {
final ads = Provider.of<List<AdModel>>(context);
return ListView.builder(
scrollDirection: Axis.vertical,
itemCount:(ads == null) ? 0 : ads.length,
itemBuilder: (context, index){
return
CustomAdTile(adModel: ads[index],);
});
}
}
【问题讨论】:
-
你可以使用类似的东西:
Text(widget?.adModel?.username ?? "Undefined")