Flutter how to pass array and show in other widget - flutter

I have a list of arrays i need to pass it to the other stateful widget and show the array there
This is my function code which retrieve data from API
Future<List> doSomeAsyncStuff() async {
final storage = new FlutterSecureStorage();
String value = await storage.read(key: 'Cnic');
print(value);
String url = 'http://api.php?offset=0&limit=1&cnic=${value}' ;
final msg = jsonEncode({"cnic": value});
Map<String,String> headers = {'Content-Type':'application/json'};
String token = value;
final response = await http.get(url);
var Data = json.decode(response.body);
print(Data);
var familyMembers = Data["records"][0]["family_members"];
print(familyMembers);
for (var familyMember in familyMembers){ //prints the name of each family member
print(familyMember["name"]);
print(familyMember["gender"]);
}
}
As you can see there is 2 list familyMember["name"] and familyMember["gender"] i need to pass it to statefulwidget
I am simple passing it like this
Navigator.push(
context,
MaterialPageRoute(builder: (context) => PersonalPage(familyMember["name"], familyMember["gender"])),
);
This is my other stateful widget I need to show the array of name and gender here
import 'package:flutter/material.dart';
class PersonalPage extends StatefulWidget {
final String name;
final String gender;
PersonalPage(this.name, this.gender);
#override
_PersonalPageState createState() => _PersonalPageState();
}
class _PersonalPageState extends State<PersonalPage> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text('I need to print name and gender here ')
),
);
}
}
flut

Try this and change your code as per this: As your First Page code is missing I have created a dummy forst Page.
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
title: 'My APP',
home: FirstRoute(),
));
}
class FirstRoute extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('List of ....'),
),
body: Center(
child: RaisedButton(
child: Text('Open details'),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => PersonalPage("NAME","GENDER")),
);
},
),
),
);
}
}
class PersonalPage extends StatefulWidget {
final String name;
final String gender;
PersonalPage(this.name, this.gender);
#override
_PersonalPageState createState() => _PersonalPageState();
}
class _PersonalPageState extends State<PersonalPage> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Row(
children : [
Text(widget.name),
Text(widget.gender),
]
)
),
);
}
}

You are doing wrong you are passing list and in stateful widget you mention its a string you can do something like this
List<String> familyMemberName = [];
List<String> familyMemberGender = [];
Future<List> doSomeAsyncStuff() async {
final storage = new FlutterSecureStorage();
String value = await storage.read(key: 'Cnic');
print(value);
String url = 'http://api.php' ;
final msg = jsonEncode({"cnic": value});
Map<String,String> headers = {'Content-Type':'application/json'};
String token = value;
final response = await http.get(url);
var Data = json.decode(response.body);
print(Data);
var familyMembers = Data["records"][0]["family_members"];
print(familyMembers);
for (var familyMember in familyMembers){
familyMemberName.add(familyMember["name"]);
familyMemberGender.add(familyMember["gender"]);
print(familyMemberName);
}
}
and in you personal widget like this
import "package:flutter/material.dart";
class PersonalPage extends StatefulWidget {
final List<String> names;
final List<String> relation;
PersonalPage(this.names,this.relation);
#override
_PersonalPageState createState() => _PersonalPageState();
}
class _PersonalPageState extends State<PersonalPage> {
#override
Widget build(BuildContext context) {
return Scaffold(
body:
ListView.builder( //use ListView here to show all the names and genders
itemCount: widget.names.length,
itemBuilder: (BuildContext context,int index){
return Padding(
padding: EdgeInsets.only(left: 10, right: 10, bottom: 10, top: 10),
child: Card(
child: Padding(
padding: EdgeInsets.all(5),
child: Column(
children: <Widget>[
Row(
children: <Widget>[
Text('Name:', style: TextStyle(color: Colors.blue, fontWeight: FontWeight.bold),),
Text(widget.names[index])
],
),
Row(
children: <Widget>[
Text('Gender:', style: TextStyle(color: Colors.blue, fontWeight: FontWeight.bold),),
Text(widget.genders[index])
],
),
],
),
),
),
);
})
);
}
}
Sorry i test code so thats why i add it in card

