FutureBuilder未进行构建



我正试图使用FutureBuilder小部件来显示我的UI,但由于某些原因它不起作用。这是我的代码:

List<ContentData> contentList = new List<ContentData>();
Future<String> getContentsInFuture;
Future<String> getCourseContent() async
{
//Get contents from server and store it in contentList
return "success";
}
void initState()
{
getContentsInFuture = getCourseContent();
super.initState(); 
}
Widget build(BuildContext context)
{
return Scaffold(
body: FutureBuilder<String>(
future: getContentsInFuture,
builder: (BuildContext context, AsyncSnapshot<String> snapshot)
{
if(snapshot.hasData)
{
return contentListView();
}
else
{
return SizedBox(
child: CircularProgressIndicator(),
width: 60,
height: 60,
);
}
}
),
);
}
ListView contentListView()
{
return ListView.builder(
padding: EdgeInsets.all(16.0),
itemCount: contentList.length,
itemBuilder: (context, index)
{
return ListTile(
title: Text(contentList[index].contentName),
);
}
);
}

此代码适用于其他页面,但在本例中不适用。我如何使用它,以便在收到服务器的响应后显示我的UI?

编辑:

我现在在调试控制台上收到错误:

E/flutter ( 7504): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: dependOnInheritedWidgetOfExactType<_ModalScopeStatus>() or dependOnInheritedElement() was called before _ContentSelection.initState() completed.
E/flutter ( 7504): When an inherited widget changes, for example if the value of Theme.of() changes, its dependent widgets are rebuilt. If the dependent widget's reference to the inherited widget is in a constructor or an initState() method, then the rebuilt dependent widget will not reflect the changes in the inherited widget.
E/flutter ( 7504): Typically references to inherited widgets should occur in widget build() methods. Alternatively, initialization based on inherited widgets can be placed in the didChangeDependencies method, which is called after initState and whenever the dependencies change thereafter.

根据我上面发布的错误代码,我所要做的就是替换:

void initState()
{
getContentsInFuture = getCourseContent();
super.initState(); 
}

带有

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

getContentsInFuture = getCourseContent();
}

相关内容

最新更新