Flutter 函数返回 null

时间:2021-03-31 04:05:37

标签: flutter gridview flutter-layout

我是颤振的新手。我正在尝试使用 Giphy 的 API 创建一个 flutter gif 应用程序 该应用程序正常运行。但是 GridView exib 一个错误说:

NoSuchMethodError: The method '[]' was called on null.
Receiver: null.
TriedCalling: []("data")
See also:
...

我的控制台出现此错误:

Launching lib\main.dart on Redmi Note 8 in debug mode...
lib\main.dart:1
√ Built build\app\outputs\flutter-apk\app-debug.apk.
Connecting to VM Service at ws://127.0.0.1:60514/6GdZXC3CG_w=/ws
I/m.example.gifi( 4670): ProcessProfilingInfo new_methods=449 is saved saved_to_disk=1 resolve_classes_delay=8000


════════ Exception caught by widgets library ═══════════════════════════════════
The following NoSuchMethodError was thrown building FutureBuilder<Map<dynamic, dynamic>>(dirty, state: _FutureBuilderState<Map<dynamic, dynamic>>#54085):
The method '[]' was called on null.
Receiver: null
Tried calling: []("data")

The relevant error-causing widget was
══FutureBuilder<Map<dynamic, dynamic>>
package:gifie/ui/home.dart:52
When the exception was thrown, this was the stack
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
#1      _HomePageState._createGifTable
package:gifie/ui/home.dart:87
#2      _HomePageState.build.<anonymous closure>
package:gifie/ui/home.dart:72══════ Exception caught by widgets library
#3      _FutureBuilderState.build
package:flutter/…/widgets/async.dart:773
#4      StatefulElement.build
package:flutter/…/widgets/framework.dart:4612
...
════════════════════════════════════════════════════════════════════════════════
Application finished.
Exited (sigterm)

当我尝试访问网络浏览器时,我的 API 正常返回 我试图扑通干净,没有任何变化。 我的颤动医生 -v 是正常的。

请帮忙。

我的完整代码:

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

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

class _HomePageState extends State<HomePage> {
  String _search;
  int _offset = 0;

  Future<Map> _getGifs() async {
    http.Response response;

    if (_search == null) {
      response = await http.get(Uri.parse(
          "https://api.giphy.com/v1/gifs/trending?api_key=h1xGoDG0FsqnKtOmI3I1A8zxBCuxEqUx&limit=20&rating=G"));
    } else {
      response = await http.get(Uri.parse(
          "https://api.giphy.com/v1/gifs/search?api_key=h1xGoDG0FsqnKtOmI3I1A8zxBCuxEqUx&q=$_search&limit=25&offset=$_offset&rating=g&lang=en"));

      return json.decode(response.body);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.black,
        title: Image.network(
            "https://developers.giphy.com/branch/master/static/header-logo-8974b8ae658f704a5b48a2d039b8ad93.gif"),
        centerTitle: true,
      ),
      backgroundColor: Colors.black,
      body: Column(
        children: [
          Padding(
            padding: EdgeInsets.all(10),
            child: TextField(
              decoration: InputDecoration(
                  labelText: "Buscar GIF incrível..,",
                  labelStyle: TextStyle(color: Colors.white),
                  border: OutlineInputBorder()),
              style: TextStyle(color: Colors.white, fontSize: 18.8),
              textAlign: TextAlign.center,
            ),
          ),
          Expanded(
            child: FutureBuilder(
              future: _getGifs(),
              builder: (context, snapshot) {
                switch (snapshot.connectionState) {
                  case ConnectionState.waiting:
                  case ConnectionState.none:
                    return Container(
                      width: 200.0,
                      height: 200.0,
                      alignment: Alignment.center,
                      child: CircularProgressIndicator(
                        valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                        strokeWidth: 5.0,
                      ),
                    );

                  default:
                    if (snapshot.hasError)
                      return Container();
                    else
                      return _createGifTable(context, snapshot);
                }
              },
            ),
          ),
        ],
      ),
    );
  }

  Widget _createGifTable(BuildContext context, AsyncSnapshot snapshot) {
    return GridView.builder(
      padding: EdgeInsets.all(10.0),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2, crossAxisSpacing: 10.0, mainAxisSpacing: 10.0),
      itemCount: snapshot.data["data"].length,
      itemBuilder: (context, index) {
        return GestureDetector(
          child: Image.network(
            snapshot.data["data"][index]["images"]["fixed_height"]["url"],
            height: 300.0,
            fit: BoxFit.cover,
          ),
        );
      },
    );
  }
}

我错过了什么?

3 个答案:

答案 0 :(得分:0)

你好像忘记添加了

return json.decode(response.body);

在您的 if 语句中。 或者您可以将当前的 return 语句从 else{} 移出 if else 分支。

答案 1 :(得分:0)

请试试

  Future<Map> _getGifs() async {
    http.Response response;

    if (_search == null) {
      response = await http.get(Uri.parse(
          "https://api.giphy.com/v1/gifs/trending?api_key=h1xGoDG0FsqnKtOmI3I1A8zxBCuxEqUx&limit=20&rating=G"));
    } else {
      response = await http.get(Uri.parse(
          "https://api.giphy.com/v1/gifs/search?api_key=h1xGoDG0FsqnKtOmI3I1A8zxBCuxEqUx&q=$_search&limit=25&offset=$_offset&rating=g&lang=en"));

      //return json.decode(response.body); Move this line
    }
    return json.decode(response.body); // to this line     
  }

答案 2 :(得分:0)

你必须在函数 getGifs() 的条件语句之外添加 return 语句 未来 _getGifs() 异步 { http.Response 响应;

if (_search == null) {
  response = await http.get(Uri.parse(
      "https://api.giphy.com/v1/gifs/trending?api_key=h1xGoDG0FsqnKtOmI3I1A8zxBCuxEqUx&limit=20&rating=G"));
} else {
  response = await http.get(Uri.parse(
      "https://api.giphy.com/v1/gifs/search?api_key=h1xGoDG0FsqnKtOmI3I1A8zxBCuxEqUx&q=$_search&limit=25&offset=$_offset&rating=g&lang=en"));


}
return json.decode(response.body);

}