Text(widget.name)
Text(widget.gender)
or
Text("My name is ${widget.name} and my gender is ${widget.gender}")

Related

Can't get the futurebuilder data into the dropdownbutton to pick from there

I am trying to get some String data from a server via future builder, which works. Then transfer those strings into the dropdownbutton thing, to show as options then to be picked. I mean they will show up on dropdownbutton. Think of it like, I will choose a person to do a job here, I get the names from a database and show it on screen. So user can choose from there. Here is the important data that supposedly gets the dropdown data from the futurebuilder:
String dropdownValue = _MyAppState.data2.first;
It gives the following error:
Bad state: No element
And here is my code:
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
const List<String> list = <String>['One', 'Two', 'Three', 'Four'];
Future<List<Album>> fetchAlbum() async {
final response = await http.get(
Uri.parse('https://my-json-server.typicode.com/fluttirci/testJson/db'));
//this was for testing.
//print(response);
Map<String, dynamic> userMap = jsonDecode(response.body);
if (response.statusCode == 200) {
return (userMap['employees'] as List)
.map((e) => Album.fromJson(e))
.toList();
} else {
throw Exception('Failed to load album');
}
}
class Album {
final int userId;
final int id;
final String title;
Album(this.userId, this.id, this.title);
Album.fromJson(Map<String, dynamic> json)
: userId = json['userId'],
id = json['id'],
title = json['title'];
Map<String, dynamic> toJson() => {
'userId': userId,
'id': id,
'title': title,
};
}
void main() => runApp(const MyApp());
class MyApp extends StatefulWidget {
const MyApp({super.key});
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late Future<Album> futureAlbum;
late Future<List<Album>> user;
late List<Album> data;
static List<String> data2 = [];
#override
void initState() {
super.initState();
user = fetchAlbum();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Fetch Data Example',
theme: ThemeData(
brightness: Brightness.dark,
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: const Text('Fetch Data Example'),
),
body: Column(children: <Widget>[
const Expanded(
child: DropdownButtonExample(),
),
Expanded(
child: FutureBuilder<List<Album>>(
future: user,
builder: (context, snapshot) {
if (snapshot.hasData) {
data = snapshot.data ?? [];
return ListView.builder(
itemBuilder: (context, index) {
data2.add(data[index].title);
print('data2 was fetched: ${data2[index]}');
return Column(
children: [
Text(data[index].title),
],
);
},
itemCount: data.length,
);
} else if (snapshot.hasError) {
return Text(
'${snapshot.error}',
);
}
return const Center(
child: CircularProgressIndicator(),
);
},
),
)
]),
),
);
}
}
class DropdownButtonApp extends StatelessWidget {
const DropdownButtonApp({super.key});
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('DropdownButton Sample')),
body: const Center(
child: DropdownButtonExample(),
),
),
);
}
}
class DropdownButtonExample extends StatefulWidget {
const DropdownButtonExample({super.key});
#override
State<DropdownButtonExample> createState() => _DropdownButtonExampleState();
}
class _DropdownButtonExampleState extends State<DropdownButtonExample> {
String dropdownValue = _MyAppState.data2.first;
#override
Widget build(BuildContext context) {
return DropdownButton<String>(
value: dropdownValue,
icon: const Icon(Icons.arrow_downward),
elevation: 16,
style: const TextStyle(color: Colors.deepPurple),
underline: Container(
height: 2,
color: Colors.deepPurpleAccent,
),
onChanged: (String? value) {
// This is called when the user selects an item.
setState(() {
dropdownValue = value!;
});
},
items: list.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
);
}
}
There are more than one error in your code.
Error 1 :
You are trying to access first element from empty list. At
String dropdownValue = _MyAppState.data2.first;
Actual issue of Bad state: No element
You can give only dropdown items as value. In your case the data coming from api and hardcoded list List<String> list = <String>['One', 'Two', 'Three', 'Four']; both are different.
Hope this helps

