我正在尝试运行此代码,但由于person.emp_id作为int变量而出错,有人可以帮忙吗? 我曾尝试制作字符串,但仍然遇到相同的错误,我也尝试在int中进行解析 error: The argument type '(int) → dynamic' can't be assigned to the parameter type '(String) → void'
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() {
runApp(MaterialApp(
home: MyGetHttpData(),
));
}
class MyGetHttpData extends StatefulWidget {
@override
MyGetHttpDataState createState() => MyGetHttpDataState();
}
class MyGetHttpDataState extends State<MyGetHttpData> {
final String url = "https://raw.githubusercontent.com/uc-ach/flutter/master/test.json";
List data;
Future<String> getJSONData() async {
var response = await http.get(
Uri.encodeFull(url),
headers: {"Accept": "application/json"});
print(response.body);
setState(() {
var dataConvertedToJSON = json.decode(response.body);
data = dataConvertedToJSON;
});
return "Successfull";
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Inside Sales User List"),
),
body: ListView.builder(
itemCount: data == null ? 0 : data.length,
itemBuilder: (BuildContext context, int index) {
return Container(
child: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Card(
child: Container(
child: ListTile(
title: Text(
data[index]['name'],
style: TextStyle(
fontSize: 22.0, color: Colors.lightBlueAccent),
),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => new SecondRoute(person: new Person(data[index]['name'],data[index]['post'],data[index]['emp_id']))),
);
},
),
padding: const EdgeInsets.all(15.0),
),
)
],
)),
);
}),
);
}
@override
void initState() {
super.initState();
this.getJSONData();
}
}
class Person {
final String name;
final String post;
int empId;
Person(this.name, this.post, this.empId);
}
class SecondRoute extends StatelessWidget {
final Person person;
SecondRoute({Key key, @required this.person}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Details for " +person.name),
),
body: Padding(
padding: EdgeInsets.all(16.0),
child: Column( children: <Widget>[
Text("Name: " +person.name, style: TextStyle(
fontSize: 20.0),),
Text("Emp Id: " +person.empId, style: TextStyle(
fontSize: 20.0),)
],),
),
);
}
}
答案 0 :(得分:1)
只需将代码更改为
Text("Emp Id: " + person.empId.toString(), style: TextStyle(fontSize: 20.0),)
“ person.empId”是一个int值,您正在将其分配给“文本”窗口小部件,该窗口小部件始终期望使用String值。
答案 1 :(得分:0)
当您在MaterialPageRoute上创建新的Person对象时,您是从json获取数据的,它作为String出现,但是您的Person的id定义为int。将字符串转换为int应该可以解决您的问题:
MaterialPageRoute(builder: (context) => new SecondRoute(
person: new Person(
data[index]['name'],
data[index]['post'],
int.parse(data[index]['emp_id'])
)
)),