這是我在 php 中的關聯陣列:
{"No":"020474","name":"Ayuk Baye"}
{"No":"08273","name":"Cedrick"}
{"No":"08274","name":"Ayuk Baye"}
{"No":"08275","name":"Ayu Rebecca"}
{"No":"08276","name":"Raymond"}
{"No":"08277","name":"Jolie"}
{"No":"08278","name":"Prince"}
{"No":"08474","name":"Ayuk Baye"}
我需要幫助將此資料決議為帶有顫振的 listView Builder。
uj5u.com熱心網友回復:
首先,后端語言并不重要。總之,你的問題基本上是問兩件事。
- 如何在 Flutter 中決議 Json
- 如何在顫振中繪制串列
對于 #1,您可以使用 json 序列化程式。上面的json內容是無效的,但是如果你把它放在一個陣列中那么它就會有效。
[
{"No":"020474","name":"Ayuk Baye"}{"No":"08273","name":"Cedrick"},
{"No":"08274","name":"Ayuk Baye"}{"No":"08275","name":"Ayu Rebecca"},
{"No":"08276","name":"Raymond"}{"No":"08277","name":"Jolie"},
{"No":"08278","name":"Prince"}{"No":"08474","name":"Ayuk Baye"}
]
現在您擁有有效的 JSON,您可以使用Json 序列化檔案。有了專案串列后,您可以繼續進行 2。
您只需使用串列視圖來顯示您的串列。
ListView.builder(itemBuilder: (context, index) =>
Container(child:
Text(myJsonList[index].name))
uj5u.com熱心網友回復:
1) 為你的 json resopnce 創建一個模型類
在線搜索 json to dart 轉換器并為回應創建一個模型類
2)從API得到你的回應
像這樣: -
Future<http.Response> getdata() {
return http.get(Uri.parse('your http end point'));
}
3) 將回應轉換為自定義的 Dart 物件
return YourModelClassName.fromJson(jsonDecode(response.body));
4) 使用 initState 獲取所需頁面上的資料
你的班級應該是有狀態的班級
就像這樣: -
class _MyAppState extends State<MyApp> {
late Future<YourModelClass> getdata;
@override
void initState() {
super.initState();
getdata = getdata();
}
// ···
}
5) 使用 futurebuilder 顯示您的資料
參考下面的代碼
FutureBuilder<Album>(
future: futureAlbum,
builder: (context, snapshot) {
if (snapshot.hasData) {
return
//Show your listview.builder here
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
// By default, show a loading spinner.
return const CircularProgressIndicator();
},
)
5)在串列視圖構建器中顯示您的資料
請參閱下面的此代碼
ListView.builder(
padding: const EdgeInsets.all(8),
itemCount: entries.length,
itemBuilder: (BuildContext context, int index) {
return Container(
//Here you can show your data with the help of the model class
//You can you the 'index' to iterate throug every data
);
}
);
有關更多資訊,請參閱這些檔案
從互聯網獲取資料
串列視圖生成器
謝謝
uj5u.com熱心網友回復:
您可以使用FutureBuilder來獲取資料,然后將其傳遞到您的 ListView 中
FutureBuilder<List<User>>(
future: getUser, //your service to get the data from API
builder: (BuildContext context, AsyncSnapshot snapshot) {
if(snapshot.hasError) {
return Container(
color: Colors.white,
height: MediaQuery.of(context).size.height,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [],
),
);
} else if (snapshot.hasData) {
List<User> userList = snapshot.data;
return ListView.separated(
separatorBuilder: (BuildContext context, int i) => Divider(color: Colors.grey[400]),
itemCount: userList.length,
itemBuilder: (context, index) {
User user = userList[index];
return Container(
child: Text(user.name)
)
}
);
}
}
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/382770.html
