# 我已经处理这个问题很长时间了。 我正在尝试解析 JSON 并将其转换为列表视图。 我正在获取响应正文,它也被转换为列表,但它向未来的构建器发送空值,我收到此错误: #
小部件库捕获的异常 ========================================== ============== 在构建 FutureBuilder(dirty, state: _FutureBuilderState#a289a) 时抛出了以下 _TypeError: 'Null' 类型不是 'List' 类型的子类型
The relevant error-causing widget was:
FutureBuilder<dynamic> file:///Users/metehanmacbook/StudioProjects/flutter_mysql/lib/main.dart:37:13
When the exception was thrown, this was the stack:
#0 _MyHomePageState.build.<anonymous closure> (package:flutter_mysql/main.dart:40:14)
#1 _FutureBuilderState.build (package:flutter/src/widgets/async.dart:775:55)
#2 StatefulElement.build (package:flutter/src/widgets/framework.dart:4691:27)
#3 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4574:15)
#4 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4746:11)
...
**# Codes: #**
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter MySql',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.lime,
),
home: MyHomePage(title: 'Flutter MYSQL'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: FutureBuilder(
future: Getmethod(),
builder: (BuildContext context, AsyncSnapshot snapshot){
List snap = snapshot.data;
if(snapshot.connectionState == ConnectionState.waiting){
return Center(
child: CircularProgressIndicator(),
);
}
if(snapshot.hasError){
return Center(
child: Text('error fatch'),
);
}
return ListView.builder(
itemCount: snap.length,
itemBuilder: (context, index){
return ListTile(
title: Text("Product Name: ${snap[index]['pro_name']}"),
subtitle: Text("Product Desc: ${snap[index]['pro_desc']}"),
);
}
);
},
),
);
}
Getmethod()async{
String theurl = ('http://10.0.2.2/flutter-demo/getdata.php');
var res = await http.get(Uri.parse(Uri.encodeFull(theurl)),headers: {"Accept":"application/json"});
var responseBody = json.decode(res.body);
print(responseBody);
return responseBody;
}
}
我该如何解决这个问题?
答案 0 :(得分:1)
似乎错误是 List snap = snapshot.data;
快照。数据为空,您想将其强制转换为列表。
解决方案:
snap
变量设为 nullable
:List? snap = snapshot.data;
snap
返回 null
,您可以返回默认值(例如空列表):List snap = snapshot.data ?? [];
Getmethod
返回 null
的原因;