Update Text with Dissmissble setState

I want to update my Text() value whenever I dismiss an item from the screen .
This is the MainScreen() :
Text.rich(
TextSpan(
text: total().toString() + " DT",
style: TextStyle(
fontSize: 16,
color: Colors.black,
fontWeight: FontWeight.bold),
),
The function total() is located in Product Class like this :
class Product {
final int? id;
final String? nameProd;
final String? image;
final double? price;
Product({this.id, this.nameProd, this.image, this.price});
}
List<Product> ListProduitss = [
Product(
price: 100, nameProd: 'Produit1', image: 'assets/images/freedomlogo.png')
];
double total() {
double total = 0;
for (var i = 0; i < ListProduitss.length; i++) {
total += ListProduitss[i].price!;
}
print(total);
return total;
}
I have this in the main screen .
After I remove the item from list , I want to reupdate the Text() because the function is printing a new value in console everytime I dismiss a product :
This is from statefulWidget CartItem() that I render inside MainScreen() :
ListView.builder(
itemCount: ListProduitss.length,
itemBuilder: (context, index) => Padding(
padding: EdgeInsets.symmetric(vertical: 10),
child: Dismissible(
key: Key(ListProduitss.toString()),
direction: DismissDirection.endToStart,
onDismissed: (direction) {
setState(() {
ListProduitss.removeAt(index);
total();
// What to add here to update Text() value everytime
});
},
I tried to refresh the main screen but It didn't work .
onDismissed: (direction) {
setState(() {
ListProduitss.removeAt(index);
MainScreen();
});
},
One way is to declare a local string variable to use within the text. Then initialise the variable using total() within initState(). Then in setState do the same process.
However, it may be beneficial for you to look into a state management pattern such as BLoC pattern. https://bloclibrary.dev/#/
late String text;
void initState() {
super.initState();
text = Product.total();
}
Widget build(BuildContext context) {
return Scaffold(
extendBody: true,
appBar: AppBar(),
body: Column(
children: [
Text(text),
ElevatedButton(child: Text("Update"), onPressed:() => setState(() {
text = Product.total();
}),)
],
)
);
}
I am going to add another example as there was confusion to the above example. Below is an example of updated a text field with the length of the list. It is updated every time an item is removed.
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Code Sample';
#override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: const MyStatefulWidget(),
),
);
}
}
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({Key? key}) : super(key: key);
#override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
List<int> items = List<int>.generate(100, (int index) => index);
late String text;
#override
void initState() {
text = items.length.toString(); // << this is total;
super.initState();
}
#override
Widget build(BuildContext context) {
return Column(
children: [
Text(text),
Expanded(
child: ListView.builder(
itemCount: items.length,
padding: const EdgeInsets.symmetric(vertical: 16),
itemBuilder: (BuildContext context, int index) {
return Dismissible(
background: Container(
color: Colors.green,
),
key: ValueKey<int>(items[index]),
onDismissed: (DismissDirection direction) {
setState(() {
items.removeAt(index);
text = items.length.toString(); // < this is total()
});
},
child: ListTile(
title: Text(
'Item ${items[index]}',
),
),
);
},
),
),
],
);
}
}

Flutter post HTTP request

