簡體   English   中英

如何在有狀態小部件中傳遞 object 的值?

[英]How to pass the value of an object within a Stateful widget?

如何將index的值從Test的構造函數傳遞到build方法?

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),
                  ),
                );
              },
            ),
          ],
        ),
      ),
    );
  }
}

您可以在構建方法中訪問widget.index

只需使用widget.varName (您的變量名)調用 statefulWidget class 中的任何值

只需使用 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
      ),
    );
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM