flutter - 方法 '[]'在null上被调用,但在inApp中有效

2021-08-03 10:40:18 浏览数 (1)

flutter - 方法 '[]'在null上被调用,但在inApp中有效

代码语言:javascript复制
class DetailPage extends StatefulWidget {
    final String text;
  DetailPage ({Key key, @required this.text}) : super(key: key);
  @override
  _DetailPage createState() => _DetailPage();
}
​
class _DetailPage extends State<DetailPage> {
  Map mapResponse;
  Future fetchData() async {
    Uri url = Uri.parse('');
​
    Response<String> response = await Dio().request(url.toString(),
        options: Options(
            headers: {}));
​
    if (response.statusCode == 200) {
      setState(() {
        mapResponse = json.decode(response.data);
      });
    }
  
  }
​
  @override
  void initState() {
    fetchData();
    super.initState();
  }
​
​
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: SafeArea(
            bottom: false,
            child: Stack(children: <Widget>[
              SingleChildScrollView(
                  child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                    Padding(
                      padding: const EdgeInsets.all(32.0),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          SizedBox(height: 300),
                          Text(
                            mapResponse['item']['name'],
                            style: TextStyle(
                              fontFamily: 'Avenir',
                              fontSize: 56,
                              color: Colors.blue,
                              fontWeight: FontWeight.w900,
                            ),

这就是我的json的样子

代码语言:javascript复制
{
    "status": true,
    "item": {
        "name": "Name here",
    (moreJsonHere)

最佳答案

这意味着检索数据需要很短的时间, 试试这个。数据为空时,它将在短时间内通过进度指示器

代码语言:javascript复制
mapResponse !=null ? Text(
    mapResponse['item']['name'],
    style: TextStyle(
    fontFamily: 'Avenir',
    fontSize: 56,
    color: Colors.blue,
    fontWeight: FontWeight.w900,
    ):CircularProgressIndicator(),

0 人点赞