I'm trying to send a post request and then get some response. This is the site: www.reqres.in and the user data https://reqres.in/api/users.
When I press the Button I don't see any text. Posting name and job to an API and receiving name, id, Datetime and job. If I don't use Widget _showData and show the text in the build below text field then I see the Data, but with a lateInitialization error, but I want to show it using the Widget _showData.
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:http_req_advanced/usermodel.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'HTTP Request 2',
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
var users;
Future<UserModel> createUser(String name, String job) async {
final apiUrl = "https://reqres.in/api/users";
final response =
await http.post(Uri.parse(apiUrl), body: {"name": name, "job": job});
if (response.statusCode == 201) {
users = userModelFromJson(response.body);
} else
throw Exception('Failed to load');
return users;
}
late UserModel user;
final nameController = TextEditingController();
final jobController = TextEditingController();
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
title: Text('HTTP Request'),
),
body: Container(
padding: EdgeInsets.all(16),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextField(
controller: nameController,
),
TextField(
controller: jobController,
),
//Text(
// "The user ${user.name} ${user.id} is created at ${user.createdAt} with job${user.job}"),
ElevatedButton(
onPressed: () async {
final String name = nameController.text;
final String job = jobController.text;
final UserModel userr = await createUser(name, job);
setState(() {
user = userr;
_showData(user.name, user.job, user.id, user.createdAt);
});
},
child: Text('Make a Request'),
),
],
),
),
),
);
}
Widget _showData(String name, String job, String id, DateTime createdat) {
return Container(
alignment: Alignment.bottomCenter,
child: SizedBox(
height: 32,
child:
Text('The user $name [$id] is created at $createdat with job $job'),
),
);
}
}
Instead of using late initialization:
late UserModel user;
Use:
UserModel? user;
When you use late you are declaring a non null variable that will be later initialized, in this case you don't need to use late because user can be null.
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:http_req_advanced/usermodel.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'HTTP Request 2',
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
var users;
Future<UserModel> createUser(String name, String job) async {
final apiUrl = "https://reqres.in/api/users";
final response =
await http.post(Uri.parse(apiUrl), body: {"name": name, "job": job});
if (response.statusCode == 201) {
users = userModelFromJson(response.body);
} else
throw Exception('Failed to load');
return users;
}
late UserModel user;
final nameController = TextEditingController();
final jobController = TextEditingController();
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
title: Text('HTTP Request'),
),
body: Container(
padding: EdgeInsets.all(16),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextField(
controller: nameController,
),
TextField(
controller: jobController,
),
user != null
? _showData(user.name, user.job, user.id, user.createdAt)
: Container(),
//Text(
// "The user ${user.name} ${user.id} is created at ${user.createdAt} with job${user.job}"),
ElevatedButton(
onPressed: () async {
final String name = nameController.text;
final String job = jobController.text;
final UserModel userr = await createUser(name, job);
setState(() {
user = userr;
});
},
child: Text('Make a Request'),
),
],
),
),
),
);
}
Widget _showData(String name, String job, String id, DateTime createdat) {
return Container(
alignment: Alignment.bottomCenter,
child: SizedBox(
height: 32,
child:
Text('The user $name [$id] is created at $createdat with job $job'),
),
);
}
}

Flutter Shared Preferences acces in other class

