获取工作正常,但是在从获取数据中推送值之后,“ title”数组中没有任何值。
function getdata(){
const title = [];
const body = [];
const url = 'https://jsonplaceholder.typicode.com/posts';
fetch(url)
.then(response => response.json())
.then(data => {
// console.log(data) /*This works just fine*/
data.forEach(posts => {
title.push(posts.title)
body.push(posts.body)
})
})
// const onlytentitle = title.slice(0,9);
// return onlytentitle;
return title;
}
const titled = getdata();
console.log(titled);
答案 0 :(得分:1)
Widget _authBuilder(context, Widget body) {
final authModel = Provider.of<FAAuthModel>(context);
return StreamBuilder(
stream: FirebaseAuth.instance.onAuthStateChanged,
builder: (context, snapshot) {
authModel.user = snapshot.data;
return body;
},
);
}
是一个异步函数,您要从获取的外部返回标题,因此您的函数将在获取请求完成之前返回标题。
尝试一下。
I/flutter (28504): ══╡ EXCEPTION CAUGHT BY FOUNDATION LIBRARY ╞════════════════════════════════════════════════════════
I/flutter (28504): The following assertion was thrown while dispatching notifications for FAAuthModel:
I/flutter (28504): setState() or markNeedsBuild() called during build.
I/flutter (28504): This _DefaultInheritedProviderScope<FAAuthModel> widget cannot be marked as needing to build because
I/flutter (28504): the framework is already in the process of building widgets. A widget can be marked as needing to
I/flutter (28504): be built during the build phase only if one of its ancestors is currently building. This exception
I/flutter (28504): is allowed because the framework builds parent widgets before children, which means a dirty
I/flutter (28504): descendant will always be built. Otherwise, the framework might not visit this widget during this
I/flutter (28504): build phase.
I/flutter (28504): The widget on which setState() or markNeedsBuild() was called was:
I/flutter (28504): _DefaultInheritedProviderScope<FAAuthModel>
I/flutter (28504): The widget which was currently being built when the offending call was made was:
I/flutter (28504): StreamBuilder<FirebaseUser>
I/flutter (28504):
使用fetch
function getdata() {
const title = [];
const body = [];
const url = "https://jsonplaceholder.typicode.com/posts";
return fetch(url)
.then(response => response.json())
.then(data => {
data.forEach(posts => {
title.push(posts.title);
body.push(posts.body);
});
return title;
});
}
(async function() {
const titled = await getdata();
console.log(titled);
})();