我正在嘗試從 API 獲取用戶資訊。為此,我創建了一個用戶物件。我想呼叫該函式并將其存盤在用戶中。但問題是,我不能使用 await 并等到所有資料都在那里。
因此,我嘗試使用 .then 并用資料填充 userInfo,而不是 async 和 await。但是現在沒有顯示電子郵件值。它顯示“正在加載...”。
如果我使用 Future 我不能做 user.email。
使用 FutureBuilder 會更好嗎?或者嘗試使用 Async 和 Await(呼叫需要 2.5 秒)
這是代碼
class Addressbook extends StatefulWidget {
const Addressbook({Key? key}) : super(key: key);
@override
State<Addressbook> createState() => _AddressbookState();
}
class _AddressbookState extends State<Addressbook> {
User? userInfo;
Future<User> getUserInformation() async {
User user = await UserService().getUserById(12345);
return user;
}
@override
void initState() {
// TODO: implement initState
getUserInformation().then((response) {
userInfo = response;
});
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Mijn adresboek'),
centerTitle: true,
elevation: 0.5,
titleTextStyle: const TextStyle(
fontSize: 21,
color: Colors.black,
fontWeight: FontWeight.bold,
),
),
body: Text(userInfo?.email ?? "loading..."),
);
}
}
我要歸檔什么?
我想在螢屏上顯示用戶資料。在這種情況下,我想顯示電子郵件。
問題是什么?
用戶未在 init 上填充資料(可能是因為它仍在加載以獲取資料)。
我的問題
我怎么解決這個問題?是異步等待解決方案還是我應該使用 FutureBuilder?你能給我一個作業樣本嗎?
感謝您的幫助!
uj5u.com熱心網友回復:
你可以使用 futurebuilder 或者你可以在 initstate 中使用來獲取 api

@override
void initState() {
// TODO: implement initState
Future.delayed(Duration(seconds: 10), () {
setState(() {
userinfo = "response";
});
// userinfo = "response";
});
super.initState();
}
小部件內部
Text(userinfo != null ? userinfo.toString() : "loading..."),
示例代碼
import 'package:flutter/material.dart';
//import 'package:pucon/home.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
MyApp({Key? key}) : super(key: key);
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String? userinfo = null;
String? userinfo2 = null;
@override
void initState() {
// TODO: implement initState
Future.delayed(Duration(seconds: 10), () {
setState(() {
userinfo = "response";
});
// userinfo = "response";
});
super.initState();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: ListView(
shrinkWrap: true,
children: [
Text(""),
Text(""),
Text(userinfo != null ? userinfo.toString() : "loading..."),
Row(
children: [
FutureBuilder(
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
return Container(
child: Text(userinfo2.toString()), );
} else {
return SizedBox(
child: CircularProgressIndicator(),
height: 45,
width: 45,
);
// else
// return Container(
// child: CircularProgressIndicator(),
// height: 45,
// width: 45,
// );
}
},
future: _future(),
),
],
)
// InsertData(),
],
),
);
}
_future() async {
await Future.delayed(Duration(seconds: 5), () {
userinfo2 = "Completed";
// setState(() {
//
// });
// userinfo = "response";
});
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/441775.html
上一篇:從同一個API獲取兩種型別的資料
下一篇:fat檔案,但缺少兼容架構有“i386,x86_64”,MacM1Pro芯片上的bcrypt需要“arm64e”錯誤