In the following class I have created a ListView of Strings which are stored sing shared preferences. Now I need to access the content of List<String> categoryList in another class. I do not know where to implement a get function to give other classes access to this List.
One Idea was to create a class for the List (But I dont want to mess up everything)
That is my Class with the List View
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
class Categories extends StatefulWidget {
#override
_CategoriesState createState() => _CategoriesState();
}
class _CategoriesState extends State<Categories> {
List<String> categoryList = List<String>();
TextEditingController _textFieldController = TextEditingController();
#override
Widget build(BuildContext context) {
_update();
return Scaffold(
appBar: AppBar(
title: Text("Categories"),
),
body: SafeArea(
child: Container(
color: Colors.white,
child: getCategoriesListView(),
),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {
setState(() {
_displayDialog(context);
});
},
),
);
}
ListView getCategoriesListView() {
return ListView.builder(
itemCount: categoryList.length,
itemBuilder: (context, int position) {
return Card(
color: Colors.white,
elevation: 2.0,
child: ListTile(
title: Text(categoryList[position]),
trailing: GestureDetector(
child: Icon(
Icons.delete,
color: Colors.grey,
),
onTap: () {
setState(() {
_delete(context, categoryList[position]);
});
},
),
),
);
});
}
void _add(BuildContext context, String category) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
categoryList.add(category);
prefs.setStringList('Categories', categoryList);
}
void _delete(BuildContext context, String category) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
categoryList.remove(category);
prefs.setStringList('Categories', categoryList);
}
void _update() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
categoryList = prefs.getStringList('Categories');
});
}
void showSnackBar(BuildContext context, String message) async {
final snackBar = SnackBar(content: Text(message));
Scaffold.of(context).showSnackBar((snackBar));
}
_displayDialog(BuildContext context) async {
_textFieldController.clear();
return showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text('Add new category'),
content: TextField(
controller: _textFieldController,
),
actions: <Widget>[
FlatButton(
child: Text('ADD'),
onPressed: () {
setState(() {
String name = _textFieldController.text;
_add(context, name);
Navigator.of(context).pop();
});
},
),
FlatButton(
child: Text('CANCEL'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
});
}
}
Second Class
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
class MonthlyOverview extends StatefulWidget {
#override
_MonthlyOverviewState createState() => _MonthlyOverviewState();
}
class _MonthlyOverviewState extends State<MonthlyOverview> {
List<String> _categories = new List<String>();
#override
Widget build(BuildContext context) {
_getCategory().then((value) {
_categories = value;
});
print(_categories);
return Scaffold(
appBar: AppBar(),
body: Container(
color: Colors.white,
),
);
}
_getCategory() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
List<String> categoryList = prefs.getStringList('Categories');
return categoryList;
}
}
Console output
I/flutter (13417): []
#Frederik, have you tried implementing a get function in your second class and accessing the list? It could be something like this in your second class,
_getCategory() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
List<String> categoryList = prefs.getStringList('Categories');
return categoryList;
}
Call (depends on where you're calling it but this should give you an idea):
List<String> _categories = new List<String>();
_getCategory().then((value) {
_categories = value;
});
//Your _categories has the value now , use it here.
Full code:
void main() {
runApp(MaterialApp(
home: new MyApp(),
routes: <String, WidgetBuilder>{
"/monthlyOverview" : (BuildContext context)=> new MonthlyOverview(),
//add more routes here
}
));
}
class MyApp extends StatefulWidget {
#override
MyAppState createState() => MyAppState();
}
class MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Test'),
),
body: Padding(
padding: EdgeInsets.all(20.0),
child: Center(
child: FlatButton(
child: Text('Next', style: TextStyle(fontSize: 18.0, fontWeight: FontWeight.bold),),
onPressed: () async {
List<String> categoryList = ['Item 1', 'Item 2', 'Item 3'];
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setStringList('Categories', categoryList);
Navigator.of(context).pushNamed("/monthlyOverview");
},
)
)
),
);
}
}
class MonthlyOverview extends StatefulWidget {
#override
_MonthlyOverviewState createState() => _MonthlyOverviewState();
}
class _MonthlyOverviewState extends State<MonthlyOverview> {
List<String> _categories = new List<String>();
#override
void initState() {
super.initState();
_getCategory().then((value) {
_categories = value;
setState(() {});
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Center(
child: Container(
color: Colors.white,
child: _categories.length > 0 ? Text(_categories[0] + '\n' + _categories[1] + '\n' + _categories[2], style: TextStyle(fontSize: 18.0, fontWeight: FontWeight.bold),) : Text(''),
)
),
);
}
_getCategory() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
List<String> categoryList = prefs.getStringList('Categories');
return categoryList;
}
}
Hope this helps.

Error : the argument type int cannot be assigned to the parameter type string

I am trying to run this code but getting error for person.emp_id as its an int variable, can anyone help ?
I have tried making string, but still I get same error, I also tried parsing in 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),)
],),
),
);
}
}
Just change your code to
Text("Emp Id: " + person.empId.toString(), style: TextStyle(fontSize: 20.0),)
"person.empId" is an int value and you are assigning it to the Text widget which expects always a String value.
When you are creating your new Person object on the MaterialPageRoute you are getting the data from json and it comes as a String, but your Person has the id defined as an int. Converting the string to an int should fix your issue:
MaterialPageRoute(builder: (context) => new SecondRoute(
person: new Person(
data[index]['name'],
data[index]['post'],
int.parse(data[index]['emp_id'])
)
)),