flutter - Flutter 函数返回 null
问题描述
我是新来的。我正在尝试使用 Giphy 的 API 创建一个颤动的 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)
当我尝试访问 webbrowser 时,我的 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,
),
);
},
);
}
}
我错过了什么?
解决方案
请试试
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
}
推荐阅读
- android - 在 Frestore 上删除之前,先在 recyclerView 上完成滑动以删除的动画
- google-sheets - 自动增加 COUNTIF 日期标准
- python - 如何在python中使用随机形成函数的恒定结果
- java - 以下代码如何使用三元运算符查找最多三个数字
- c# - 使用简单的破折号/幻灯片机制 C# Unity2d 进行编码
- c# - this.Close() 不会杀死观察者 NewThreadScheduler.Default.Schedule 创建的线程
- ios - 结构属性闭包在 Swift 中只运行一次
- python - 多序列组的 LSTM 模型
- python - 带有 ANDed 条件的 Django `filter` 和 `Q` 查询方法不起作用
- c# - 如何将日期“2018-12-13T07:33:35.893Z”转换为 13/12/2018