Flutter 如何处理此颤振异常(未处理的异常:NoSuchMethodError:方法';findAncestorStateOfType';在null上被调用)
我想从URL获取数据并在listview中显示,但出现了一个错误(未处理的异常:NoSuchMethodError:对null调用了“findAncestorStateOfType”方法)。我找了很多,但我的问题没有解决,我不明白我在这里犯了什么错误。这是我的代码和错误列表。请给我建议Flutter 如何处理此颤振异常(未处理的异常:NoSuchMethodError:方法';findAncestorStateOfType';在null上被调用),flutter,Flutter,我想从URL获取数据并在listview中显示,但出现了一个错误(未处理的异常:NoSuchMethodError:对null调用了“findAncestorStateOfType”方法)。我找了很多,但我的问题没有解决,我不明白我在这里犯了什么错误。这是我的代码和错误列表。请给我建议 import 'package:deviceinstallation/model/order_model.dart'; import 'package:flutter/cupertino.dart'; impor
import 'package:deviceinstallation/model/order_model.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:http/http.dart' as http;
import 'dashboard_screen.dart';
import 'ordercountdetail.dart';
void main()=> runApp(OrderScreen());
class OrderScreen extends StatelessWidget{
@override
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyOrderPage(title: 'Flutter Demo Home Page'),
);
}
}
class MyOrderPage extends StatefulWidget{
@override
MyOrderPage({Key key, this.title}) : super(key: key);
final String title;
@override
OrderScreenState createState() => OrderScreenState();
}
class OrderScreenState extends State<MyOrderPage> {
Icon cusIcon =Icon(Icons.search);
Widget cusSearchBar= Text("Order");
bool _isLoading=false;
final String sUrl= "https://fasttracksoft.us/api_v2/device_installation/";
List<OrderModel> orderList;
BuildContext context;
Future<List<OrderModel>> _orderList()async{
setState(() {
_isLoading=true;
});
final prefs= await SharedPreferences.getInstance();
var params = "myaccount.php?id="+prefs.getString("id")+"&type=" +"order";
print(params);
try{
final res =await http.get(sUrl+params);
//print(res.body);
if(res.statusCode==200){
orderList= orderModelFromJson(res.body);
if(orderList!=null){
setState(() {
_isLoading=false;
});
}
}
}catch(e){
}
return orderList;
}
@override
void initState() {
// TODO: implement initState
super.initState();
setState(()
{
this._orderList();
});
}
@override
Widget build(BuildContext context) {
// TODO: implement build
setState(() => this.context = context);
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back, color: Colors.white),
onPressed: (){
Navigator.push(
context,
MaterialPageRoute(builder: (context) => HomePage()),
);
},
),
title: cusSearchBar,
actions: <Widget>[
IconButton(
onPressed: () {
setState(() {
if(this.cusIcon.icon==Icons.search){
this.cusIcon=Icon(Icons.cancel);
this.cusSearchBar=TextField(
textInputAction: TextInputAction.go,
decoration: InputDecoration(
border: InputBorder.none,
hintText: "Search here",
),
style: TextStyle(
color: Colors.white,
fontSize: 16.0,
),
);
}else{
this.cusIcon =Icon(Icons.search);
this.cusSearchBar= Text("AppBar");
}
});
},
icon: cusIcon,
),
],
),
body: ListView.builder(
itemCount: null== orderList ? 0 : orderList.length ,
itemBuilder: (context, index) {
OrderModel orderModel= orderList[index];
return Padding(
padding: const EdgeInsets.only(
top: 0.0, bottom: 0.0, left: 5.0, right: 5.0),
child: GestureDetector(
onTap: ()=> Navigator.push(context, new MaterialPageRoute(builder: (context)=> new OrderCountDetails())),
child: Card(
elevation: 10,
child: Container(
child: Column(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
width: MediaQuery
.of(context)
.size
.width * 15.5,
color: Colors.green,
padding: const EdgeInsets.only(
top: 10.0, bottom: 10.0, left: 15.0, right: 0.0),
child: Text("NEW ORDER",
style: TextStyle(
fontSize: 20.0,
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
),
new Container(
padding: const EdgeInsets.only(
top: 10.0, bottom: 0.0, left: 10.0, right: 10.0),
child: Text('Customer Name :'+ orderModel.customerName.toString(),
style: TextStyle(
fontSize: 15.0,
fontWeight: FontWeight.bold,
color: Colors.green,
),
),
),
new Container(
padding: const EdgeInsets.only(
top: 0.0, bottom: 0.0, left: 10.0, right: 10.0),
child: Text('Type :'+orderModel.type.toString(),
style: TextStyle(
fontSize: 15.0,
color: Colors.black,
),
),
),
new Container(
padding: const EdgeInsets.only(
top: 0.0, bottom: 0.0, left: 10.0, right: 10.0),
child: Text('Total Devices :',
style: TextStyle(
fontSize: 15.0,
color: Colors.black,
),
),
),
new Container(
padding: const EdgeInsets.only(
top: 0.0, bottom: 0.0, left: 10.0, right: 10.0),
child: Text('Address :'+orderModel.address.toString(),
style: TextStyle(
fontSize: 15.0,
color: Colors.black,
),
),
),
new Container(
padding: const EdgeInsets.only(
top: 0.0, bottom: 10.0, left: 10.0, right: 10.0),
child: Text('New Orders Count :'+orderModel.neworder,
style: TextStyle(
fontSize: 15.0,
color: Colors.black,
),
),
),
],
),
),
),
),
);
},
),
);
}
}
Performing hot restart...
Syncing files to device Mi A2...
Malformed message
Restarted application in 2,060ms.
I/flutter ( 9906): Started the splash screen
I/flutter ( 9906): Finished
E/flutter ( 9906): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: NoSuchMethodError: The method 'findAncestorStateOfType' was called on null.
E/flutter ( 9906): Receiver: null
E/flutter ( 9906): Tried calling: findAncestorStateOfType<NavigatorState>()
E/flutter ( 9906): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
E/flutter ( 9906): #1 Navigator.of (package:flutter/src/widgets/navigator.dart:1492:19)
E/flutter ( 9906): #2 Navigator.pushNamed (package:flutter/src/widgets/navigator.dart:917:22)
E/flutter ( 9906): #3 _MyHomePageState.finished (package:deviceinstallation/splash_screen.dart:59:15)
E/flutter ( 9906): #4 _rootRun (dart:async/zone.dart:1122:38)
E/flutter ( 9906): #5 _CustomZone.run (dart:async/zone.dart:1023:19)
E/flutter ( 9906): #6 _CustomZone.runGuarded (dart:async/zone.dart:925:7)
E/flutter ( 9906): #7 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:965:23)
E/flutter ( 9906): #8 _rootRun (dart:async/zone.dart:1126:13)
E/flutter ( 9906): #9 _CustomZone.run (dart:async/zone.dart:1023:19)
E/flutter ( 9906): #10 _CustomZone.bindCallback.<anonymous closure> (dart:async/zone.dart:949:23)
E/flutter ( 9906): #11 Timer._createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:23:15)
E/flutter ( 9906): #12 _Timer._runTimers (dart:isolate-patch/timer_impl.dart:384:19)
E/flutter ( 9906): #13 _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:418:5)
E/flutter ( 9906): #14 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:174:12)
E/flutter ( 9906):
E/flutter ( 9906): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: Invalid argument(s)
import'包:设备安装/model/order_model.dart';
进口“包装:颤振/cupertino.dart”;
进口“包装:颤振/材料.省道”;
导入“package:shared_preferences/shared_preferences.dart”;
将“package:http/http.dart”导入为http;
导入“dashboard_screen.dart”;
导入“ordercountdetail.dart”;
void main()=>runApp(OrderScreen());
类OrderScreen扩展了无状态小部件{
@凌驾
小部件构建(构建上下文){
//TODO:实现构建
返回材料PP(
debugShowCheckedModeBanner:false,
标题:“颤振演示”,
主题:主题数据(
主样本:颜色。蓝色,
),
主页:MyOrderPage(标题:“颤振演示主页”),
);
}
}
类MyOrderPage扩展了StatefulWidget{
@凌驾
MyOrderPage({Key,this.title}):超级(Key:Key);
最后的字符串标题;
@凌驾
OrderScreenState createState()=>OrderScreenState();
}
类OrderScreenState扩展了状态{
图标cusIcon=图标(Icons.search);
Widget cusSearchBar=文本(“订单”);
bool_isLoading=false;
最终字符串sUrl=”https://fasttracksoft.us/api_v2/device_installation/";
列表订单列表;
构建语境;
Future\u orderList()异步{
设置状态(){
_isLoading=true;
});
final prefs=wait SharedPreferences.getInstance();
var params=“myaccount.php?id=“+prefs.getString(“id”)+”&type=“+”order”;
打印(参数);
试一试{
final res=wait http.get(sUrl+params);
//印刷品(正文);
如果(res.statusCode==200){
orderList=orderModelFromJson(res.body);
if(orderList!=null){
设置状态(){
_isLoading=false;
});
}
}
}捕获(e){
}
返回订单列表;
}
@凌驾
void initState(){
//TODO:实现initState
super.initState();
设置状态()
{
这是._orderList();
});
}
@凌驾
小部件构建(构建上下文){
//TODO:实现构建
setState(()=>this.context=context);
返回脚手架(
appBar:appBar(
领先:IconButton(
图标:图标(Icons.arrow\u back,颜色:Colors.white),
已按下:(){
导航器。推(
上下文
MaterialPackageRoute(生成器:(上下文)=>HomePage()),
);
},
),
标题:库斯切巴,
行动:[
图标按钮(
已按下:(){
设置状态(){
if(this.cusIcon.icon==Icons.search){
this.cusIcon=Icon(Icons.cancel);
this.cusSearchBar=TextField(
textInputAction:textInputAction.go,
装饰:输入装饰(
边框:InputBorder.none,
hintText:“在此处搜索”,
),
样式:TextStyle(
颜色:颜色,白色,
字体大小:16.0,
),
);
}否则{
this.cusIcon=Icon(Icons.search);
this.cusSearchBar=文本(“AppBar”);
}
});
},
图标:cusIcon,
),
],
),
正文:ListView.builder(
itemCount:null==orderList?0:orderList.length,
itemBuilder:(上下文,索引){
OrderModel OrderModel=订单列表[索引];
返回填充(
填充:仅限常量边设置(
顶部:0.0,底部:0.0,左侧:5.0,右侧:5.0),
儿童:手势检测器(
onTap:()=>Navigator.push(上下文,new MaterialPage路由(生成器:(上下文)=>new OrderCountDetails()),
孩子:卡片(
标高:10,
子:容器(
子:列(
mainAxisSize:mainAxisSize.max,
crossAxisAlignment:crossAxisAlignment.start,
儿童:[
容器(
宽度:MediaQuery
.of(上下文)
.尺寸
.宽度*15.5,
颜色:颜色。绿色,
填充:仅限常量边设置(
顶部:10.0,底部:10.0,左侧:15.0,右侧:0.0),
子项:文本(“新订单”,
样式:TextStyle(
字体大小:20.0,
颜色:颜色,白色,
fontWeight:fontWeight.bold,
),
),
),
新容器(
填充:仅限常量边设置(
顶部:10.0,底部:0.0,左侧:10.0,右侧:10.0),
子项:Text('Customer Name:'+orderModel.customerName.toString(),
样式:TextStyle(
字体大小:15.0,
fontWeight:fontWeight.bold,
颜色:颜色。绿色,
),
),
),
新容器(
填充:仅限常量边设置(
顶部:0.0,底部:0.0,左侧:10.0,右侧:10.0),
子项:Text('Type:'+orderModel.Type.toString(),
样式:TextStyle(
@override
Widget build(BuildContext context) {
// TODO: implement build
setState(() => this.context = context);
@override
void initState() {
// TODO: implement initState
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
_orderList();
});
}
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
List<OrderModel> orderModelFromJson(String str) =>
List<OrderModel>.from(json.decode(str).map((x) => OrderModel.fromJson(x)));
String orderModelToJson(List<OrderModel> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class OrderModel {
OrderModel({
this.neworder,
this.address,
this.type,
this.customerName,
});
String neworder;
String address;
String type;
String customerName;
factory OrderModel.fromJson(Map<String, dynamic> json) => OrderModel(
neworder: json["neworder"],
address: json["address"],
type: json["type"],
customerName: json["customerName"],
);
Map<String, dynamic> toJson() => {
"neworder": neworder,
"address": address,
"type": type,
"customerName": customerName,
};
}
void main() => runApp(OrderScreen());
class OrderScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyOrderPage(title: 'Flutter Demo Home Page'),
);
}
}
class MyOrderPage extends StatefulWidget {
@override
MyOrderPage({Key key, this.title}) : super(key: key);
final String title;
@override
OrderScreenState createState() => OrderScreenState();
}
class OrderScreenState extends State<MyOrderPage> {
Icon cusIcon = Icon(Icons.search);
Widget cusSearchBar = Text("Order");
bool _isLoading = false;
final String sUrl = "https://fasttracksoft.us/api_v2/device_installation/";
List<OrderModel> orderList;
BuildContext context;
Future<List<OrderModel>> _orderList() async {
setState(() {
_isLoading = true;
});
/*final prefs= await SharedPreferences.getInstance();
var params = "myaccount.php?id="+prefs.getString("id")+"&type=" +"order";
print(params);*/
try {
//final res =await http.get(sUrl+params);
//print(res.body);
String jsonString = '''
[
{
"neworder" : "order 1",
"address" : "abc",
"type" : "def",
"customerName": "aaa"
},
{
"neworder" : "order 2",
"address" : "abc1",
"type" : "def1",
"customerName": "aaa1"
}
]
''';
await Future.delayed(Duration(seconds: 3), () {});
final res = http.Response(jsonString, 200);
if (res.statusCode == 200) {
orderList = orderModelFromJson(res.body);
if (orderList != null) {
setState(() {
_isLoading = false;
});
}
}
} catch (e) {}
return orderList;
}
@override
void initState() {
// TODO: implement initState
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
_orderList();
});
}
@override
Widget build(BuildContext context) {
// TODO: implement build
//setState(() => this.context = context);
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back, color: Colors.white),
onPressed: () {
/*Navigator.push(
context,
MaterialPageRoute(builder: (context) => HomePage()),
);*/
},
),
title: cusSearchBar,
actions: <Widget>[
IconButton(
onPressed: () {
setState(() {
if (this.cusIcon.icon == Icons.search) {
this.cusIcon = Icon(Icons.cancel);
this.cusSearchBar = TextField(
textInputAction: TextInputAction.go,
decoration: InputDecoration(
border: InputBorder.none,
hintText: "Search here",
),
style: TextStyle(
color: Colors.white,
fontSize: 16.0,
),
);
} else {
this.cusIcon = Icon(Icons.search);
this.cusSearchBar = Text("AppBar");
}
});
},
icon: cusIcon,
),
],
),
body: ListView.builder(
itemCount: null == orderList ? 0 : orderList.length,
itemBuilder: (context, index) {
OrderModel orderModel = orderList[index];
return Padding(
padding: const EdgeInsets.only(
top: 0.0, bottom: 0.0, left: 5.0, right: 5.0),
child: GestureDetector(
//onTap: ()=> Navigator.push(context, new MaterialPageRoute(builder: (context)=> new OrderCountDetails())),
child: Card(
elevation: 10,
child: Container(
child: Column(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
width: MediaQuery.of(context).size.width * 15.5,
color: Colors.green,
padding: const EdgeInsets.only(
top: 10.0, bottom: 10.0, left: 15.0, right: 0.0),
child: Text(
"NEW ORDER",
style: TextStyle(
fontSize: 20.0,
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
),
new Container(
padding: const EdgeInsets.only(
top: 10.0, bottom: 0.0, left: 10.0, right: 10.0),
child: Text(
'Customer Name :' +
orderModel.customerName.toString(),
style: TextStyle(
fontSize: 15.0,
fontWeight: FontWeight.bold,
color: Colors.green,
),
),
),
new Container(
padding: const EdgeInsets.only(
top: 0.0, bottom: 0.0, left: 10.0, right: 10.0),
child: Text(
'Type :' + orderModel.type.toString(),
style: TextStyle(
fontSize: 15.0,
color: Colors.black,
),
),
),
new Container(
padding: const EdgeInsets.only(
top: 0.0, bottom: 0.0, left: 10.0, right: 10.0),
child: Text(
'Total Devices :',
style: TextStyle(
fontSize: 15.0,
color: Colors.black,
),
),
),
new Container(
padding: const EdgeInsets.only(
top: 0.0, bottom: 0.0, left: 10.0, right: 10.0),
child: Text(
'Address :' + orderModel.address.toString(),
style: TextStyle(
fontSize: 15.0,
color: Colors.black,
),
),
),
new Container(
padding: const EdgeInsets.only(
top: 0.0, bottom: 10.0, left: 10.0, right: 10.0),
child: Text(
'New Orders Count :' + orderModel.neworder,
style: TextStyle(
fontSize: 15.0,
color: Colors.black,
),
),
),
],
),
),
),
),
);
},
),
);
}
}