点击时无法将数据传递到新屏幕

时间:2019-01-02 12:06:15

标签: flutter flutter-layout

我有一个使用card小部件显示的新闻列表,并希望在用户点击任何新闻时在新屏幕中显示相应新闻的详细信息。但是,以某种方式我要传递到新屏幕的数据是null,并且不确定问题出在哪里。我遇到的错误是:

The getter 'urlToImage' was called on null.如果我正确理解此错误,那么我传递的news对象将返回null,但是如何使用该对象通过Navigator发送实际数据?

新闻模式:

class News {
  String title;
  String description;
  String urlToImage;
  String content;

  News(
    this.title,
    this.description,
    this.urlToImage,
    this.content
  );
}

卡片小部件,显示新闻的图片和标题:

class NewsCard extends StatelessWidget{
final String title, urlToImage;

  News news;

NewsCard({this.title,this.urlToImage});
final makeListTile = ListTile(
    onTap: () {
      Navigator.push(context, MaterialPageRoute(builder: (context) => new Details(news)));
    },
    contentPadding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 10.0),
    leading: Container(
      padding: EdgeInsets.only(right: 12.0),
      decoration: BoxDecoration(
        border: Border(
          right: BorderSide(
            width: 1.0,
          ),
        ),
      ),
      child: Image(
        height: 50.0,
        width: 50.0,
        fit: BoxFit.cover,
        image: NetworkImage(urlToImage),
      ),
    ),
    title: Text(title, style: TextStyle(
      fontWeight: FontWeight.bold
    )),
    trailing: Icon(Icons.keyboard_arrow_right, size: 30.0)
  );
  return
    Card(
    shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15.0)),
    elevation: 8.0,
    margin: new EdgeInsets.symmetric(horizontal: 10.0, vertical: 6.0),
    child: Container(
      child: makeListTile,
    )
    );
}

}

NewsCard类的调用如下:

class _NewsClassState extends State<NewsClass> {
  final List<NewsCard> _news = <NewsCard>[];

详细信息屏幕

class Details extends StatelessWidget {

  final News news;

  Details(this.news);

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Text('News Details'),
        centerTitle: true,
      ),
      body: ListView(
        children: <Widget>[
          Image.network('${news.urlToImage}',fit: BoxFit.cover,),
          Container(
            child: Text('${news.content}')
            ),
      ]
          )
      );
  }

}

0 个答案:

没有答案