【问题标题】:Make data available to all classes flutter让所有类都可以使用数据
【发布时间】:2020-06-07 10:33:45
【问题描述】:

我正在我的主页上创建一个http get request,它返回一个Iterable 的列表。单击tab 时,我需要将此结果传递到屏幕。它不能按预期工作,因为它在导航到新屏幕时返回 null。所以我猜这不是正确的做法。

主页

class DashBoardPage extends StatefulWidget {
  @override
  _DashBoardPageState createState() => _DashBoardPageState();
}

class _DashBoardPageState extends State<DashBoardPage> {
  List<MentorIndex> mentorIndexes = [];
  SharedPreferences sharedPreferences;
  Iterable newList;

  Widget callPage(int currentIndex) {
    switch (currentIndex) {
      case 0:
        showTabs = true;

        return TabBarView(
            //trying to pass this list to new tab screen
            children: [new HomePage(), new SchedulePage(), RequestsPage(menteeIds: newList,)]);
        break;

      default:
        return HomePage();
    }
  }

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

    fetchIndex();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '',


  }



 }
   Future fetchIndex() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    var uri = NetworkUtils.host + AuthUtils.endPointIndex;
    try {
      final response = await http.get(
        uri,
        headers: {'Accept': 'application/json', 'Content-Type': 'application/json','Authorization': 'Bearer ' + sharedPreferences.get("token"), },
      );
      final responseJson = json.decode(response.body);
      for (var u in responseJson["data"]) {
        MentorIndex user = MentorIndex(
            u["id"],
            u["mentor_id"],
            u["mentee_id"],
            u["status"],
            u["session_count"],
            u["current_job"],
            u["email"],
            u["phone_call"],
            u["video_call"],
            u["face_to_face"],
            u["created_at"],
            u["updated_at"]);

        mentorIndexes.add(user);
        newList = mentorIndexes.map((MentorIndex) => MentorIndex.mentee_id);
      }
      return responseJson;
    } catch (exception) {
      print(exception);
    }
  }
}

【问题讨论】:

    标签: flutter dart tabs iterable


    【解决方案1】:

    您需要在 Stateful 小部件中设置状态以更改其状态并重建小部件,现在您只需传递创建时分配的 newListnull 值。

    在您的 fetchIndex 方法中,使用 setState 包装您的 newList 分配代码,就像这样

            setState((){
               newList = mentorIndexes.map((MentorIndex) => MentorIndex.mentee_id);
            })
    

    这样您将通知您的StatefulWidget 它的State 对象已更改并且需要重建。

    【讨论】:

      猜你喜欢
      • 2016-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-27
      • 2021-02-24
      • 1970-01-01
      • 2011-01-15
      • 1970-01-01
      相关资源
      最近更新 更多