Flutter中已有build方法时,动态创建ListView的位置咨询
Solution: Adding a Dynamic ListView to Your Flutter Scaffold
Got it, let's fix this step by step! The key here is that the Scaffold has a body property specifically meant for your main content—this is where you'll place your dynamic ListView. Also, since your userDetails is loaded asynchronously, we need to manage the state properly to update the UI once the data is ready.
Step 1: Add State Variables
First, add variables to your _SearchState class to store the fetched user data and track the loading state:
class _SearchState extends State<Search> { // Store your user details here Map<String, dynamic> userDetails = {}; // Track if data is being loaded bool isLoading = false; // ... rest of your code }
Step 2: Update the _getTicketDetails Method
Modify your async method to update the state when data starts loading and finishes loading:
_getTicketDetails() async { setState(() { isLoading = true; // Show loading state userDetails = {}; // Reset data before fetching }); print(widget.id); final response = await http.get( "https:...", headers: {HttpHeaders.AUTHORIZATION: "..."} ); List returnTicketDetails = json.decode(response.body); print(returnTicketDetails); Map<String, dynamic> fetchedUsers = {}; for (var i = 0; i < (returnTicketDetails?.length ?? 0); i++) { final ticketresponse = await http.get( "..${returnTicketDetails[i]["user_id"].toString()}", headers: {HttpHeaders.AUTHORIZATION: "..."} ); fetchedUsers[returnTicketDetails[i]["user_id"]] = json.decode(ticketresponse.body); } // Update state with new data and end loading setState(() { userDetails = fetchedUsers; isLoading = false; }); print(userDetails); }
Step 3: Add the ListView to the Scaffold's Body
Now, use the body property of your Scaffold to render the appropriate UI based on the state:
@override Widget build(BuildContext context) { widget.id; return Scaffold( appBar: AppBar( actions: <Widget>[ IconButton( icon: const Icon(Icons.exit_to_app), onPressed: _getTicketDetails ) ], centerTitle: true, title: const Text( "TicketsDetails", style: TextStyle(fontFamily: 'Poppins'), ), ), // This is where your ListView goes! body: isLoading ? const Center(child: CircularProgressIndicator()) // Show loading spinner : userDetails.isEmpty ? const Center(child: Text("No users found")) // Empty state : ListView.builder( itemCount: userDetails.length, itemBuilder: (context, index) { // Get the user ID and details String userId = userDetails.keys.elementAt(index); var userData = userDetails[userId]; // Build your list item return ListTile( leading: userData["profile_image"] != null ? Image.network(userData["profile_image"]) : const Icon(Icons.person), title: Text("${userData["first_name"]} ${userData["last_name"]}"), subtitle: Text("User ID: $userId"), ); }, ), ); }
Key Notes:
- The
Scaffold'sbodyis designed to hold your main screen content—this is the perfect spot for yourListView. - We use
setStateto trigger UI updates when the loading state changes or when new data is fetched. ListView.builderis efficient for dynamic lists because it only builds items that are visible on screen.
内容的提问来源于stack exchange,提问作者heyr
相关产品推荐
相关产品推荐

