如何在Flutter饼图中展示指定JSON数据的百分比?
Got it, let's fix this up for you. Here's how you can swap those hardcoded numbers in your dataMap with the values from your dashboardResult JSON:
Step 1: Store Your Dashboard Data
First, make sure you have access to the dashboardResult data in your widget. You can define it as a class member variable (either hardcoded for testing, or populated via an API request later):
// Define this at the top of your widget class Map<String, dynamic> dashboardResult = { "new_call": 18, "overdue_calls": 0, "completed_calls": 2523 };
Step 2: Update initState to Use JSON Values
Modify your initState method to pull values directly from dashboardResult instead of hardcoding them. We'll also clear the map first to avoid duplicate entries:
@override void initState() { super.initState(); // Clear existing entries to prevent duplicates dataMap.clear(); // Map JSON values to your pie chart labels dataMap.putIfAbsent("Complete", () => dashboardResult["completed_calls"]); dataMap.putIfAbsent("New Calls", () => dashboardResult["new_call"]); dataMap.putIfAbsent("Overdue", () => dashboardResult["overdue_calls"]); }
Step 3: Handle Async Data (If Fetching from API)
If your dashboardResult comes from an API call instead of being hardcoded, you'll need to update the dataMap after the request completes and trigger a rebuild with setState:
// Add this method to your widget class Future<void> fetchDashboardData() async { // Replace with your actual API endpoint final response = await http.get(Uri.parse("your_dashboard_api_url")); if (response.statusCode == 200) { setState(() { // Parse the JSON response final jsonData = json.decode(response.body); dashboardResult = jsonData["dashboardResult"]; // Update the pie chart data map dataMap.clear(); dataMap.putIfAbsent("Complete", () => dashboardResult["completed_calls"]); dataMap.putIfAbsent("New Calls", () => dashboardResult["new_call"]); dataMap.putIfAbsent("Overdue", () => dashboardResult["overdue_calls"]); }); } else { // Handle request failure (e.g., show an error message) print("Failed to load dashboard data"); } } // Call the fetch method in initState @override void initState() { super.initState(); fetchDashboardData(); }
Important Notes:
- Ensure
dataMapis declared as a class member variable with the correct type (usuallyMap<String, num>since pie chart libraries accept integers or doubles) - If
overdue_callsis 0, it won't appear in the pie chart (since it contributes 0% to the total) — this is expected behavior - Don't forget to import required packages:
dart:convertfor JSON parsing andpackage:http/http.dartif using API calls
内容的提问来源于stack exchange,提问作者shilpa navale

