Home > Software engineering >  How to pass the value of an object within a Stateful widget?
How to pass the value of an object within a Stateful widget?

Time:04-06

How do I pass the value of index from the constructor of Test to the build method?

class Test extends StatefulWidget {
  final int index;  //How do I pass the value of this index....
  const Test(this.index);

  @override
  State<Test> createState() => _TestState();
}

class _TestState extends State<Test> {
  @override
  Widget build(BuildContext context) {
    getFollowers(index).then((response) {   //..to here?
      setState(() {
        Iterable followerPlaceHolder = json.decode(response.body);
        followerList =
            followerPlaceHolder.map((model) => Data.fromJson(model)).toList();
      });
    });

    return SafeArea(
      child: Scaffold(
        body: ExpansionTile(
          title: const Text("Followers"),
          children: [
            ListView.builder(
              itemCount: followerList.length,
              scrollDirection: Axis.vertical,
              itemBuilder: (context, value) {
                return ListTile(
                  leading: CircleAvatar(
                    backgroundImage:
                        NetworkImage(followerList[value].avatarUrl),
                  ),
                );
              },
            ),
          ],
        ),
      ),
    );
  }
}

CodePudding user response:

You can access widget.index in the build method.

CodePudding user response:

just call any value in statefulWidget class with widget.varName(your variable name)

CodePudding user response:

Just use widget.index

class Test extends StatefulWidget {
  final int index;  //How do I pass the value of this index....
  const Test(this.index);
  @override
  State<Test> createState() => _TestState();
}

class _TestState extends State<Test> {
  @override
  Widget build(BuildContext context) {
   
    return SafeArea(
      child: Scaffold(
        body: Text(widget.index.toString()),  // just use widget.index
      ),
    );
  }
}
  • Related