【问题标题】:How to pass value from initstate to widgets in flutter如何将值从initstate传递给flutter中的小部件
【发布时间】:2021-10-25 09:39:36
【问题描述】:

在我的应用程序中,我对 initstate 进行了 api 调用,我能够检索响应数据

void initState() {
    super.initState();
    _dbHelper.getAllUserData().then((value)async{
      userdetails = value;
      await getsubjectList(value[0].userId!, value[0].accountId!).then((value){
        testfunction(value);
      });
    });
  } 

我需要将其响应传递给 ListViewBuilder 以在应用程序上显示该值,我该如何实现?

【问题讨论】:

    标签: flutter flutter-widget flutter-listview


    【解决方案1】:

    在你的班级声明一个列表:

    List<YourObject> list = [];
    

    在列表中设置你的值(最好创建一个填充列表的函数:

    fetchData() {
       List<YourObject> tempList = ... get the data ...;
    
       setState(() { list = tempList; });
    }
    

    在您的initState() 中致电fetchData

    然后创建 ListView:

       ListView.builder(
            itemCount: list.length,
            physics: AlwaysScrollableScrollPhysics()
            itemBuilder: (context, index){
              return ListTile(
                title: Text("${list[index].toString()}")
                );
            }
        ),
    

    我也希望你有一个有状态的小部件,而不是无状态的。

    【讨论】:

      【解决方案2】:

      首先,您在itemCount 中调用列表的长度,在这里我返回列表生成器ListTile,您可以将其更改为您的自定义设计:

      初始化部分:

      List<YourModelClass> subjectList = [];
      void initState() {
          super.initState();
          _dbHelper.getAllUserData().then((value)async{
            userdetails = value;
             // subjectList.add(value); // store the user item 
            await getsubjectList(value[0].userId!, value[0].accountId!).then((value){
              testfunction(value);
            });
          });
        } 
      

      主体:

      body: ListView.builder(
              itemCount: subjectList.length,
              shrinkWrap: true,
              physics: ScrollPhysics()
              itemBuilder: (BuildContext context,int index){
                return ListTile(
                  title:Text("${subjectList[index].itemName}")
                  );
              }
              ),
      

      【讨论】:

      • 我需要先存储对列表的响应吗??
      • 在初始化部分你首先存储数据
      【解决方案3】:

      1- 创建私有变量var _response;

      2- 在您的 initState 中,使用 setState

      为您的 _response 变量设置一个值
        @override
        void initState() {
          super.initState();
             setState(() {
              _response = yourApiResponse;
             });
        }
      

      3- 在您的 listView.builder 小部件中使用 _response

      body: ListView.builder(
              itemCount: _response.length,
              itemBuilder: (context,index){
                return ListTile(
                  title:Text(_response[index].Name)
                  );
              }
              ),
      

      【讨论】:

        猜你喜欢
        • 2020-11-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-28
        相关资源
        最近更新 更多