problem in passing values between classes in flutter

-1

I am still training on flutter so no full knowledge yet.

Now I am trying to receive an array of data from a web server on the app in form of list I created the API and it worked the idea now is that I have a list of contacts and each contact received its data and viewing it in middle of this data is the id of the contact I want when I click on a contact its id sent to another class which is the details of the contact page so the in the details page it sends the id to the API again to receive a full data about the contact but when I do that it says cannot receive a null value can anybody help the first-page code and the second page and the error in the emulatorno such method error the getter length was called on null receiver: null tried calling: lenght

class topfreelancers extends StatefulWidget {
@override
_topfreelancers createState() => _topfreelancers();
}

class _topfreelancers extends State<topfreelancers> {
List data = [];


@override
void initState() {
fetchData();
super.initState();
}

void fetchData() async {
final response = await http.get('http://10.0.2.2/phpapi/getfreelancers.php');

if (response.statusCode == 200) {
setState(() {
data = json.decode(response.body);
});
}
}
@override
Widget build(BuildContext context) {
return
Column(
children: <Widget>[
Row(children: <Widget>[
SizedBox(width:15),
Text(
'Weekly Top 10 Freelancers',
textAlign: TextAlign.left,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontWeight: FontWeight.normal ,fontSize: 18),
)
],)
,SizedBox(height: 20),
Container(
height:200,
width:MediaQuery.of(context).size.width,
child:ListView.builder(
physics: BouncingScrollPhysics(),
scrollDirection: Axis.horizontal,
itemCount: data.length,
itemBuilder: (BuildContext context, int index) =>
Container(
child:
Row(children: <Widget>[
SizedBox(width:10),
Column(
children: <Widget>[
Stack(
children: <Widget>[
Column(children: <Widget>[
Stack(
children: <Widget>[
SizedBox(height:10),
CircleAvatar(
backgroundImage:
NetworkImage(data[index]['image']),
child:FlatButton(
color: Colors.transparent,
splashColor: Colors.transparent,
onPressed: (){
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => information(id:data[index]['id'])
));
}
) ,
radius: 60,
),
],
),
Row(
children: <Widget>[
SizedBox(width:5),
Container(
width: 40,
height: 20,
decoration: BoxDecoration(
color: const Color(0xffffffff),
borderRadius: BorderRadius.circular(10),
boxShadow:[BoxShadow(offset: const Offset(0,3), blurRadius: 6,color: const Color(0xff000000).withOpacity(0.16),)],
),
child:Row(children:<Widget>[
SizedBox(width:2),
Icon(Icons.star,color:Colors.yellow,size:20),
SizedBox(width:1),
Text(
data[index]['id'],
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: 'SF Display',
fontSize: 11,
color: Color(0xff202020),
),
)],),
)
],
)
],)
],
),
SizedBox(height:5),
Text(
data[index]['name'],
textAlign: TextAlign.center,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontWeight: FontWeight.bold,fontSize: 15),
),
SizedBox(height:5),
Text(
data[index]['category'],
textAlign: TextAlign.center,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontWeight: FontWeight.normal,fontSize: 12),
)
],
)
],)
)
),
),
Row(
children: <Widget>[
SizedBox(width:700),
GestureDetector(onTap: (){
null;
},
child:
const Text(
'see more',
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: 'SF Display',
fontSize: 16,
color: Color(0xff2a3377),
decoration: TextDecoration.underline,
),
),
)
],
)
]
);

}
}

the second page

class ApiProvider {

  final String key =information().id;


  Future<Post> fetchPost() async {



    final response = await http.post("https://10.0.2.2/phpapi/select.php", body:{"key": key});


    if (response.statusCode == 200) {
      return  Post.fromJson(json.decode(response.body));
    } else {
      throw Exception('Failed to load post');
    }
  }
}



class Post{
  final  userid;
  final  username;
  final  userphone;
  Post({this.userid,this.username,this.userphone});
  factory Post.fromJson(Map<String, dynamic> json){
    return Post(
      userid: json['id'],
      username: json['name'],
      userphone: json['phone'],
    );
  }
}


class information extends StatefulWidget {
  String id;
  information({this.id});


  @override
  _data createState() => _data();
}

class _data extends State<information> {

  final Future<Post> post = ApiProvider().fetchPost();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(),
        body:
        Center(
            child: FutureBuilder<Post>(
                future: post,
                builder: (context, snapshot){
                  if (snapshot.hasData){
                    return
                      Column(
                        children: <Widget>[
                          SizedBox(height:80),
                          SizedBox(height:80),
                          SizedBox(height:80),
                          Text(snapshot.data.userid),
                          Text(snapshot.data.username),
                          Text(snapshot.data.userphone)
                        ],
                      );
                  }else if (snapshot.hasError){
                    return Text("${snapshot.error}");
                  }
                  return CircularProgressIndicator();
                }
            )
        )
    );
  }
}
android
flutter
asked on Stack Overflow Aug 3, 2020 by Shady Essam • edited Aug 4, 2020 by Shady Essam

1 Answer

1

You can use initState and set parameter with fetchPost(widget.id)
code snippet

Future<Post> fetchPost(String key) async {
    final response = await http
        .post("https://10.0.2.2/phpapi/select.php", body: {"key": key});
... 
class _data extends State<information> {
  Future<Post> post;

  @override
  void initState() {
    super.initState();
    post = ApiProvider().fetchPost(widget.id);
  }

full code snippet

class ApiProvider {
  //final String key = information().id;

  Future<Post> fetchPost(String key) async {
    final response = await http
        .post("https://10.0.2.2/phpapi/select.php", body: {"key": key});

    if (response.statusCode == 200) {
      return Post.fromJson(json.decode(response.body));
    } else {
      throw Exception('Failed to load post');
    }
  }
}

class information extends StatefulWidget {
  String id;
  information({this.id});

  @override
  _data createState() => _data();
}

class _data extends State<information> {
  Future<Post> post;

  @override
  void initState() {
    super.initState();
    post = ApiProvider().fetchPost(widget.id);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(),
        body: Center(
            child: FutureBuilder<Post>(
                future: post,
                builder: (context, snapshot) {
                  if (snapshot.hasData) {
                    return Column(
                      children: <Widget>[
                        SizedBox(height: 80),
                        SizedBox(height: 80),
                        SizedBox(height: 80),
                        Text(snapshot.data.userid),
                        Text(snapshot.data.username),
                        Text(snapshot.data.userphone)
                      ],
                    );
                  } else if (snapshot.hasError) {
                    return Text("${snapshot.error}");
                  }
                  return CircularProgressIndicator();
                })));
  }
}
answered on Stack Overflow Aug 4, 2020 by chunhunghan

User contributions licensed under CC BY-SA 3.0