commit 9f7b5ca4adc3ddedbe7c3545dbcfdd49d30e3e49 Author: zilillah08 Date: Fri Jun 19 12:54:15 2026 +0700 Upload project M Posyandu Final diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..dd13ca1 --- /dev/null +++ b/.gitignore @@ -0,0 +1,47 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release + +*.log diff --git a/.metadata b/.metadata new file mode 100644 index 0000000..1f19d86 --- /dev/null +++ b/.metadata @@ -0,0 +1,45 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "c519ee916eaeb88923e67befb89c0f1dabfa83e6" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: c519ee916eaeb88923e67befb89c0f1dabfa83e6 + base_revision: c519ee916eaeb88923e67befb89c0f1dabfa83e6 + - platform: android + create_revision: c519ee916eaeb88923e67befb89c0f1dabfa83e6 + base_revision: c519ee916eaeb88923e67befb89c0f1dabfa83e6 + - platform: ios + create_revision: c519ee916eaeb88923e67befb89c0f1dabfa83e6 + base_revision: c519ee916eaeb88923e67befb89c0f1dabfa83e6 + - platform: linux + create_revision: c519ee916eaeb88923e67befb89c0f1dabfa83e6 + base_revision: c519ee916eaeb88923e67befb89c0f1dabfa83e6 + - platform: macos + create_revision: c519ee916eaeb88923e67befb89c0f1dabfa83e6 + base_revision: c519ee916eaeb88923e67befb89c0f1dabfa83e6 + - platform: web + create_revision: c519ee916eaeb88923e67befb89c0f1dabfa83e6 + base_revision: c519ee916eaeb88923e67befb89c0f1dabfa83e6 + - platform: windows + create_revision: c519ee916eaeb88923e67befb89c0f1dabfa83e6 + base_revision: c519ee916eaeb88923e67befb89c0f1dabfa83e6 + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..27d429c --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,25 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "name": "posyandu_care", + "request": "launch", + "type": "dart" + }, + { + "name": "posyandu_care (profile mode)", + "request": "launch", + "type": "dart", + "flutterMode": "profile" + }, + { + "name": "posyandu_care (release mode)", + "request": "launch", + "type": "dart", + "flutterMode": "release" + } + ] +} \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..4d79f89 --- /dev/null +++ b/README.md @@ -0,0 +1,16 @@ +# posyandu_care + +A new Flutter project. + +## Getting Started + +This project is a starting point for a Flutter application. + +A few resources to get you started if this is your first Flutter project: + +- [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab) +- [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook) + +For help getting started with Flutter development, view the +[online documentation](https://docs.flutter.dev/), which offers tutorials, +samples, guidance on mobile development, and a full API reference. diff --git a/analysis_options.yaml b/analysis_options.yaml new file mode 100644 index 0000000..0d29021 --- /dev/null +++ b/analysis_options.yaml @@ -0,0 +1,28 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at https://dart.dev/lints. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. + rules: + # avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/android/.gitignore b/android/.gitignore new file mode 100644 index 0000000..55afd91 --- /dev/null +++ b/android/.gitignore @@ -0,0 +1,13 @@ +gradle-wrapper.jar +/.gradle +/captures/ +/gradlew +/gradlew.bat +/local.properties +GeneratedPluginRegistrant.java + +# Remember to never publicly share your keystore. +# See https://flutter.dev/to/reference-keystore +key.properties +**/*.keystore +**/*.jks diff --git a/android/app/build.gradle b/android/app/build.gradle new file mode 100644 index 0000000..b8d784e --- /dev/null +++ b/android/app/build.gradle @@ -0,0 +1,44 @@ +plugins { + id "com.android.application" + id "kotlin-android" + // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. + id "dev.flutter.flutter-gradle-plugin" +} + +android { + namespace = "com.example.posyandu_care" + compileSdk = flutter.compileSdkVersion + ndkVersion = flutter.ndkVersion + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + } + + kotlinOptions { + jvmTarget = JavaVersion.VERSION_1_8 + } + + defaultConfig { + // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). + applicationId = "com.example.posyandu_care" + // You can update the following values to match your application needs. + // For more information, see: https://flutter.dev/to/review-gradle-config. + minSdk = flutter.minSdkVersion + targetSdk = flutter.targetSdkVersion + versionCode = flutter.versionCode + versionName = flutter.versionName + } + + buildTypes { + release { + // TODO: Add your own signing config for the release build. + // Signing with the debug keys for now, so `flutter run --release` works. + signingConfig = signingConfigs.debug + } + } +} + +flutter { + source = "../.." +} diff --git a/android/app/src/debug/AndroidManifest.xml b/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..5afc096 --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/android/app/src/main/kotlin/com/example/posyandu_care/MainActivity.kt b/android/app/src/main/kotlin/com/example/posyandu_care/MainActivity.kt new file mode 100644 index 0000000..40fdb8b --- /dev/null +++ b/android/app/src/main/kotlin/com/example/posyandu_care/MainActivity.kt @@ -0,0 +1,5 @@ +package com.example.posyandu_care + +import io.flutter.embedding.android.FlutterActivity + +class MainActivity: FlutterActivity() diff --git a/android/app/src/main/res/drawable-v21/launch_background.xml b/android/app/src/main/res/drawable-v21/launch_background.xml new file mode 100644 index 0000000..f74085f --- /dev/null +++ b/android/app/src/main/res/drawable-v21/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/android/app/src/main/res/drawable/launch_background.xml b/android/app/src/main/res/drawable/launch_background.xml new file mode 100644 index 0000000..304732f --- /dev/null +++ b/android/app/src/main/res/drawable/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..db77bb4 Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-hdpi/launcher_icon.png b/android/app/src/main/res/mipmap-hdpi/launcher_icon.png new file mode 100644 index 0000000..15972f3 Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/launcher_icon.png differ diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..17987b7 Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-mdpi/launcher_icon.png b/android/app/src/main/res/mipmap-mdpi/launcher_icon.png new file mode 100644 index 0000000..d355a4b Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/launcher_icon.png differ diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..09d4391 Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xhdpi/launcher_icon.png b/android/app/src/main/res/mipmap-xhdpi/launcher_icon.png new file mode 100644 index 0000000..2383797 Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/launcher_icon.png differ diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..d5f1c8d Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxhdpi/launcher_icon.png b/android/app/src/main/res/mipmap-xxhdpi/launcher_icon.png new file mode 100644 index 0000000..1b37e4b Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/launcher_icon.png differ diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..4d6372e Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxxhdpi/launcher_icon.png b/android/app/src/main/res/mipmap-xxxhdpi/launcher_icon.png new file mode 100644 index 0000000..49d4aac Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/launcher_icon.png differ diff --git a/android/app/src/main/res/values-night/styles.xml b/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 0000000..06952be --- /dev/null +++ b/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/android/app/src/main/res/values/styles.xml b/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..cb1ef88 --- /dev/null +++ b/android/app/src/main/res/values/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/android/app/src/profile/AndroidManifest.xml b/android/app/src/profile/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/android/app/src/profile/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/android/build.gradle b/android/build.gradle new file mode 100644 index 0000000..d2ffbff --- /dev/null +++ b/android/build.gradle @@ -0,0 +1,18 @@ +allprojects { + repositories { + google() + mavenCentral() + } +} + +rootProject.buildDir = "../build" +subprojects { + project.buildDir = "${rootProject.buildDir}/${project.name}" +} +subprojects { + project.evaluationDependsOn(":app") +} + +tasks.register("clean", Delete) { + delete rootProject.buildDir +} diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 0000000..2597170 --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,3 @@ +org.gradle.jvmargs=-Xmx4G -XX:MaxMetaspaceSize=2G -XX:+HeapDumpOnOutOfMemoryError +android.useAndroidX=true +android.enableJetifier=true diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..7bb2df6 --- /dev/null +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.3-all.zip diff --git a/android/settings.gradle b/android/settings.gradle new file mode 100644 index 0000000..9c3f403 --- /dev/null +++ b/android/settings.gradle @@ -0,0 +1,25 @@ +pluginManagement { + def flutterSdkPath = { + def properties = new Properties() + file("local.properties").withInputStream { properties.load(it) } + def flutterSdkPath = properties.getProperty("flutter.sdk") + assert flutterSdkPath != null, "flutter.sdk not set in local.properties" + return flutterSdkPath + }() + + includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") + + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +plugins { + id "dev.flutter.flutter-plugin-loader" version "1.0.0" + id "com.android.application" version "8.1.1" apply false + id "org.jetbrains.kotlin.android" version "1.8.22" apply false +} + +include ":app" diff --git a/assets/images/logo sumberasih.png b/assets/images/logo sumberasih.png new file mode 100644 index 0000000..1634cc3 Binary files /dev/null and b/assets/images/logo sumberasih.png differ diff --git a/assets/images/logo.png b/assets/images/logo.png new file mode 100644 index 0000000..8757c15 Binary files /dev/null and b/assets/images/logo.png differ diff --git a/assets/images/logo1.png b/assets/images/logo1.png new file mode 100644 index 0000000..2d12eee Binary files /dev/null and b/assets/images/logo1.png differ diff --git a/assets/images/logoo.webp b/assets/images/logoo.webp new file mode 100644 index 0000000..608dd6a Binary files /dev/null and b/assets/images/logoo.webp differ diff --git a/assets/sounds/notif.mp3 b/assets/sounds/notif.mp3 new file mode 100644 index 0000000..bee67d7 Binary files /dev/null and b/assets/sounds/notif.mp3 differ diff --git a/ios/.gitignore b/ios/.gitignore new file mode 100644 index 0000000..7a7f987 --- /dev/null +++ b/ios/.gitignore @@ -0,0 +1,34 @@ +**/dgph +*.mode1v3 +*.mode2v3 +*.moved-aside +*.pbxuser +*.perspectivev3 +**/*sync/ +.sconsign.dblite +.tags* +**/.vagrant/ +**/DerivedData/ +Icon? +**/Pods/ +**/.symlinks/ +profile +xcuserdata +**/.generated/ +Flutter/App.framework +Flutter/Flutter.framework +Flutter/Flutter.podspec +Flutter/Generated.xcconfig +Flutter/ephemeral/ +Flutter/app.flx +Flutter/app.zip +Flutter/flutter_assets/ +Flutter/flutter_export_environment.sh +ServiceDefinitions.json +Runner/GeneratedPluginRegistrant.* + +# Exceptions to above rules. +!default.mode1v3 +!default.mode2v3 +!default.pbxuser +!default.perspectivev3 diff --git a/ios/Flutter/AppFrameworkInfo.plist b/ios/Flutter/AppFrameworkInfo.plist new file mode 100644 index 0000000..7c56964 --- /dev/null +++ b/ios/Flutter/AppFrameworkInfo.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + App + CFBundleIdentifier + io.flutter.flutter.app + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + App + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1.0 + MinimumOSVersion + 12.0 + + diff --git a/ios/Flutter/Debug.xcconfig b/ios/Flutter/Debug.xcconfig new file mode 100644 index 0000000..592ceee --- /dev/null +++ b/ios/Flutter/Debug.xcconfig @@ -0,0 +1 @@ +#include "Generated.xcconfig" diff --git a/ios/Flutter/Release.xcconfig b/ios/Flutter/Release.xcconfig new file mode 100644 index 0000000..592ceee --- /dev/null +++ b/ios/Flutter/Release.xcconfig @@ -0,0 +1 @@ +#include "Generated.xcconfig" diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..3edd59b --- /dev/null +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,616 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXBuildFile section */ + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C807B294A618700263BE5 /* RunnerTests.swift */; }; + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C8085294A63A400263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 97C146E61CF9000F007C117D /* Project object */; + proxyType = 1; + remoteGlobalIDString = 97C146ED1CF9000F007C117D; + remoteInfo = Runner; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 9705A1C41CF9048500538489 /* Embed Frameworks */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Embed Frameworks"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; + 331C807B294A618700263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 331C8081294A63A400263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; + 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; + 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 97C146EB1CF9000F007C117D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C8082294A63A400263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C807B294A618700263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 9740EEB11CF90186004384FC /* Flutter */ = { + isa = PBXGroup; + children = ( + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 9740EEB31CF90195004384FC /* Generated.xcconfig */, + ); + name = Flutter; + sourceTree = ""; + }; + 97C146E51CF9000F007C117D = { + isa = PBXGroup; + children = ( + 9740EEB11CF90186004384FC /* Flutter */, + 97C146F01CF9000F007C117D /* Runner */, + 97C146EF1CF9000F007C117D /* Products */, + 331C8082294A63A400263BE5 /* RunnerTests */, + ); + sourceTree = ""; + }; + 97C146EF1CF9000F007C117D /* Products */ = { + isa = PBXGroup; + children = ( + 97C146EE1CF9000F007C117D /* Runner.app */, + 331C8081294A63A400263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 97C146F01CF9000F007C117D /* Runner */ = { + isa = PBXGroup; + children = ( + 97C146FA1CF9000F007C117D /* Main.storyboard */, + 97C146FD1CF9000F007C117D /* Assets.xcassets */, + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, + 97C147021CF9000F007C117D /* Info.plist */, + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, + ); + path = Runner; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C8080294A63A400263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 331C807D294A63A400263BE5 /* Sources */, + 331C807F294A63A400263BE5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 331C8086294A63A400263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C8081294A63A400263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 97C146ED1CF9000F007C117D /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 9740EEB61CF901F6004384FC /* Run Script */, + 97C146EA1CF9000F007C117D /* Sources */, + 97C146EB1CF9000F007C117D /* Frameworks */, + 97C146EC1CF9000F007C117D /* Resources */, + 9705A1C41CF9048500538489 /* Embed Frameworks */, + 3B06AD1E1E4923F5004D2608 /* Thin Binary */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Runner; + productName = Runner; + productReference = 97C146EE1CF9000F007C117D /* Runner.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 97C146E61CF9000F007C117D /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C8080294A63A400263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 97C146ED1CF9000F007C117D; + }; + 97C146ED1CF9000F007C117D = { + CreatedOnToolsVersion = 7.3.1; + LastSwiftMigration = 1100; + }; + }; + }; + buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 97C146E51CF9000F007C117D; + productRefGroup = 97C146EF1CF9000F007C117D /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 97C146ED1CF9000F007C117D /* Runner */, + 331C8080294A63A400263BE5 /* RunnerTests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C807F294A63A400263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EC1CF9000F007C117D /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${TARGET_BUILD_DIR}/${INFOPLIST_PATH}", + ); + name = "Thin Binary"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; + }; + 9740EEB61CF901F6004384FC /* Run Script */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Run Script"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C807D294A63A400263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EA1CF9000F007C117D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C8086294A63A400263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 97C146ED1CF9000F007C117D /* Runner */; + targetProxy = 331C8085294A63A400263BE5 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 97C146FA1CF9000F007C117D /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C146FB1CF9000F007C117D /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C147001CF9000F007C117D /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 249021D3217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Profile; + }; + 249021D4217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.example.posyanduCare; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Profile; + }; + 331C8088294A63A400263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.posyanduCare.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Debug; + }; + 331C8089294A63A400263BE5 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.posyanduCare.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Release; + }; + 331C808A294A63A400263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.posyanduCare.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Profile; + }; + 97C147031CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = AppIcon; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 97C147041CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = AppIcon; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 97C147061CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.example.posyanduCare; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Debug; + }; + 97C147071CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.example.posyanduCare; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C8088294A63A400263BE5 /* Debug */, + 331C8089294A63A400263BE5 /* Release */, + 331C808A294A63A400263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147031CF9000F007C117D /* Debug */, + 97C147041CF9000F007C117D /* Release */, + 249021D3217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147061CF9000F007C117D /* Debug */, + 97C147071CF9000F007C117D /* Release */, + 249021D4217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 97C146E61CF9000F007C117D /* Project object */; +} diff --git a/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..8e3ca5d --- /dev/null +++ b/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,98 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner.xcworkspace/contents.xcworkspacedata b/ios/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..1d526a1 --- /dev/null +++ b/ios/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swift new file mode 100644 index 0000000..6266644 --- /dev/null +++ b/ios/Runner/AppDelegate.swift @@ -0,0 +1,13 @@ +import Flutter +import UIKit + +@main +@objc class AppDelegate: FlutterAppDelegate { + override func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + GeneratedPluginRegistrant.register(with: self) + return super.application(application, didFinishLaunchingWithOptions: launchOptions) + } +} diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..d36b1fa --- /dev/null +++ b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,122 @@ +{ + "images" : [ + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@3x.png", + "scale" : "3x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@3x.png", + "scale" : "3x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@3x.png", + "scale" : "3x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@2x.png", + "scale" : "2x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@3x.png", + "scale" : "3x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@1x.png", + "scale" : "1x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@1x.png", + "scale" : "1x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@1x.png", + "scale" : "1x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@2x.png", + "scale" : "2x" + }, + { + "size" : "83.5x83.5", + "idiom" : "ipad", + "filename" : "Icon-App-83.5x83.5@2x.png", + "scale" : "2x" + }, + { + "size" : "1024x1024", + "idiom" : "ios-marketing", + "filename" : "Icon-App-1024x1024@1x.png", + "scale" : "1x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png new file mode 100644 index 0000000..c7743a4 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png new file mode 100644 index 0000000..588cf04 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png new file mode 100644 index 0000000..6d068ed Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png new file mode 100644 index 0000000..0befcbd Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png new file mode 100644 index 0000000..e79eb31 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png new file mode 100644 index 0000000..80f8b05 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png new file mode 100644 index 0000000..bd4ee27 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png new file mode 100644 index 0000000..6d068ed Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png new file mode 100644 index 0000000..bb7d3a0 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png new file mode 100644 index 0000000..21e9176 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@1x.png new file mode 100644 index 0000000..8987239 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@2x.png new file mode 100644 index 0000000..1427c9c Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@1x.png new file mode 100644 index 0000000..f630f00 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@2x.png new file mode 100644 index 0000000..0c612c7 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png new file mode 100644 index 0000000..21e9176 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png new file mode 100644 index 0000000..d20b8a4 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@1x.png new file mode 100644 index 0000000..15972f3 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@2x.png new file mode 100644 index 0000000..1b37e4b Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png new file mode 100644 index 0000000..7675e98 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png new file mode 100644 index 0000000..8a0cd41 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png new file mode 100644 index 0000000..fac9f29 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json new file mode 100644 index 0000000..0bedcf2 --- /dev/null +++ b/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "LaunchImage.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@2x.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@3x.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md b/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md new file mode 100644 index 0000000..89c2725 --- /dev/null +++ b/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md @@ -0,0 +1,5 @@ +# Launch Screen Assets + +You can customize the launch screen with your own desired assets by replacing the image files in this directory. + +You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images. \ No newline at end of file diff --git a/ios/Runner/Base.lproj/LaunchScreen.storyboard b/ios/Runner/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 0000000..f2e259c --- /dev/null +++ b/ios/Runner/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner/Base.lproj/Main.storyboard b/ios/Runner/Base.lproj/Main.storyboard new file mode 100644 index 0000000..f3c2851 --- /dev/null +++ b/ios/Runner/Base.lproj/Main.storyboard @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist new file mode 100644 index 0000000..e624cfc --- /dev/null +++ b/ios/Runner/Info.plist @@ -0,0 +1,49 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + Posyandu Care + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + posyandu_care + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleSignature + ???? + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSRequiresIPhoneOS + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + CADisableMinimumFrameDurationOnPhone + + UIApplicationSupportsIndirectInputEvents + + + diff --git a/ios/Runner/Runner-Bridging-Header.h b/ios/Runner/Runner-Bridging-Header.h new file mode 100644 index 0000000..308a2a5 --- /dev/null +++ b/ios/Runner/Runner-Bridging-Header.h @@ -0,0 +1 @@ +#import "GeneratedPluginRegistrant.h" diff --git a/ios/RunnerTests/RunnerTests.swift b/ios/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..86a7c3b --- /dev/null +++ b/ios/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Flutter +import UIKit +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/lib/bidan/bidan_drawer.dart b/lib/bidan/bidan_drawer.dart new file mode 100644 index 0000000..84023e7 --- /dev/null +++ b/lib/bidan/bidan_drawer.dart @@ -0,0 +1,196 @@ +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import '../layout/main_layout.dart'; + +class BidanDrawer extends StatefulWidget { + const BidanDrawer({super.key}); + + @override + State createState() => _BidanDrawerState(); +} + +class _BidanDrawerState extends State { + String? fotoUser; + String namaUser = "Bidan"; + + @override + void initState() { + super.initState(); + _loadUserData(); + } + + Future _loadUserData() async { + final prefs = await SharedPreferences.getInstance(); + setState(() { + fotoUser = prefs.getString('foto'); + namaUser = prefs.getString('nama') ?? "Bidan Posyandu"; + }); + } + + @override + Widget build(BuildContext context) { + return Drawer( + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.only( + topRight: Radius.circular(20), + bottomRight: Radius.circular(20), + ), + ), + child: Column( + children: [ + // ================= HEADER ================= + Material( + color: MainLayout.mainColor, + borderRadius: const BorderRadius.only( + topRight: Radius.circular(20), + ), + child: InkWell( + onTap: () { + Navigator.pushReplacementNamed(context, '/profile-bidan'); + }, + child: Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(vertical: 40), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + CircleAvatar( + radius: 40, + backgroundColor: Colors.white, + child: CircleAvatar( + radius: 37, + backgroundColor: Colors.blue.shade100, + backgroundImage: (fotoUser != null && + fotoUser!.isNotEmpty) + ? NetworkImage( + "http://ta.myhost.id/E31230549/mposyandu_api/uploads/$fotoUser") + : null, + child: (fotoUser == null || fotoUser!.isEmpty) + ? const Icon( + Icons.person, + size: 40, + color: MainLayout.mainColor, + ) + : null, + ), + ), + const SizedBox(height: 12), + Text( + namaUser, + style: GoogleFonts.poppins( + color: Colors.white, + fontSize: 16, + fontWeight: FontWeight.bold, + ), + ), + Text( + "Lihat Profil", + style: GoogleFonts.poppins( + color: Colors.white70, + fontSize: 12, + ), + ), + ], + ), + ), + ), + ), + + // ================= MENU LIST ================= + Expanded( + child: ListView( + padding: EdgeInsets.zero, + children: [ + _drawerItem(context, Icons.home, "Home", '/dashboard-bidan'), + + // ================= DROPDOWN JADWAL (TANPA GARIS) ================= + Theme( + data: Theme.of(context) + .copyWith(dividerColor: Colors.transparent), + child: ExpansionTile( + shape: const Border(), + collapsedShape: const Border(), + leading: const Icon(Icons.calendar_today, + color: MainLayout.mainColor), + title: Text( + "Jadwal", + style: GoogleFonts.poppins( + color: Colors.black, + fontWeight: FontWeight.w500, + fontSize: 14, + ), + ), + iconColor: MainLayout.mainColor, + collapsedIconColor: MainLayout.mainColor, + childrenPadding: const EdgeInsets.only(left: 10), + children: [ + _drawerItem(context, Icons.event_note, "Jadwal Posyandu", + '/jadwal-posyandu'), + // Link ke halaman Jadwal ANC yang baru dibuat + _drawerItem(context, Icons.medical_information, + "Jadwal Periksa ANC", '/jadwal-anc'), + ], + ), + ), + + _drawerItem(context, Icons.pregnant_woman, + "Pemeriksaan Kehamilan", '/periksa-kehamilan'), + _drawerItem(context, Icons.child_care, "Data Gizi Balita", + '/data-gizi-balita'), + _drawerItem( + context, Icons.medical_services, "Imunisasi", '/imunisasi'), + _drawerItem(context, Icons.menu_book, "Edukasi", '/edukasi'), + _drawerItem(context, Icons.description, "Laporan", '/laporan'), + ], + ), + ), + + const Divider(), + + // ================= LOGOUT ================= + ListTile( + leading: const Icon(Icons.logout, color: MainLayout.mainColor), + title: Text( + "Logout", + style: GoogleFonts.poppins( + color: Colors.black, + fontWeight: FontWeight.w500, + fontSize: 14, + ), + ), + onTap: () => _logout(context), + ), + const SizedBox(height: 10), + ], + ), + ); + } + + // ================= DRAWER ITEM WIDGET ================= + Widget _drawerItem( + BuildContext context, IconData icon, String text, String route) { + return ListTile( + leading: Icon(icon, color: MainLayout.mainColor), + title: Text( + text, + style: GoogleFonts.poppins( + color: Colors.black, + fontWeight: FontWeight.w500, + fontSize: 14, + ), + ), + onTap: () { + Navigator.pushReplacementNamed(context, route); + }, + ); + } + + // ================= LOGOUT FUNCTION ================= + Future _logout(BuildContext context) async { + final prefs = await SharedPreferences.getInstance(); + await prefs.clear(); + if (!context.mounted) return; + Navigator.pushNamedAndRemoveUntil(context, '/login', (route) => false); + } +} diff --git a/lib/bidan/crud_data_gizi/edit_gizi_balita.dart b/lib/bidan/crud_data_gizi/edit_gizi_balita.dart new file mode 100644 index 0000000..34a2f7c --- /dev/null +++ b/lib/bidan/crud_data_gizi/edit_gizi_balita.dart @@ -0,0 +1,441 @@ +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:http/http.dart' as http; + +class EditGiziBalitaPage extends StatefulWidget { + final Map dataGizi; + + const EditGiziBalitaPage({super.key, required this.dataGizi}); + + @override + State createState() => _EditGiziBalitaPageState(); +} + +class _EditGiziBalitaPageState extends State { + final _formKey = GlobalKey(); + + late TextEditingController zbbController; + late TextEditingController ztbController; + late TextEditingController zbbtbController; + late TextEditingController tindakController; + late TextEditingController saranController; + + // Variabel penampung teks rentang standar deviasi (SD) + String keteranganBBU = "-"; + String keteranganTBU = "-"; + String keteranganBBTB = "-"; + + // Tiga status gizi berbeda sesuai dengan database baru + String? _selectedStatusBBU; + String? _selectedStatusTBU; + String? _selectedStatusBBTB; + bool isLoading = false; + + // List kategori indikator masing-masing gizi + final List _listBBU = [ + 'Gizi Buruk', + 'Gizi Kurang', + 'Gizi Baik', + 'Risiko Gizi Lebih' + ]; + final List _listTBU = ['Sangat Pendek', 'Pendek', 'Normal', 'Tinggi']; + final List _listBBTB = [ + 'Sangat Kurus', + 'Kurus', + 'Normal', + 'Gemuk', + 'Obesitas' + ]; + + @override + void initState() { + super.initState(); + zbbController = TextEditingController( + text: widget.dataGizi["zscore_bb_u"]?.toString() ?? ""); + ztbController = TextEditingController( + text: widget.dataGizi["zscore_tb_u"]?.toString() ?? ""); + zbbtbController = TextEditingController( + text: widget.dataGizi["zscore_bb_tb"]?.toString() ?? ""); + tindakController = + TextEditingController(text: widget.dataGizi["tindak_lanjut"] ?? ""); + saranController = + TextEditingController(text: widget.dataGizi["saran"] ?? ""); + + // Ambil rentang standar deviasi otomatis berdasarkan nilai Z-Score yang ada + double zBBU = double.tryParse(zbbController.text) ?? 0; + double zTBU = double.tryParse(ztbController.text) ?? 0; + double zBBTB = double.tryParse(zbbtbController.text) ?? 0; + + keteranganBBU = _getSDStatus(zBBU); + keteranganTBU = _getSDStatus(zTBU); + keteranganBBTB = _getSDStatus(zBBTB); + + // Set nilai awal dropdown berdasarkan data yang ada di database + if (_listBBU.contains(widget.dataGizi["status_bbu"])) { + _selectedStatusBBU = widget.dataGizi["status_bbu"]; + } + if (_listTBU.contains(widget.dataGizi["status_tbu"])) { + _selectedStatusTBU = widget.dataGizi["status_tbu"]; + } + if (_listBBTB.contains(widget.dataGizi["status_bbtb"])) { + _selectedStatusBBTB = widget.dataGizi["status_bbtb"]; + } + } + + // Fungsi penentu keterangan standar deviasi (Sama dengan kode tambah) + String _getSDStatus(double z) { + if (z < -3) return "Di bawah -3 SD"; + if (z < -2) return "-3 SD s/d -2 SD"; + if (z <= 1) return "-2 SD s/d +1 SD"; + if (z <= 2) return "Di atas +1 SD s/d +2 SD"; + return "Di atas +2 SD"; + } + + String formatTanggal(String? tgl) { + if (tgl == null || tgl == "-" || tgl.isEmpty) return "-"; + try { + DateTime dt = DateTime.parse(tgl); + List bulanIndo = [ + "", + "Januari", + "Februari", + "Maret", + "April", + "Mei", + "Juni", + "Juli", + "Agustus", + "September", + "Oktober", + "November", + "Desember" + ]; + return "${dt.day} ${bulanIndo[dt.month]} ${dt.year}"; + } catch (e) { + return tgl; + } + } + + String hitungUsia(String? tglLahir) { + if (tglLahir == null || tglLahir.isEmpty) return "-"; + try { + DateTime lahir = DateTime.parse(tglLahir); + DateTime sekarang = DateTime.now(); + int bulan = + (sekarang.year - lahir.year) * 12 + sekarang.month - lahir.month; + return "$bulan Bulan"; + } catch (e) { + return "-"; + } + } + + Future updateData() async { + if (!_formKey.currentState!.validate()) return; + setState(() => isLoading = true); + + try { + final response = await http.post( + Uri.parse( + "http://ta.myhost.id/E31230549/mposyandu_api/gizi_balita/update_gizi_balita.php"), + body: { + "id_gizi": widget.dataGizi["id_gizi"].toString(), + "zscore_bb_u": zbbController.text, + "zscore_tb_u": ztbController.text, + "zscore_bb_tb": zbbtbController.text, + "status_bbu": _selectedStatusBBU ?? "", + "status_tbu": _selectedStatusTBU ?? "", + "status_bbtb": _selectedStatusBBTB ?? "", + "tindak_lanjut": tindakController.text, + "saran": saranController.text, + }, + ); + + final data = json.decode(response.body); + if (data["success"] == true) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text("Data berhasil diupdate"))); + Navigator.pop(context, true); + } else { + if (!mounted) return; + ScaffoldMessenger.of(context) + .showSnackBar(const SnackBar(content: Text("Gagal update"))); + } + } catch (e) { + if (!mounted) return; + ScaffoldMessenger.of(context) + .showSnackBar(SnackBar(content: Text("Error: $e"))); + } + if (mounted) setState(() => isLoading = false); + } + + @override + Widget build(BuildContext context) { + final usia = hitungUsia(widget.dataGizi["tanggal_lahir"]?.toString()); + final tglPeriksa = + formatTanggal(widget.dataGizi["tanggal_pemeriksaan"]?.toString()); + final catatan = widget.dataGizi["catatan"] ?? "-"; + + return Scaffold( + backgroundColor: Colors.grey[100], + appBar: AppBar( + title: const Text(""), + backgroundColor: Colors.blue, + iconTheme: const IconThemeData(color: Colors.white), + ), + body: isLoading + ? const Center(child: CircularProgressIndicator()) + : Center( + child: SingleChildScrollView( + padding: const EdgeInsets.all(16), + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 500), + child: Form( + key: _formKey, + child: Column( + children: [ + Text( + "Edit Data Gizi Balita", + style: GoogleFonts.poppins( + fontSize: 18, + fontWeight: FontWeight.bold, + color: Colors.black, + ), + textAlign: TextAlign.center, + ), + const SizedBox(height: 15), + + // CARD INFO BALITA (BIRU) + Container( + width: double.infinity, + padding: const EdgeInsets.all(15), + decoration: BoxDecoration( + color: Colors.blue, + borderRadius: BorderRadius.circular(10)), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(widget.dataGizi["nama"] ?? "-", + style: GoogleFonts.poppins( + color: Colors.white, + fontWeight: FontWeight.bold, + fontSize: 15)), + const Divider(color: Colors.white), + _rowInfo("Tgl Pemeriksaan", tglPeriksa), + _rowInfo("Usia Balita", usia), + _rowInfo("BB / TB / LK", + "${widget.dataGizi['bb']} kg / ${widget.dataGizi['tb']} cm / ${widget.dataGizi['lk']} cm"), + _rowInfo("Catatan Kader", catatan), + ], + ), + ), + const SizedBox(height: 15), + + // CARD INPUT (PUTIH) + Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(10), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.05), + blurRadius: 10) + ], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Bagian Input Z-Score & Tampilan Standar Deviasi (Sama dengan Kode Tambah) + _buildSection( + "Z-Score BB/U", + zbbController, + keteranganBBU, + _listBBU, + _selectedStatusBBU, (v) { + setState(() => _selectedStatusBBU = v); + }), + + _buildSection( + "Z-Score TB/U", + ztbController, + keteranganTBU, + _listTBU, + _selectedStatusTBU, (v) { + setState(() => _selectedStatusTBU = v); + }), + + _buildSection( + "Z-Score BB/TB", + zbbtbController, + keteranganBBTB, + _listBBTB, + _selectedStatusBBTB, (v) { + setState(() => _selectedStatusBBTB = v); + }), + + const Padding( + padding: EdgeInsets.symmetric(vertical: 10), + child: Divider(), + ), + + _buildLabel("Tindak Lanjut"), + _buildTextField(tindakController, + hint: "Masukkan rencana tindakan..."), + _buildLabel("Saran"), + _buildTextField(saranController, + hint: "Masukkan saran..."), + const SizedBox(height: 25), + + // --- TOMBOL SIMPAN PERUBAHAN --- + SizedBox( + width: double.infinity, + child: OutlinedButton( + onPressed: isLoading ? null : updateData, + style: OutlinedButton.styleFrom( + side: const BorderSide( + color: Colors.blue, width: 2), + shape: const StadiumBorder(), + padding: const EdgeInsets.symmetric( + vertical: 15), + ), + child: Text( + "Simpan Perubahan", + style: GoogleFonts.poppins( + color: Colors.blue, + fontSize: 13, + fontWeight: FontWeight.bold, + ), + ), + ), + ), + ], + ), + ), + ], + ), + ), + ), + ), + ), + ); + } + + // Komponen pembangun struktur input + kotak Standar Deviasi + Dropdown + Widget _buildSection(String title, TextEditingController controller, + String sd, List items, String? val, Function(String?) onChanged) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildLabel(title), + Row( + children: [ + Expanded( + flex: 2, + child: TextFormField( + controller: controller, + readOnly: true, + decoration: _inputDeco(isFilled: true), + style: GoogleFonts.poppins( + fontSize: 12, + fontWeight: FontWeight.bold, + color: Colors.blue[900]), + ), + ), + const SizedBox(width: 10), + Expanded( + flex: 3, + child: Container( + padding: const EdgeInsets.all(10), + decoration: BoxDecoration( + color: Colors.amber[50], + borderRadius: BorderRadius.circular(8), + border: Border.all(color: Colors.amber[200]!)), + child: Text( + sd, + style: GoogleFonts.poppins( + fontSize: 11, + fontWeight: FontWeight.bold, + color: Colors.amber[900]), + ), + ), + ), + ], + ), + const SizedBox(height: 10), + DropdownButtonFormField( + value: val, + hint: Text("Pilih Status $title", + style: GoogleFonts.poppins(fontSize: 12)), + isExpanded: true, + items: items + .map((e) => DropdownMenuItem( + value: e, + child: Text(e, style: GoogleFonts.poppins(fontSize: 12)))) + .toList(), + onChanged: onChanged, + decoration: _inputDeco(), + validator: (v) => v == null ? "Wajib dipilih" : null, + ), + const SizedBox(height: 10), + ], + ); + } + + Widget _rowInfo(String label, String value) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 2), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: 110, + child: Text(label, + style: GoogleFonts.poppins( + color: Colors.white, + fontSize: 12, + fontWeight: FontWeight.w600))), + const Text(": ", style: TextStyle(color: Colors.white)), + Expanded( + child: Text(value, + style: GoogleFonts.poppins( + color: Colors.white, + fontSize: 12, + fontWeight: FontWeight.w500))), + ], + ), + ); + } + + Widget _buildLabel(String t) => Padding( + padding: const EdgeInsets.only(top: 10, bottom: 4), + child: Text(t, + style: + GoogleFonts.poppins(fontSize: 12, fontWeight: FontWeight.w600))); + + Widget _buildTextField(TextEditingController c, {String? hint}) { + return TextFormField( + controller: c, + maxLines: 2, + style: GoogleFonts.poppins(fontSize: 12, color: Colors.black), + decoration: _inputDeco(hint: hint), + ); + } + + InputDecoration _inputDeco({String? hint, bool isFilled = false}) { + return InputDecoration( + hintText: hint, + hintStyle: GoogleFonts.poppins(fontSize: 11), + filled: true, + fillColor: isFilled ? Colors.blue[50] : Colors.grey[50], + contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide(color: Colors.grey[300]!)), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide(color: Colors.grey[300]!)), + ); + } +} diff --git a/lib/bidan/crud_data_gizi/riwayat_gizi_balita.dart b/lib/bidan/crud_data_gizi/riwayat_gizi_balita.dart new file mode 100644 index 0000000..87e3e6c --- /dev/null +++ b/lib/bidan/crud_data_gizi/riwayat_gizi_balita.dart @@ -0,0 +1,476 @@ +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:http/http.dart' as http; +import 'edit_gizi_balita.dart'; + +class RiwayatGiziBalitaPage extends StatefulWidget { + final Map balita; + + const RiwayatGiziBalitaPage({super.key, required this.balita}); + + @override + State createState() => _RiwayatGiziBalitaPageState(); +} + +class _RiwayatGiziBalitaPageState extends State { + List> _riwayatGizi = []; + List> _filteredRiwayatGizi = []; + bool _isLoading = true; + final TextEditingController _searchController = TextEditingController(); + + // Variabel Pagination + int _currentPage = 0; + final int _rowsPerPage = 5; + + @override + void initState() { + super.initState(); + fetchRiwayat(); + } + + // Logika mendapatkan data per halaman + List> get _paginatedData { + if (_filteredRiwayatGizi.isEmpty) return []; + final start = _currentPage * _rowsPerPage; + final end = start + _rowsPerPage; + if (start >= _filteredRiwayatGizi.length) return []; + return _filteredRiwayatGizi.sublist( + start, + end > _filteredRiwayatGizi.length ? _filteredRiwayatGizi.length : end, + ); + } + + String formatTanggal(String? tgl) { + if (tgl == null || tgl == "-" || tgl.isEmpty) return "-"; + try { + DateTime dt = DateTime.parse(tgl); + List bulanIndo = [ + "", + "Januari", + "Februari", + "Maret", + "April", + "Mei", + "Juni", + "Juli", + "Agustus", + "September", + "Oktober", + "November", + "Desember" + ]; + return "${dt.day} ${bulanIndo[dt.month]} ${dt.year}"; + } catch (e) { + return tgl; + } + } + + void _filterData(String query) { + setState(() { + _filteredRiwayatGizi = _riwayatGizi.where((data) { + final tanggal = + data["tanggal_pemeriksaan"]?.toString().toLowerCase() ?? ""; + return tanggal.contains(query.toLowerCase()); + }).toList(); + _currentPage = 0; // Reset ke halaman pertama saat mencari + }); + } + + String hitungUsia(String? tglLahir) { + if (tglLahir == null || tglLahir == "-" || tglLahir.isEmpty) return "-"; + try { + DateTime lahir = DateTime.parse(tglLahir); + DateTime sekarang = DateTime.now(); + int bulan = + (sekarang.year - lahir.year) * 12 + sekarang.month - lahir.month; + return "$bulan Bulan"; + } catch (e) { + return "-"; + } + } + + Future fetchRiwayat() async { + setState(() => _isLoading = true); + try { + final idBalita = widget.balita['id']; + final response = await http.get( + Uri.parse( + "http://ta.myhost.id/E31230549/mposyandu_api/gizi_balita/get_riwayat_gizi_balita.php?id_balita=$idBalita"), + ); + + if (response.statusCode == 200) { + final data = json.decode(response.body); + setState(() { + _riwayatGizi = List>.from(data); + _filteredRiwayatGizi = _riwayatGizi; + _isLoading = false; + }); + } else { + throw Exception("Gagal load data"); + } + } catch (e) { + setState(() => _isLoading = false); + } + } + + Future hapusData(String idGizi) async { + try { + final response = await http.post( + Uri.parse( + "http://ta.myhost.id/E31230549/mposyandu_api/gizi_balita/hapus_gizi_balita.php"), + headers: {"Content-Type": "application/json"}, + body: jsonEncode({"id_gizi": idGizi}), + ); + final res = json.decode(response.body); + if (res["success"] == true) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text("Data berhasil dihapus"))); + fetchRiwayat(); + } + } catch (e) { + ScaffoldMessenger.of(context) + .showSnackBar(SnackBar(content: Text("Error: $e"))); + } + } + + @override + Widget build(BuildContext context) { + final totalPages = _filteredRiwayatGizi.isEmpty + ? 1 + : (_filteredRiwayatGizi.length / _rowsPerPage).ceil(); + + return Scaffold( + backgroundColor: Colors.grey[50], + appBar: AppBar( + backgroundColor: Colors.blue, + elevation: 0, + iconTheme: const IconThemeData(color: Colors.white), + title: Text("", + style: GoogleFonts.poppins( + color: Colors.white, + fontSize: 16, + fontWeight: FontWeight.w600)), + ), + body: Padding( + padding: const EdgeInsets.all(16), + child: Column( + children: [ + Center( + child: Text("Data Riwayat Gizi Balita", + style: GoogleFonts.poppins( + fontSize: 18, + fontWeight: FontWeight.bold, + color: Colors.black)), + ), + const SizedBox(height: 15), + TextField( + controller: _searchController, + onChanged: _filterData, + style: GoogleFonts.poppins(fontSize: 12), + decoration: InputDecoration( + hintText: "Cari berdasarkan tanggal (YYYY-MM-DD)...", + hintStyle: GoogleFonts.poppins(fontSize: 12), + prefixIcon: const Icon(Icons.search, size: 20), + border: + OutlineInputBorder(borderRadius: BorderRadius.circular(10)), + contentPadding: const EdgeInsets.symmetric(vertical: 8), + ), + ), + const SizedBox(height: 20), + Expanded( + child: _isLoading + ? const Center(child: CircularProgressIndicator()) + : _filteredRiwayatGizi.isEmpty + ? Center( + child: Text("Data tidak ditemukan", + style: GoogleFonts.poppins( + fontSize: 12, color: Colors.grey))) + : ListView.builder( + itemCount: _paginatedData.length, + itemBuilder: (context, index) { + final gizi = _paginatedData[index]; + return _buildCardIdentik(gizi); + }, + ), + ), + Container( + padding: const EdgeInsets.symmetric(vertical: 8), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + "Halaman ${_currentPage + 1} dari $totalPages", + style: GoogleFonts.poppins(fontSize: 12), + ), + Row( + children: [ + IconButton( + icon: const Icon(Icons.chevron_left), + onPressed: _currentPage == 0 + ? null + : () => setState(() => _currentPage--), + ), + IconButton( + icon: const Icon(Icons.chevron_right), + onPressed: _currentPage >= totalPages - 1 + ? null + : () => setState(() => _currentPage++), + ), + ], + ), + ], + ), + ), + ], + ), + ), + ); + } + + Widget _buildCardIdentik(Map data) { + return Container( + margin: const EdgeInsets.only(bottom: 16), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12), + boxShadow: const [ + BoxShadow(color: Colors.black12, blurRadius: 8, offset: Offset(0, 4)) + ], + ), + child: Column( + children: [ + Container( + width: double.infinity, + padding: const EdgeInsets.all(15), + decoration: const BoxDecoration( + color: Colors.blue, + borderRadius: BorderRadius.vertical(top: Radius.circular(12)), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(widget.balita["nama"]?.toString() ?? "-", + style: GoogleFonts.poppins( + color: Colors.white, + fontWeight: FontWeight.bold, + fontSize: 14)), + const Divider(color: Colors.white54), + _rowWhite("Orang Tua", + widget.balita["nama_orang_tua"]?.toString() ?? "-"), + _rowWhite("Usia", + hitungUsia(widget.balita["tanggal_lahir"]?.toString())), + _rowWhite("Tgl Pemeriksaan", + formatTanggal(data["tanggal_pemeriksaan"]?.toString())), + _rowWhite("BB / TB / LK", + "${data['bb'] ?? '-'}kg / ${data['tb'] ?? '-'}cm / ${data['lk'] ?? '-'}cm"), + _rowWhite("Catatan Kader", data["catatan"]?.toString() ?? "-"), + ], + ), + ), + Container( + width: double.infinity, + padding: const EdgeInsets.all(15), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text("Detail Pemeriksaan", + style: GoogleFonts.poppins( + fontWeight: FontWeight.w600, fontSize: 12)), + const SizedBox(height: 8), + _rowGizi( + "Z-Score BB/U", data["zscore_bb_u"]?.toString() ?? "-"), + _rowGizi( + "Z-Score TB/U", data["zscore_tb_u"]?.toString() ?? "-"), + _rowGizi( + "Z-Score BB/TB", data["zscore_bb_tb"]?.toString() ?? "-"), + const Divider(), + _rowStatus("Status Gizi", data), + _rowGizi( + "Tindak Lanjut", data["tindak_lanjut"]?.toString() ?? "-"), + _rowGizi("Saran", data["saran"]?.toString() ?? "-"), + const SizedBox(height: 12), + Row( + children: [ + _stadiumButton(Icons.edit, "Edit", Colors.orange, () async { + await Navigator.push( + context, + MaterialPageRoute( + builder: (context) => EditGiziBalitaPage( + dataGizi: { + ...data, + "nama": widget.balita["nama"], + "tanggal_lahir": widget.balita["tanggal_lahir"], + }, + ), + ), + ); + fetchRiwayat(); + }), + const SizedBox(width: 8), + _stadiumButton(Icons.delete, "Hapus", Colors.red, () { + _showDeleteDialog(data["id_gizi"].toString()); + }), + ], + ) + ], + ), + ), + ], + ), + ); + } + + Widget _rowWhite(String label, String value) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: Row( + children: [ + SizedBox( + width: 120, + child: Text(label, + style: GoogleFonts.poppins( + color: Colors.white, + fontSize: 12, + fontWeight: FontWeight.w600))), + const Text(": ", style: TextStyle(color: Colors.white)), + Expanded( + child: Text(value, + style: + GoogleFonts.poppins(color: Colors.white, fontSize: 12))), + ], + ), + ); + } + + Widget _rowGizi(String label, String value) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: Row( + children: [ + SizedBox( + width: 120, + child: Text(label, + style: GoogleFonts.poppins( + fontSize: 12, + fontWeight: FontWeight.w600, + color: Colors.grey[800]))), + const Text(": "), + Expanded( + child: Text(value, + style: + GoogleFonts.poppins(fontSize: 12, color: Colors.black))), + ], + ), + ); + } + + Widget _rowStatus(String label, Map data) { + return Container( + margin: const EdgeInsets.symmetric(vertical: 5), + padding: const EdgeInsets.all(10), + decoration: BoxDecoration( + color: Colors.orange[50], borderRadius: BorderRadius.circular(8)), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text("$label :", + style: GoogleFonts.poppins( + fontSize: 12, + fontWeight: FontWeight.w600, + color: Colors.orange[900])), + const SizedBox(height: 4), + Padding( + padding: const EdgeInsets.only(left: 12), + child: Column( + children: [ + _rowStatusDetail("BB / U", data["status_bbu"] ?? "-"), + _rowStatusDetail("TB / U", data["status_tbu"] ?? "-"), + _rowStatusDetail("BB / TB", data["status_bbtb"] ?? "-"), + ], + ), + ), + ], + ), + ); + } + + Widget _rowStatusDetail(String indikator, String nilai) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 2), + child: Row( + children: [ + SizedBox( + width: 65, + child: Text( + indikator, + style: GoogleFonts.poppins( + fontSize: 12, + fontWeight: FontWeight.w600, + color: Colors.orange[900]), + ), + ), + Text( + " : ", + style: GoogleFonts.poppins( + fontSize: 12, + fontWeight: FontWeight.w600, + color: Colors.orange[900]), + ), + Expanded( + child: Text( + nilai, + style: GoogleFonts.poppins( + fontSize: 12, + fontWeight: FontWeight.bold, + color: Colors.orange[900]), + ), + ), + ], + ), + ); + } + + Widget _stadiumButton( + IconData icon, String text, Color color, VoidCallback onPressed) { + return Expanded( + child: OutlinedButton.icon( + onPressed: onPressed, + icon: Icon(icon, size: 14, color: color), + label: Text(text, + style: GoogleFonts.poppins( + fontSize: 11, color: color, fontWeight: FontWeight.bold)), + style: OutlinedButton.styleFrom( + side: BorderSide(color: color), + shape: const StadiumBorder(), + padding: const EdgeInsets.symmetric(vertical: 8), + ), + ), + ); + } + + void _showDeleteDialog(String id) { + showDialog( + context: context, + builder: (context) => AlertDialog( + title: Text("Hapus Data", + style: + GoogleFonts.poppins(fontWeight: FontWeight.bold, fontSize: 16)), + content: Text("Yakin ingin menghapus data pemeriksaan ini?", + style: GoogleFonts.poppins(fontSize: 13)), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text("Batal")), + TextButton( + onPressed: () async { + Navigator.pop(context); + await hapusData(id); + }, + child: const Text("Hapus", style: TextStyle(color: Colors.red)), + ), + ], + ), + ); + } +} diff --git a/lib/bidan/crud_data_gizi/tambah_gizi_balita.dart b/lib/bidan/crud_data_gizi/tambah_gizi_balita.dart new file mode 100644 index 0000000..6e192cb --- /dev/null +++ b/lib/bidan/crud_data_gizi/tambah_gizi_balita.dart @@ -0,0 +1,453 @@ +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:http/http.dart' as http; + +class TambahGiziBalitaPage extends StatefulWidget { + final Map balita; + + const TambahGiziBalitaPage({super.key, required this.balita}); + + @override + State createState() => _TambahGiziBalitaPageState(); +} + +class _TambahGiziBalitaPageState extends State { + final _formKey = GlobalKey(); + bool _isSaving = false; + bool _isLoadingPreview = + true; // Menahan transisi widget selama proses hitung API + + // Controller text form input & field readonly + final TextEditingController _bbUController = TextEditingController(); + final TextEditingController _tbUController = TextEditingController(); + final TextEditingController _bbTbController = TextEditingController(); + final TextEditingController _tindakLanjutController = TextEditingController(); + final TextEditingController _saranController = TextEditingController(); + + // Status klasifikasi gizi text yang dihitung dinamis oleh server PHP + String? _selectedStatusBBU; + String? _selectedStatusTBU; + String? _selectedStatusBBTB; + + String keteranganBBU = "Menghitung..."; + String keteranganTBU = "Menghitung..."; + String keteranganBBTB = "Menghitung..."; + + // Master list referensi dropdown status gizi penyeimbang data + final List _listBBU = [ + 'Gizi Buruk', + 'Gizi Kurang', + 'Gizi Baik', + 'Risiko Gizi Lebih' + ]; + final List _listTBU = ['Sangat Pendek', 'Pendek', 'Normal', 'Tinggi']; + final List _listBBTB = [ + 'Sangat Kurus', + 'Kurus', + 'Normal', + 'Gemuk', + 'Obesitas' + ]; + + @override + void initState() { + super.initState(); + _ambilPreviewKalkulasiServer(); + } + + // Helper pembersih string angka timbangan gizi anak di card atas + String formatAngka(dynamic value, String satuan) { + if (value == null || + value.toString().trim().isEmpty || + value.toString().toLowerCase() == "null") { + return "-"; + } + return "${value.toString()} $satuan"; + } + + // ========================================================================= + // Fungsi Pendukung Realtime Preview Kalkulasi Z-Score dari Database Server + // ========================================================================= + Future _ambilPreviewKalkulasiServer() async { + try { + final response = await http.post( + Uri.parse( + "http://ta.myhost.id/E31230549/mposyandu_api/gizi_balita/tambah_gizi_balita.php"), + body: { + "id_pemeriksaan": widget.balita["id_pemeriksaan"].toString(), + "id_balita": widget.balita["id"].toString(), + "mode": "preview" // Triger parameter pembeda request mode di PHP + }, + ); + + final result = json.decode(response.body); + if (result['success'] == true) { + double zBBU = + double.tryParse(result['zscore_bb_u']?.toString() ?? '0.0') ?? 0.0; + double zTBU = + double.tryParse(result['zscore_tb_u']?.toString() ?? '0.0') ?? 0.0; + double zBBTB = + double.tryParse(result['zscore_bb_tb']?.toString() ?? '0.0') ?? 0.0; + + _bbUController.text = zBBU.toStringAsFixed(2); + _tbUController.text = zTBU.toStringAsFixed(2); + _bbTbController.text = zBBTB.toStringAsFixed(2); + + String serverBBU = result['status_bbu']?.toString() ?? 'Gizi Baik'; + String serverTBU = result['status_tbu']?.toString() ?? 'Normal'; + String serverBBTB = result['status_bbtb']?.toString() ?? 'Normal'; + + // Penyelaras kata kunci jika seandainya backend mengirimkan teks "Normal" pada kategori BB/U + if (serverBBU == "Normal") serverBBU = "Gizi Baik"; + + setState(() { + // Sistem pengaman asersi: hanya masukkan value ke dropdown jika string terdaftar di list widget + _selectedStatusBBU = _listBBU.contains(serverBBU) ? serverBBU : null; + _selectedStatusTBU = _listTBU.contains(serverTBU) ? serverTBU : null; + _selectedStatusBBTB = + _listBBTB.contains(serverBBTB) ? serverBBTB : null; + + keteranganBBU = _getSDStatus(zBBU); + keteranganTBU = _getSDStatus(zTBU); + keteranganBBTB = _getSDStatus(zBBTB); + _isLoadingPreview = + false; // Mematikan putaran loading & memunculkan form komponen gizi + }); + } else { + setState(() => _isLoadingPreview = false); + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text("Info: ${result['message']}"))); + } + } + } catch (e) { + setState(() { + keteranganBBU = "Gagal memuat"; + keteranganTBU = "Gagal memuat"; + keteranganBBTB = "Gagal memuat"; + _isLoadingPreview = false; + }); + } + } + + // ========================================================================= + // Perbaikan Inti: Logika Pemisah Angka Minus & Plus Terhadap Nilai Median + // ========================================================================= + String _getSDStatus(double z) { + if (z < -3) return "Di bawah -3 SD"; + if (z < -2) return "-3 SD s/d -2 SD"; + + // Jika nilai desimal minus (misal -0.07), langsung kunci ke rentang kiri median + if (z < 0) return "-2 SD s/d < Median"; + // Jika nilai desimal nol atau positif kecil, masukkan ke rentang kanan median + if (z <= 1) return "Median s/d +1 SD"; + + if (z <= 2) return "Di atas +1 SD s/d +2 SD"; + return "Di atas +2 SD"; + } + + // ========================================================================= + // Fungsi Penyimpanan Data Gizi Transaksional Bersih ke Server API + // ========================================================================= + Future _simpanData() async { + if (!_formKey.currentState!.validate()) return; + + setState(() => _isSaving = true); + try { + final response = await http.post( + Uri.parse( + "http://ta.myhost.id/E31230549/mposyandu_api/gizi_balita/tambah_gizi_balita.php"), + body: { + "id_pemeriksaan": widget.balita["id_pemeriksaan"].toString(), + "id_balita": widget.balita["id"].toString(), + "tindak_lanjut": _tindakLanjutController.text, + "saran": _saranController.text, + "status_bbu": _selectedStatusBBU, + "status_tbu": _selectedStatusTBU, + "status_bbtb": _selectedStatusBBTB, + }, + ); + + final result = json.decode(response.body); + if (result['success'] == true) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text("Data Berhasil Disimpan"))); + Navigator.pop(context, true); + } else { + throw result['message']; + } + } catch (e) { + ScaffoldMessenger.of(context) + .showSnackBar(SnackBar(content: Text("Error: $e"))); + } finally { + if (mounted) setState(() => _isSaving = false); + } + } + + @override + Widget build(BuildContext context) { + final bb = formatAngka(widget.balita['bb'], "kg"); + final tb = formatAngka(widget.balita['tb'], "cm"); + + return Scaffold( + backgroundColor: Colors.grey[100], + appBar: AppBar( + backgroundColor: Colors.blue, + iconTheme: const IconThemeData(color: Colors.white), + elevation: 0, + ), + body: Center( + child: SingleChildScrollView( + padding: const EdgeInsets.all(16), + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 500), + child: Form( + key: _formKey, + child: Column( + children: [ + // Judul Besar Halaman Tengah Atas + Text( + "Tambah Data Gizi Balita", + style: GoogleFonts.poppins( + fontSize: 18, + fontWeight: FontWeight.bold, + color: Colors.black), + ), + const SizedBox(height: 15), + + // Card Informasi Identitas Balita (Warna Biru) + Container( + width: double.infinity, + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: Colors.blue, + borderRadius: BorderRadius.circular(12)), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + widget.balita["nama"] ?? "-", + style: GoogleFonts.poppins( + color: Colors.white, + fontWeight: FontWeight.bold, + fontSize: 15), + ), + const SizedBox(height: 4), + const Divider(color: Colors.white54, thickness: 1), + const SizedBox(height: 4), + Text("BB / TB: $bb / $tb", + style: GoogleFonts.poppins( + color: Colors.white, fontSize: 13)), + ], + ), + ), + const SizedBox(height: 15), + + // Blok Container Putih Pembungkus Seluruh Form Gizi + Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.05), + blurRadius: 10) + ], + ), + child: _isLoadingPreview + ? const Padding( + padding: EdgeInsets.all(30.0), + child: Center(child: CircularProgressIndicator()), + ) + : Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // 1. Seksi Z-Score BB/U + _buildSection( + "Z-Score BB/U", + _bbUController, + keteranganBBU, + _listBBU, + _selectedStatusBBU, + (v) => + setState(() => _selectedStatusBBU = v)), + + // 2. Seksi Z-Score TB/U + _buildSection( + "Z-Score TB/U", + _tbUController, + keteranganTBU, + _listTBU, + _selectedStatusTBU, + (v) => + setState(() => _selectedStatusTBU = v)), + + // 3. Seksi Z-Score BB/TB + _buildSection( + "Z-Score BB/TB", + _bbTbController, + keteranganBBTB, + _listBBTB, + _selectedStatusBBTB, + (v) => + setState(() => _selectedStatusBBTB = v)), + + const Divider(height: 30, thickness: 1), + + // Input Field Catatan Tindak Lanjut + _buildLabel("Tindak Lanjut"), + _buildTextField(_tindakLanjutController, + "Rencana tindakan..."), + + const SizedBox(height: 10), + + // Input Field Catatan Saran + _buildLabel("Saran"), + _buildTextField( + _saranController, "Saran untuk orang tua..."), + + const SizedBox(height: 25), + + // Tombol Aksi Simpan Data Bergaya Outline (Putih-Biru Stadium) + SizedBox( + width: double.infinity, + child: OutlinedButton( + onPressed: _isSaving ? null : _simpanData, + style: OutlinedButton.styleFrom( + backgroundColor: Colors.white, + side: const BorderSide( + color: Colors.blue, width: 2), + shape: const StadiumBorder(), + padding: const EdgeInsets.symmetric( + vertical: 14)), + child: _isSaving + ? const SizedBox( + height: 18, + width: 18, + child: CircularProgressIndicator( + strokeWidth: 2, + color: Colors.blue)) + : Text("Simpan Data Gizi", + style: GoogleFonts.poppins( + color: Colors.blue, + fontWeight: FontWeight.bold, + fontSize: 14)), + ), + ), + ], + ), + ), + ], + ), + ), + ), + ), + ), + ); + } + + // Widget generator baris isian Z-score (Form, Label SD, dan Dropdown Kategori) + Widget _buildSection(String title, TextEditingController controller, + String sd, List items, String? val, Function(String?) onChanged) { + // Penentu warna latar background dinamis teks keterangan rentang SD + Color bgKuningMuda = + sd.contains('atas') ? Colors.orange[50]! : Colors.amber[50]!; + Color borderKuning = + sd.contains('atas') ? Colors.orange[200]! : Colors.amber[200]!; + Color textKuningTua = + sd.contains('atas') ? Colors.orange[900]! : Colors.amber[900]!; + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildLabel(title), + Row( + children: [ + // Sisi Kiri: Nilai Angka Z-Score (Read-Only) + Expanded( + flex: 2, + child: TextFormField( + controller: controller, + readOnly: true, + decoration: _inputDeco(isFilled: true), + style: GoogleFonts.poppins( + fontSize: 12, fontWeight: FontWeight.bold))), + const SizedBox(width: 10), + // Sisi Kanan: Teks Status Deviasi (Warna Kuning/Orange Kotak) + Expanded( + flex: 3, + child: Container( + padding: const EdgeInsets.symmetric( + horizontal: 12, vertical: 11), + decoration: BoxDecoration( + color: bgKuningMuda, + borderRadius: BorderRadius.circular(8), + border: Border.all(color: borderKuning)), + child: Text(sd, + style: GoogleFonts.poppins( + fontSize: 11, + fontWeight: FontWeight.bold, + color: textKuningTua)))), + ], + ), + const SizedBox(height: 10), + // Dropdown Pemilihan Status Klasifikasi Dibawahnya + DropdownButtonFormField( + value: val, + hint: Text("Pilih Status $title", + style: + GoogleFonts.poppins(fontSize: 12, color: Colors.grey[600])), + isExpanded: true, + items: items + .map((e) => DropdownMenuItem( + value: e, + child: Text(e, style: GoogleFonts.poppins(fontSize: 12)))) + .toList(), + onChanged: onChanged, + decoration: _inputDeco(), + validator: (v) => v == null ? "Pilih salah satu status" : null, + ), + const SizedBox(height: 10), + ], + ); + } + + Widget _buildLabel(String t) => Padding( + padding: const EdgeInsets.only(top: 10, bottom: 6), + child: Text(t, + style: GoogleFonts.poppins( + fontSize: 12, + fontWeight: FontWeight.bold, + color: Colors.black87))); + + Widget _buildTextField(TextEditingController c, String h) => TextFormField( + controller: c, + maxLines: 2, + style: GoogleFonts.poppins(fontSize: 12), + decoration: _inputDeco(hint: h)); + + InputDecoration _inputDeco({String? hint, bool isFilled = false}) => + InputDecoration( + hintText: hint, + hintStyle: GoogleFonts.poppins(fontSize: 11, color: Colors.grey[400]), + filled: true, + fillColor: isFilled ? Colors.blue[50] : Colors.white, + contentPadding: + const EdgeInsets.symmetric(horizontal: 12, vertical: 10), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide(color: Colors.grey[300]!)), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: const BorderSide(color: Colors.blue)), + errorBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: const BorderSide(color: Colors.red)), + focusedErrorBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: const BorderSide(color: Colors.red, width: 2)), + ); +} diff --git a/lib/bidan/crud_edukasi/edit_edukasi_balita.dart b/lib/bidan/crud_edukasi/edit_edukasi_balita.dart new file mode 100644 index 0000000..1a88a19 --- /dev/null +++ b/lib/bidan/crud_edukasi/edit_edukasi_balita.dart @@ -0,0 +1,342 @@ +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:http/http.dart' as http; +import 'package:image_picker/image_picker.dart'; + +class EditEdukasiBalitaPage extends StatefulWidget { + final Map data; + const EditEdukasiBalitaPage({super.key, required this.data}); + + @override + State createState() => _EditEdukasiBalitaPageState(); +} + +class _EditEdukasiBalitaPageState extends State { + final _formKey = GlobalKey(); + + late TextEditingController _judulController; + late TextEditingController _deskripsiController; + + bool isSubmitting = false; + File? _selectedImage; + Uint8List? _webImage; + final picker = ImagePicker(); + + // Sesuaikan URL jika sudah beralih ke hosting ta.myhost.id + final String urlEdit = + "http://ta.myhost.id/E31230549/mposyandu_api/edukasi_balita/edit_edukasi_balita.php"; + + @override + void initState() { + super.initState(); + _judulController = TextEditingController(text: widget.data['judul']); + + // Memproses deskripsi agar kode JSON Delta dikonversi menjadi teks biasa + String rawDeskripsi = widget.data['deskripsi'] ?? ""; + _deskripsiController = TextEditingController( + text: _convertJsonToPlainText(rawDeskripsi), + ); + } + + // Fungsi untuk membersihkan format JSON Quill menjadi Plain Text + String _convertJsonToPlainText(String input) { + try { + // Jika input diawali dengan '[' berarti itu format JSON Delta + if (input.trim().startsWith('[')) { + List jsonDelta = jsonDecode(input); + String plainText = ""; + for (var node in jsonDelta) { + if (node['insert'] != null) { + plainText += node['insert']; + } + } + return plainText; + } + } catch (e) { + debugPrint("Info: Deskripsi bukan format JSON, menggunakan teks asli."); + } + return input; // Kembalikan teks asli jika bukan JSON atau gagal decode + } + + @override + void dispose() { + _judulController.dispose(); + _deskripsiController.dispose(); + super.dispose(); + } + + Future pickImage() async { + final picked = await picker.pickImage( + source: ImageSource.gallery, + imageQuality: 80, + ); + + if (picked == null) return; + + if (kIsWeb) { + _webImage = await picked.readAsBytes(); + } else { + _selectedImage = File(picked.path); + } + + setState(() {}); + } + + Future _updateData() async { + if (!_formKey.currentState!.validate()) return; + setState(() => isSubmitting = true); + + try { + var request = http.MultipartRequest("POST", Uri.parse(urlEdit)); + request.fields["id"] = widget.data["id"].toString(); + request.fields["judul"] = _judulController.text; + request.fields["deskripsi"] = _deskripsiController.text; + + if (_selectedImage != null) { + request.files.add( + await http.MultipartFile.fromPath("gambar", _selectedImage!.path), + ); + } else if (_webImage != null) { + request.files.add( + http.MultipartFile.fromBytes( + "gambar", + _webImage!, + filename: "upload.jpg", + ), + ); + } + + var response = await request.send(); + var res = await http.Response.fromStream(response); + var data = jsonDecode(res.body); + + if (data["status"] == "success") { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text("Data berhasil diperbarui")), + ); + Navigator.pop(context, true); + } else { + throw data["message"] ?? "Gagal memperbarui data"; + } + } catch (e) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text("Terjadi kesalahan: $e")), + ); + } finally { + if (mounted) setState(() => isSubmitting = false); + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: const Color(0xFFF5F5F5), + appBar: AppBar( + title: Text("", + style: GoogleFonts.poppins(color: Colors.white, fontSize: 16)), + backgroundColor: Colors.blue, + elevation: 0, + centerTitle: true, + iconTheme: const IconThemeData(color: Colors.white), + ), + body: SingleChildScrollView( + padding: const EdgeInsets.all(16), + child: Center( + child: Container( + constraints: const BoxConstraints(maxWidth: 900), + child: Card( + color: Colors.white, + elevation: 3, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10), + ), + child: Padding( + padding: const EdgeInsets.all(25), + child: Form( + key: _formKey, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Center( + child: Text( + "Perbarui Edukasi Balita", + style: GoogleFonts.poppins( + fontSize: 18, + fontWeight: FontWeight.bold, + ), + ), + ), + const SizedBox(height: 10), + const Divider(), + const SizedBox(height: 20), + _buildLabel("Gambar Edukasi"), + _buildImagePreview(), + const SizedBox(height: 30), + _buildLabel("Judul Edukasi"), + _buildTitleField(), + const SizedBox(height: 25), + _buildLabel("Deskripsi"), + _buildDescriptionField(), + const SizedBox(height: 35), + _buildSubmitButton(), + ], + ), + ), + ), + ), + ), + ), + ), + ); + } + + Widget _buildDescriptionField() { + return TextFormField( + controller: _deskripsiController, + maxLines: 12, + keyboardType: TextInputType.multiline, + style: GoogleFonts.poppins(fontSize: 14), + decoration: InputDecoration( + hintText: "Tulis isi materi di sini...", + filled: true, + fillColor: Colors.grey[50], + contentPadding: const EdgeInsets.all(15), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: BorderSide(color: Colors.grey.shade400), + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: const BorderSide(color: Colors.blue), + ), + ), + validator: (value) => + value == null || value.isEmpty ? "Wajib diisi" : null, + ); + } + + Widget _buildImagePreview() { + return Center( + child: Column( + children: [ + Container( + height: 200, + width: 350, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(10), + border: Border.all(color: Colors.grey.shade200), + ), + child: ClipRRect( + borderRadius: BorderRadius.circular(10), + child: _selectedImage != null + ? Image.file(_selectedImage!, fit: BoxFit.cover) + : _webImage != null + ? Image.memory(_webImage!, fit: BoxFit.cover) + : (widget.data["gambar"] != null + ? Image.network( + "http://ta.myhost.id/E31230549/mposyandu_api/upload/edukasi/${widget.data['gambar']}", + fit: BoxFit.cover, + errorBuilder: (c, e, s) => const Icon(Icons.image, + size: 50, color: Colors.grey), + ) + : const Icon(Icons.image, + size: 50, color: Colors.grey)), + ), + ), + const SizedBox(height: 12), + SizedBox( + height: 35, + child: OutlinedButton.icon( + onPressed: pickImage, + icon: const Icon(Icons.image, size: 16), + label: Text( + "Ganti Gambar", + style: GoogleFonts.poppins(fontSize: 12), + ), + style: OutlinedButton.styleFrom( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(20), + ), + foregroundColor: Colors.blue, + side: BorderSide(color: Colors.grey.shade300), + ), + ), + ), + ], + ), + ); + } + + Widget _buildLabel(String label) { + return Padding( + padding: const EdgeInsets.only(bottom: 8), + child: Text( + label, + style: GoogleFonts.poppins( + fontSize: 13, + fontWeight: FontWeight.bold, + color: Colors.black87, + ), + ), + ); + } + + Widget _buildTitleField() { + return TextFormField( + controller: _judulController, + style: GoogleFonts.poppins(fontSize: 14), + decoration: InputDecoration( + hintText: "Masukkan judul", + filled: true, + fillColor: Colors.grey[50], + contentPadding: + const EdgeInsets.symmetric(horizontal: 15, vertical: 12), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: BorderSide(color: Colors.grey.shade400), + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: const BorderSide(color: Colors.blue), + ), + ), + validator: (value) => + value == null || value.isEmpty ? "Wajib diisi" : null, + ); + } + + Widget _buildSubmitButton() { + return Align( + alignment: Alignment.centerRight, + child: SizedBox( + width: 180, + child: ElevatedButton( + onPressed: isSubmitting ? null : _updateData, + style: ElevatedButton.styleFrom( + backgroundColor: Colors.blue, + foregroundColor: Colors.white, + padding: const EdgeInsets.symmetric(vertical: 15), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10), + ), + ), + child: isSubmitting + ? const SizedBox( + height: 20, + width: 20, + child: CircularProgressIndicator( + color: Colors.white, strokeWidth: 2), + ) + : Text("Simpan Perubahan", + style: GoogleFonts.poppins(fontWeight: FontWeight.bold)), + ), + ), + ); + } +} diff --git a/lib/bidan/crud_edukasi/edit_edukasi_ibu_hamil.dart b/lib/bidan/crud_edukasi/edit_edukasi_ibu_hamil.dart new file mode 100644 index 0000000..190ecfc --- /dev/null +++ b/lib/bidan/crud_edukasi/edit_edukasi_ibu_hamil.dart @@ -0,0 +1,313 @@ +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:http/http.dart' as http; +import 'package:image_picker/image_picker.dart'; + +class EditEdukasiBumilPage extends StatefulWidget { + final Map data; + const EditEdukasiBumilPage({super.key, required this.data}); + + @override + State createState() => _EditEdukasiBumilPageState(); +} + +class _EditEdukasiBumilPageState extends State { + final _formKey = GlobalKey(); + late TextEditingController _judulController; + late TextEditingController _deskripsiController; + + File? selectedImage; + Uint8List? webImage; + bool isSubmitting = false; + final picker = ImagePicker(); + + // Jika nanti sudah migrasi ke hosting, ganti localhost menjadi ta.myhost.id + final String urlEdit = + "http://ta.myhost.id/E31230549/mposyandu_api/edukasi_ibu_hamil/edit_edukasi_ibu_hamil.php"; + + @override + void initState() { + super.initState(); + _judulController = TextEditingController(text: widget.data['judul']); + + // Mengambil deskripsi dan membersihkannya dari format JSON Delta + String rawDeskripsi = widget.data['deskripsi'] ?? ""; + _deskripsiController = TextEditingController( + text: _convertJsonToPlainText(rawDeskripsi), + ); + } + + // Fungsi pembantu untuk mengonversi format JSON Quill ke teks biasa + String _convertJsonToPlainText(String input) { + try { + if (input.trim().startsWith('[')) { + List jsonDelta = jsonDecode(input); + String plainText = ""; + for (var node in jsonDelta) { + if (node['insert'] != null) { + plainText += node['insert']; + } + } + return plainText; + } + } catch (e) { + debugPrint("Info: Menggunakan teks asli karena bukan format JSON."); + } + return input; + } + + @override + void dispose() { + _judulController.dispose(); + _deskripsiController.dispose(); + super.dispose(); + } + + Future pickImage() async { + final picked = + await picker.pickImage(source: ImageSource.gallery, imageQuality: 80); + if (picked == null) return; + if (kIsWeb) { + webImage = await picked.readAsBytes(); + } else { + selectedImage = File(picked.path); + } + setState(() {}); + } + + Future _updateData() async { + if (!_formKey.currentState!.validate()) return; + setState(() => isSubmitting = true); + + try { + var request = http.MultipartRequest("POST", Uri.parse(urlEdit)); + request.fields["id"] = widget.data['id'].toString(); + request.fields["judul"] = _judulController.text; + request.fields["deskripsi"] = _deskripsiController.text; + + if (selectedImage != null) { + request.files.add( + await http.MultipartFile.fromPath("gambar", selectedImage!.path)); + } else if (webImage != null) { + request.files.add(http.MultipartFile.fromBytes("gambar", webImage!, + filename: "upload.jpg")); + } + + var response = await request.send(); + var res = await http.Response.fromStream(response); + var data = jsonDecode(res.body); + + if (data["status"] == "success") { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text("Data berhasil diperbarui")), + ); + Navigator.pop(context, true); + } else { + throw data["message"] ?? "Gagal memperbarui data"; + } + } catch (e) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text("Error: $e")), + ); + } finally { + if (mounted) setState(() => isSubmitting = false); + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: const Color(0xFFF5F5F5), + appBar: AppBar( + title: Text("", + style: GoogleFonts.poppins(color: Colors.white, fontSize: 16)), + backgroundColor: Colors.blue, + elevation: 0, + centerTitle: true, + iconTheme: const IconThemeData(color: Colors.white), + ), + body: SingleChildScrollView( + padding: const EdgeInsets.all(16), + child: Center( + child: Container( + constraints: const BoxConstraints(maxWidth: 900), + child: Card( + color: Colors.white, + elevation: 3, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10)), + child: Padding( + padding: const EdgeInsets.all(25), + child: Form( + key: _formKey, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Center( + child: Text( + "Edit Edukasi Ibu Hamil", + style: GoogleFonts.poppins( + fontSize: 18, + fontWeight: FontWeight.bold, + ), + ), + ), + const SizedBox(height: 10), + const Divider(), + const SizedBox(height: 20), + _buildLabel("Gambar Edukasi"), + _buildImageSection(), + const SizedBox(height: 25), + _buildLabel("Judul Edukasi"), + _buildTitleField(), + const SizedBox(height: 25), + _buildLabel("Deskripsi"), + _buildDescriptionField(), + const SizedBox(height: 35), + _buildSubmitButton(), + ], + ), + ), + ), + ), + ), + ), + ), + ); + } + + Widget _buildDescriptionField() { + return TextFormField( + controller: _deskripsiController, + maxLines: 12, + keyboardType: TextInputType.multiline, + style: GoogleFonts.poppins(fontSize: 14), + decoration: InputDecoration( + hintText: "Tulis isi materi di sini...", + filled: true, + fillColor: Colors.grey[50], + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: BorderSide(color: Colors.grey.shade400), + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: const BorderSide(color: Colors.blue), + ), + contentPadding: const EdgeInsets.all(15), + ), + validator: (value) => + value == null || value.isEmpty ? "Wajib diisi" : null, + ); + } + + Widget _buildImageSection() { + return Center( + child: Column( + children: [ + Container( + height: 200, + width: 350, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(10), + border: Border.all(color: Colors.grey.shade200), + ), + child: ClipRRect( + borderRadius: BorderRadius.circular(10), + child: selectedImage != null || webImage != null + ? (kIsWeb + ? Image.memory(webImage!, fit: BoxFit.cover) + : Image.file(selectedImage!, fit: BoxFit.cover)) + : (widget.data["gambar"] != null + ? Image.network( + "http://ta.myhost.id/E31230549/mposyandu_api/upload/edukasi/${widget.data['gambar']}", + fit: BoxFit.cover, + errorBuilder: (c, e, s) => const Icon( + Icons.broken_image, + size: 50, + color: Colors.grey), + ) + : const Icon(Icons.image, size: 50, color: Colors.grey)), + ), + ), + const SizedBox(height: 10), + TextButton.icon( + onPressed: pickImage, + icon: const Icon(Icons.camera_alt), + label: Text("Ganti Gambar", style: GoogleFonts.poppins())), + ], + ), + ); + } + + Widget _buildTitleField() { + return TextFormField( + controller: _judulController, + style: GoogleFonts.poppins(fontSize: 14), + decoration: InputDecoration( + hintText: "Masukkan Judul", + filled: true, + fillColor: Colors.grey[50], + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: BorderSide(color: Colors.grey.shade400), + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: const BorderSide(color: Colors.blue), + ), + contentPadding: + const EdgeInsets.symmetric(horizontal: 15, vertical: 12), + ), + validator: (value) => + value == null || value.isEmpty ? "Wajib diisi" : null, + ); + } + + Widget _buildSubmitButton() { + return Align( + alignment: Alignment.centerRight, + child: SizedBox( + width: 200, + height: 50, + child: ElevatedButton( + onPressed: isSubmitting ? null : _updateData, + style: ElevatedButton.styleFrom( + backgroundColor: Colors.blue, + foregroundColor: Colors.white, + shape: + RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)), + elevation: 2, + ), + child: isSubmitting + ? const SizedBox( + height: 20, + width: 20, + child: CircularProgressIndicator( + color: Colors.white, strokeWidth: 2)) + : Text( + "Simpan Perubahan", + style: GoogleFonts.poppins(fontWeight: FontWeight.bold), + ), + ), + ), + ); + } + + Widget _buildLabel(String text) { + return Padding( + padding: const EdgeInsets.only(bottom: 8), + child: Text(text, + style: GoogleFonts.poppins( + fontWeight: FontWeight.bold, + fontSize: 13, + color: Colors.black87)), + ); + } +} diff --git a/lib/bidan/crud_edukasi/tambah_edukasi_balita.dart b/lib/bidan/crud_edukasi/tambah_edukasi_balita.dart new file mode 100644 index 0000000..d5503f6 --- /dev/null +++ b/lib/bidan/crud_edukasi/tambah_edukasi_balita.dart @@ -0,0 +1,315 @@ +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:http/http.dart' as http; +import 'package:image_picker/image_picker.dart'; + +class TambahEdukasiBalitaPage extends StatefulWidget { + const TambahEdukasiBalitaPage({super.key}); + + @override + State createState() => + _TambahEdukasiBalitaPageState(); +} + +class _TambahEdukasiBalitaPageState extends State { + final _formKey = GlobalKey(); + + final TextEditingController _judulController = TextEditingController(); + // Menggunakan TextEditingController biasa untuk deskripsi agar fungsi ENTER lancar + final TextEditingController _deskripsiController = TextEditingController(); + + File? _imageFile; + Uint8List? _webImage; + + final ImagePicker _picker = ImagePicker(); + bool isSubmitting = false; + + final String urlTambah = + "http://ta.myhost.id/E31230549/mposyandu_api/edukasi_balita/tambah_edukasi_balita.php"; + + Future _pickImage() async { + try { + final XFile? pickedFile = await _picker.pickImage( + source: ImageSource.gallery, + imageQuality: 80, + ); + + if (pickedFile == null) return; + + if (kIsWeb) { + final bytes = await pickedFile.readAsBytes(); + setState(() { + _webImage = bytes; + _imageFile = null; + }); + } else { + setState(() { + _imageFile = File(pickedFile.path); + _webImage = null; + }); + } + } catch (e) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text("Gagal memilih gambar: $e")), + ); + } + } + + Future _simpanData() async { + if (!_formKey.currentState!.validate()) return; + + if (_imageFile == null && _webImage == null) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text("Silakan pilih gambar terlebih dahulu")), + ); + return; + } + + setState(() => isSubmitting = true); + + try { + var request = http.MultipartRequest('POST', Uri.parse(urlTambah)); + + request.fields['judul'] = _judulController.text; + // Kirim teks deskripsi apa adanya (mendukung pindah baris/newline) + request.fields['deskripsi'] = _deskripsiController.text; + + if (kIsWeb) { + request.files.add( + http.MultipartFile.fromBytes( + 'gambar', + _webImage!, + filename: "upload_web.jpg", + ), + ); + } else { + request.files.add( + await http.MultipartFile.fromPath( + 'gambar', + _imageFile!.path, + ), + ); + } + + var streamedResponse = await request.send(); + var response = await http.Response.fromStream(streamedResponse); + final data = jsonDecode(response.body); + + if (data['status'] == 'success') { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text("Data berhasil disimpan")), + ); + Navigator.pop(context); + } else { + throw data['message']; + } + } catch (e) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text("Terjadi kesalahan: $e")), + ); + } finally { + if (mounted) setState(() => isSubmitting = false); + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: const Color(0xFFF5F5F5), + appBar: AppBar( + title: const Text(""), + backgroundColor: Colors.blue, + elevation: 0, + iconTheme: const IconThemeData(color: Colors.white), + centerTitle: true, + ), + body: SingleChildScrollView( + padding: const EdgeInsets.all(16), + child: Center( + child: Container( + constraints: const BoxConstraints(maxWidth: 900), + child: Card( + elevation: 3, + color: Colors.white, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10), + ), + child: Padding( + padding: const EdgeInsets.all(25), + child: Form( + key: _formKey, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Center( + child: Text( + "Tambah Edukasi Balita", + style: GoogleFonts.poppins( + fontSize: 18, + fontWeight: FontWeight.bold, + color: Colors.black87, + ), + ), + ), + const SizedBox(height: 10), + const Divider(), + const SizedBox(height: 20), + + _buildLabel("Gambar Edukasi"), + const SizedBox(height: 8), + InkWell( + onTap: _pickImage, + borderRadius: BorderRadius.circular(10), + child: Container( + width: double.infinity, + height: 200, + decoration: BoxDecoration( + color: Colors.grey[50], + borderRadius: BorderRadius.circular(10), + border: Border.all(color: Colors.grey.shade300), + ), + child: _displayImage(), + ), + ), + const SizedBox(height: 25), + + _buildLabel("Judul Edukasi"), + _buildTitleField(), + const SizedBox(height: 25), + + _buildLabel("Deskripsi"), + // FIELD DESKRIPSI DENGAN FUNGSI ENTER (MULTILINE) + _buildDescriptionField(), + + const SizedBox(height: 35), + + _buildSubmitButton(), + ], + ), + ), + ), + ), + ), + ), + ), + ); + } + + Widget _buildDescriptionField() { + return TextFormField( + controller: _deskripsiController, + maxLines: 10, // Memberikan ruang untuk banyak baris + keyboardType: + TextInputType.multiline, // Mengaktifkan tombol ENTER di keyboard + style: GoogleFonts.poppins(fontSize: 14), + decoration: InputDecoration( + hintText: "Tulis isi edukasi di sini...", + hintStyle: GoogleFonts.poppins(color: Colors.grey, fontSize: 13), + filled: true, + fillColor: Colors.white, + contentPadding: const EdgeInsets.all(15), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: BorderSide(color: Colors.grey.shade300), + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: const BorderSide(color: Colors.blue, width: 1.5), + ), + ), + validator: (value) => + value == null || value.isEmpty ? "Wajib diisi" : null, + ); + } + + Widget _displayImage() { + if (_webImage != null || _imageFile != null) { + return ClipRRect( + borderRadius: BorderRadius.circular(10), + child: kIsWeb + ? Image.memory(_webImage!, fit: BoxFit.cover) + : Image.file(_imageFile!, fit: BoxFit.cover), + ); + } + return Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Icon(Icons.add_a_photo, color: Colors.blue, size: 40), + const SizedBox(height: 8), + Text( + "Klik untuk pilih gambar", + style: GoogleFonts.poppins(fontSize: 12, color: Colors.grey), + ), + ], + ); + } + + Widget _buildLabel(String label) { + return Padding( + padding: const EdgeInsets.only(bottom: 8), + child: Text( + label, + style: GoogleFonts.poppins( + fontSize: 13, + fontWeight: FontWeight.bold, + color: Colors.black87, + ), + ), + ); + } + + Widget _buildTitleField() { + return TextFormField( + controller: _judulController, + style: GoogleFonts.poppins(fontSize: 14), + decoration: InputDecoration( + hintText: "Contoh: Pentingnya MPASI", + hintStyle: GoogleFonts.poppins(color: Colors.grey, fontSize: 13), + filled: true, + fillColor: Colors.white, + contentPadding: + const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: BorderSide(color: Colors.grey.shade300), + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: const BorderSide(color: Colors.blue, width: 1.5), + ), + ), + validator: (value) => + value == null || value.isEmpty ? "Wajib diisi" : null, + ); + } + + Widget _buildSubmitButton() { + return SizedBox( + width: double.infinity, + height: 50, + child: ElevatedButton( + onPressed: isSubmitting ? null : _simpanData, + style: ElevatedButton.styleFrom( + backgroundColor: Colors.blue, + shape: + RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)), + ), + child: isSubmitting + ? const CircularProgressIndicator(color: Colors.white) + : Text( + "Simpan Edukasi", + style: GoogleFonts.poppins( + fontWeight: FontWeight.bold, + color: Colors.white, + ), + ), + ), + ); + } +} diff --git a/lib/bidan/crud_edukasi/tambah_edukasi_ibu_hamil.dart b/lib/bidan/crud_edukasi/tambah_edukasi_ibu_hamil.dart new file mode 100644 index 0000000..d8c5441 --- /dev/null +++ b/lib/bidan/crud_edukasi/tambah_edukasi_ibu_hamil.dart @@ -0,0 +1,267 @@ +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:http/http.dart' as http; +import 'package:image_picker/image_picker.dart'; + +class TambahEdukasiBumilPage extends StatefulWidget { + const TambahEdukasiBumilPage({super.key}); + + @override + State createState() => _TambahEdukasiBumilPageState(); +} + +class _TambahEdukasiBumilPageState extends State { + final _formKey = GlobalKey(); + final TextEditingController _judulController = TextEditingController(); + // Menggunakan TextEditingController biasa untuk deskripsi + final TextEditingController _deskripsiController = TextEditingController(); + + bool isSubmitting = false; + File? selectedImage; + Uint8List? webImage; + final picker = ImagePicker(); + + final String urlTambah = + "http://ta.myhost.id/E31230549/mposyandu_api/edukasi_ibu_hamil/tambah_edukasi_ibu_hamil.php"; + + Future pickImage() async { + final picked = await picker.pickImage( + source: ImageSource.gallery, + imageQuality: 80, + ); + + if (picked == null) return; + + if (kIsWeb) { + webImage = await picked.readAsBytes(); + } else { + selectedImage = File(picked.path); + } + + setState(() {}); + } + + Future _simpanData() async { + if (!_formKey.currentState!.validate()) return; + + if (selectedImage == null && webImage == null) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text("Silakan pilih gambar terlebih dahulu")), + ); + return; + } + + setState(() => isSubmitting = true); + + try { + var request = http.MultipartRequest("POST", Uri.parse(urlTambah)); + request.fields["judul"] = _judulController.text; + // Mengirim deskripsi sebagai teks biasa (mendukung enter/newline) + request.fields["deskripsi"] = _deskripsiController.text; + + if (selectedImage != null) { + request.files.add( + await http.MultipartFile.fromPath("gambar", selectedImage!.path)); + } + if (webImage != null) { + request.files.add(http.MultipartFile.fromBytes("gambar", webImage!, + filename: "upload.jpg")); + } + + var response = await request.send(); + var res = await http.Response.fromStream(response); + var data = jsonDecode(res.body); + + if (data["status"] == "success") { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text("Edukasi berhasil ditambahkan")), + ); + Navigator.pop(context); + } + } catch (e) { + ScaffoldMessenger.of(context) + .showSnackBar(SnackBar(content: Text("Error: $e"))); + } finally { + if (mounted) setState(() => isSubmitting = false); + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: const Color(0xFFF5F5F5), + appBar: AppBar( + title: const Text(""), + backgroundColor: Colors.blue, + elevation: 0, + centerTitle: true, + iconTheme: const IconThemeData(color: Colors.white), + ), + body: SingleChildScrollView( + padding: const EdgeInsets.all(16), + child: Center( + child: Container( + constraints: const BoxConstraints(maxWidth: 900), + child: Card( + elevation: 3, + color: Colors.white, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10)), + child: Padding( + padding: const EdgeInsets.all(25), + child: Form( + key: _formKey, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Center( + child: Text( + "Tambah Edukasi Ibu Hamil", + style: GoogleFonts.poppins( + fontSize: 18, + fontWeight: FontWeight.bold, + ), + ), + ), + const SizedBox(height: 10), + const Divider(), + const SizedBox(height: 20), + _buildImageSection(), + const SizedBox(height: 30), + _buildLabel("Judul Edukasi"), + _buildTextField( + _judulController, "Contoh: Perawatan ibu hamil", 1), + const SizedBox(height: 25), + _buildLabel("Deskripsi (Gunakan Enter untuk baris baru)"), + // Field deskripsi yang mendukung ENTER + _buildTextField(_deskripsiController, + "Tulis isi edukasi di sini...", 10), + const SizedBox(height: 35), + _buildSubmitButton(), + ], + ), + ), + ), + ), + ), + ), + ), + ); + } + + // Widget TextField Universal (bisa satu baris atau banyak baris) + Widget _buildTextField( + TextEditingController controller, String hint, int maxLines) { + return TextFormField( + controller: controller, + maxLines: maxLines, // Jika > 1, maka fungsi ENTER aktif secara otomatis + keyboardType: maxLines > 1 ? TextInputType.multiline : TextInputType.text, + style: GoogleFonts.poppins(fontSize: 14), + decoration: InputDecoration( + hintText: hint, + filled: true, + fillColor: Colors.white, + contentPadding: + const EdgeInsets.symmetric(horizontal: 15, vertical: 12), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: BorderSide(color: Colors.grey.shade300), + ), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: BorderSide(color: Colors.grey.shade300), + ), + ), + validator: (value) => + value == null || value.isEmpty ? "Wajib diisi" : null, + ); + } + + // ... (Widget _buildImageSection, _buildSubmitButton, _buildLabel tetap sama) + // [Kode _buildImageSection dll disingkat karena sama dengan aslinya] + + Widget _buildImageSection() { + return Center( + child: Column( + children: [ + _buildLabel("Gambar Edukasi"), + InkWell( + onTap: pickImage, + child: Container( + height: 200, + width: 350, + decoration: BoxDecoration( + color: Colors.grey[50], + borderRadius: BorderRadius.circular(10), + border: Border.all(color: Colors.grey.shade300), + ), + child: selectedImage != null || webImage != null + ? ClipRRect( + borderRadius: BorderRadius.circular(10), + child: kIsWeb + ? Image.memory(webImage!, fit: BoxFit.cover) + : Image.file(selectedImage!, fit: BoxFit.cover), + ) + : Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Icon(Icons.add_a_photo, + size: 40, color: Colors.blue), + const SizedBox(height: 8), + Text( + "Klik untuk pilih gambar", + style: GoogleFonts.poppins( + fontSize: 12, color: Colors.grey), + ), + ], + ), + ), + ), + ], + ), + ); + } + + Widget _buildSubmitButton() { + return SizedBox( + width: double.infinity, + height: 50, + child: ElevatedButton( + onPressed: isSubmitting ? null : _simpanData, + style: ElevatedButton.styleFrom( + backgroundColor: Colors.blue, + shape: + RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)), + ), + child: isSubmitting + ? const CircularProgressIndicator(color: Colors.white) + : Text( + "Simpan Edukasi", + style: GoogleFonts.poppins( + fontWeight: FontWeight.bold, + color: Colors.white, + ), + ), + ), + ); + } + + Widget _buildLabel(String text) { + return Padding( + padding: const EdgeInsets.only(bottom: 8), + child: Text( + text, + style: GoogleFonts.poppins( + fontSize: 13, + fontWeight: FontWeight.bold, + color: Colors.black87, + ), + ), + ); + } +} diff --git a/lib/bidan/crud_imunisasi/data_imunisasi_balita.dart b/lib/bidan/crud_imunisasi/data_imunisasi_balita.dart new file mode 100644 index 0000000..981af09 --- /dev/null +++ b/lib/bidan/crud_imunisasi/data_imunisasi_balita.dart @@ -0,0 +1,361 @@ +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:http/http.dart' as http; + +class DataImunisasiBalitaPage extends StatefulWidget { + final Map? balita; + + const DataImunisasiBalitaPage({super.key, this.balita}); + + @override + State createState() => + _DataImunisasiBalitaPageState(); +} + +class _DataImunisasiBalitaPageState extends State { + List riwayatData = []; + String _searchQuery = ""; + bool isLoading = true; + + int _currentPage = 0; + final int _rowsPerPage = 5; + + final String urlRiwayat = + "http://ta.myhost.id/E31230549/mposyandu_api/imunisasi/get_imunisasi_balita.php"; + + @override + void initState() { + super.initState(); + fetchRiwayat(); + } + + Future fetchRiwayat() async { + try { + final idBalita = widget.balita?['id']; + final url = + idBalita == null ? urlRiwayat : "$urlRiwayat?id_balita=$idBalita"; + + final response = await http.get(Uri.parse(url)); + + if (response.statusCode == 200) { + final data = jsonDecode(response.body); + + setState(() { + riwayatData = data['data'] ?? []; + isLoading = false; + }); + } + } catch (e) { + debugPrint("ERROR FETCH = $e"); + setState(() => isLoading = false); + } + } + + // Fungsi Hitung Usia + String hitungUsia(String? tanggalLahir) { + if (tanggalLahir == null || tanggalLahir.isEmpty || tanggalLahir == "-") { + return "Usia tidak diketahui"; + } + try { + DateTime lahir = DateTime.parse(tanggalLahir); + DateTime sekarang = DateTime.now(); + + int tahun = sekarang.year - lahir.year; + int bulan = sekarang.month - lahir.month; + + if (bulan < 0) { + tahun--; + bulan += 12; + } + + return "$tahun Tahun $bulan Bulan"; + } catch (e) { + return "Format tanggal salah"; + } + } + + List get _filteredData { + if (_searchQuery.isEmpty) return riwayatData; + + return riwayatData.where((item) { + final namaBalita = item['nama'].toString().toLowerCase(); + final query = _searchQuery.toLowerCase(); + return namaBalita.contains(query); + }).toList(); + } + + List get _paginatedData { + final start = _currentPage * _rowsPerPage; + final end = start + _rowsPerPage; + if (start >= _filteredData.length) return []; + return _filteredData.sublist( + start, + end > _filteredData.length ? _filteredData.length : end, + ); + } + + String formatTanggal(String tanggal) { + if (tanggal.isEmpty || tanggal == "-") return "-"; + try { + final parts = tanggal.split("-"); + if (parts.length != 3) return tanggal; + + final tahun = parts[0]; + final bulan = int.parse(parts[1]); + final hari = parts[2]; + + const namaBulan = [ + "", + "Januari", + "Februari", + "Maret", + "April", + "Mei", + "Juni", + "Juli", + "Agustus", + "September", + "Oktober", + "November", + "Desember" + ]; + + return "$hari ${namaBulan[bulan]} $tahun"; + } catch (e) { + return tanggal; + } + } + + @override + Widget build(BuildContext context) { + final totalPages = (_filteredData.length / _rowsPerPage).ceil() == 0 + ? 1 + : (_filteredData.length / _rowsPerPage).ceil(); + + return Scaffold( + backgroundColor: const Color(0xFFF5F5F5), + appBar: AppBar( + title: Text("", + style: GoogleFonts.poppins(color: Colors.white, fontSize: 16)), + backgroundColor: Colors.blue, + elevation: 0, + iconTheme: const IconThemeData(color: Colors.white), + ), + body: isLoading + ? const Center(child: CircularProgressIndicator()) + : Column( + children: [ + Expanded( + child: SingleChildScrollView( + child: Column( + children: [ + _header(), + _paginatedData.isEmpty + ? Padding( + padding: const EdgeInsets.only(top: 50), + child: Text( + "Data tidak ditemukan", + style: GoogleFonts.poppins(fontSize: 12), + ), + ) + : ListView.builder( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + padding: + const EdgeInsets.symmetric(horizontal: 16), + itemCount: _paginatedData.length, + itemBuilder: (context, index) => + _card(_paginatedData[index]), + ), + ], + ), + ), + ), + Container( + width: double.infinity, + color: Colors.white, + padding: + const EdgeInsets.symmetric(horizontal: 20, vertical: 10), + decoration: BoxDecoration( + border: Border(top: BorderSide(color: Colors.grey[200]!)), + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text("Halaman ${_currentPage + 1} dari $totalPages", + style: GoogleFonts.poppins( + fontSize: 12, fontWeight: FontWeight.w500)), + Row( + children: [ + IconButton( + icon: const Icon(Icons.chevron_left), + onPressed: _currentPage == 0 + ? null + : () => setState(() => _currentPage--), + ), + IconButton( + icon: const Icon(Icons.chevron_right), + onPressed: _currentPage >= totalPages - 1 + ? null + : () => setState(() => _currentPage++), + ), + ], + ), + ], + ), + ), + ], + ), + ); + } + + Widget _header() { + return Padding( + padding: const EdgeInsets.all(16), + child: Column( + children: [ + Text( + "Data Imunisasi Balita", + style: + GoogleFonts.poppins(fontSize: 18, fontWeight: FontWeight.bold), + ), + const SizedBox(height: 15), + TextField( + onChanged: (value) => setState(() { + _searchQuery = value; + _currentPage = 0; + }), + style: const TextStyle(fontSize: 12), + decoration: InputDecoration( + hintText: "Cari nama balita...", + hintStyle: const TextStyle(fontSize: 12), + prefixIcon: const Icon(Icons.search, size: 20), + filled: true, + fillColor: Colors.white, + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: BorderSide(color: Colors.grey[300]!), + ), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: BorderSide(color: Colors.grey[300]!), + ), + contentPadding: const EdgeInsets.symmetric(vertical: 8), + ), + ), + ], + ), + ); + } + + Widget _card(Map item) { + String alamatLengkap = + "Dusun ${item['nama_dusun'] ?? '-'}, Desa ${item['nama_desa'] ?? '-'}, ${item['alamat_detail'] ?? '-'}"; + + return Container( + margin: const EdgeInsets.only(bottom: 16), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12), + boxShadow: [ + BoxShadow(color: Colors.black.withOpacity(0.05), blurRadius: 10) + ], + ), + child: Column( + children: [ + Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 15), + decoration: const BoxDecoration( + color: Colors.blue, + borderRadius: BorderRadius.only( + topLeft: Radius.circular(12), + topRight: Radius.circular(12), + ), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + item['nama'] ?? "Nama Balita", + style: GoogleFonts.poppins( + fontSize: 13, + color: Colors.white, + fontWeight: FontWeight.bold, + ), + ), + // USIA DI BAWAH NAMA + Text( + "Usia: ${hitungUsia(item['tanggal_lahir'])}", + style: GoogleFonts.poppins( + fontSize: 11, + color: Colors.white, + fontWeight: FontWeight.w500, + ), + ), + const SizedBox(height: 4), + // NAMA ORANG TUA (WARNA PUTIH) + Text( + "Nama Orang Tua : ${item['nama_ibu'] ?? '-'}(${item['nama_suami'] ?? '-'})", + style: GoogleFonts.poppins( + fontSize: 11, + color: Colors.white, + ), + ), + // ALAMAT (WARNA PUTIH) + Text( + "Alamat : $alamatLengkap", + style: GoogleFonts.poppins( + fontSize: 11, + color: Colors.white, + fontStyle: FontStyle.normal, + ), + ), + ], + ), + ), + Padding( + padding: const EdgeInsets.all(15), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // POSISI TANGGAL DI ATAS IMUNISASI + detail("Tanggal Posyandu", + formatTanggal(item['tanggal_terakhir'] ?? "-")), + const SizedBox(height: 8), + detail("Jenis Imunisasi", item['daftar_imunisasi'] ?? "-"), + const SizedBox(height: 8), + detail("Status", item['status'] ?? "-"), + // BUTTON RIWAYAT SUDAH DIHAPUS + ], + ), + ) + ], + ), + ); + } + + Widget detail(String label, String value) { + return Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: 130, + child: Text( + label, + style: + GoogleFonts.poppins(fontSize: 12, fontWeight: FontWeight.w500), + ), + ), + Text(" : ", style: GoogleFonts.poppins(fontSize: 12)), + Expanded( + child: Text( + value, + style: GoogleFonts.poppins(fontSize: 12), + ), + ) + ], + ); + } +} diff --git a/lib/bidan/crud_imunisasi/edit_imunisasi.dart b/lib/bidan/crud_imunisasi/edit_imunisasi.dart new file mode 100644 index 0000000..8932485 --- /dev/null +++ b/lib/bidan/crud_imunisasi/edit_imunisasi.dart @@ -0,0 +1,243 @@ +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:http/http.dart' as http; + +class EditImunisasiPage extends StatefulWidget { + final Map data; // Menampung data yang dikirim dari halaman list + + const EditImunisasiPage({super.key, required this.data}); + + @override + State createState() => _EditImunisasiPageState(); +} + +class _EditImunisasiPageState extends State { + final _formKey = GlobalKey(); + + late TextEditingController _idController; + late TextEditingController _namaController; + late TextEditingController _usiaMinController; + late TextEditingController _usiaMaxController; + late TextEditingController _ketController; + + bool isSubmitting = false; + + final String urlEdit = + "http://ta.myhost.id/E31230549/mposyandu_api/imunisasi/edit_imunisasi.php"; + + @override + void initState() { + super.initState(); + // Mengisi controller dengan data yang ada + _idController = TextEditingController(text: widget.data['id'].toString()); + _namaController = + TextEditingController(text: widget.data['nama_imunisasi']); + _usiaMinController = + TextEditingController(text: widget.data['usia_min'].toString()); + _usiaMaxController = + TextEditingController(text: widget.data['usia_max'].toString()); + _ketController = + TextEditingController(text: widget.data['keterangan'] ?? ""); + } + + Future _updateData() async { + if (!_formKey.currentState!.validate()) return; + + setState(() => isSubmitting = true); + + try { + final response = await http.post( + Uri.parse(urlEdit), + body: { + "id": _idController.text, // Kirim ID sebagai kunci update + "nama_imunisasi": _namaController.text, + "usia_min": _usiaMinController.text, + "usia_max": _usiaMaxController.text, + "keterangan": _ketController.text, + }, + ); + + final data = jsonDecode(response.body); + if (data['status'] == 'success') { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(data['message']), backgroundColor: Colors.blue), + ); + Navigator.pop(context, true); // Kembali dan beri sinyal sukses + } else { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(data['message']), backgroundColor: Colors.red), + ); + } + } catch (e) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text("Terjadi kesalahan: $e"), + backgroundColor: Colors.red), + ); + } finally { + if (mounted) setState(() => isSubmitting = false); + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: const Color(0xFFF5F5F5), + appBar: AppBar( + backgroundColor: Colors.blue, + elevation: 0, + centerTitle: true, + leading: IconButton( + icon: const Icon(Icons.arrow_back, color: Colors.white), + onPressed: () => Navigator.pop(context), + ), + title: Text( + "", + style: GoogleFonts.poppins( + color: Colors.white, fontSize: 16, fontWeight: FontWeight.w600), + ), + ), + body: SingleChildScrollView( + padding: const EdgeInsets.all(16), + child: Center( + child: Container( + constraints: const BoxConstraints(maxWidth: 850), + child: Card( + elevation: 3, + color: Colors.white, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10)), + child: Padding( + padding: const EdgeInsets.all(25), + child: Form( + key: _formKey, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Center( + child: Text( + "Edit Jenis Imunisasi", + style: GoogleFonts.poppins( + fontSize: 18, fontWeight: FontWeight.bold), + ), + ), + const Divider(height: 40), + _buildLabel("Nama Imunisasi"), + _buildTextField( + _namaController, "Masukkan nama imunisasi"), + const SizedBox(height: 20), + Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildLabel("Usia Min (Bulan)"), + _buildTextField(_usiaMinController, "0", + isNumber: true), + ], + ), + ), + const SizedBox(width: 15), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildLabel("Usia Max (Bulan)"), + _buildTextField(_usiaMaxController, "12", + isNumber: true), + ], + ), + ), + ], + ), + const SizedBox(height: 20), + _buildLabel("Keterangan"), + _buildTextField(_ketController, "Keterangan tambahan...", + maxLines: 3), + const SizedBox(height: 35), + Row( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + ElevatedButton( + onPressed: isSubmitting ? null : _updateData, + style: ElevatedButton.styleFrom( + backgroundColor: + Colors.blue, // Warna orange untuk edit + padding: const EdgeInsets.symmetric( + horizontal: 35, vertical: 12), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(8)), + ), + child: isSubmitting + ? const SizedBox( + width: 16, + height: 16, + child: CircularProgressIndicator( + color: Colors.white, strokeWidth: 2)) + : Text( + "Simpan Perubahan", + style: GoogleFonts.poppins( + fontSize: 12, + color: Colors.white, + fontWeight: FontWeight.bold), + ), + ), + ], + ), + ], + ), + ), + ), + ), + ), + ), + ), + ); + } + + Widget _buildLabel(String label) { + return Padding( + padding: const EdgeInsets.only(bottom: 8), + child: Text( + label, + style: GoogleFonts.poppins( + fontSize: 12, fontWeight: FontWeight.w600, color: Colors.black87), + ), + ); + } + + Widget _buildTextField(TextEditingController controller, String hint, + {bool isNumber = false, int maxLines = 1}) { + return TextFormField( + controller: controller, + keyboardType: isNumber ? TextInputType.number : TextInputType.text, + maxLines: maxLines, + style: const TextStyle(fontSize: 12), + decoration: InputDecoration( + hintText: hint, + hintStyle: TextStyle(fontSize: 11, color: Colors.grey[400]), + filled: true, + fillColor: Colors.grey[50], + contentPadding: + const EdgeInsets.symmetric(vertical: 12, horizontal: 15), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: BorderSide(color: Colors.grey[300]!), + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: const BorderSide(color: Colors.blue, width: 1.5), + ), + errorStyle: const TextStyle(fontSize: 10), + ), + validator: (value) => + value == null || value.isEmpty ? "Wajib diisi" : null, + ); + } +} diff --git a/lib/bidan/crud_imunisasi/riwayat_detail_imunisasi_balita.dart b/lib/bidan/crud_imunisasi/riwayat_detail_imunisasi_balita.dart new file mode 100644 index 0000000..b034050 --- /dev/null +++ b/lib/bidan/crud_imunisasi/riwayat_detail_imunisasi_balita.dart @@ -0,0 +1,305 @@ +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:http/http.dart' as http; + +class RiwayatDetailBalitaPage extends StatefulWidget { + final Map balita; + final String jenisImunisasi; + + const RiwayatDetailBalitaPage({ + super.key, + required this.balita, + required this.jenisImunisasi, + }); + + @override + State createState() => + _RiwayatDetailBalitaPageState(); +} + +class _RiwayatDetailBalitaPageState extends State { + List listRiwayat = []; + String _query = ""; + bool isLoading = true; + + int _currentPage = 0; + final int _rowsPerPage = 5; + + @override + void initState() { + super.initState(); + fetchDetailRiwayat(); + } + + String formatTanggal(String tanggal) { + if (tanggal.isEmpty || tanggal == "-") return "-"; + try { + final parts = tanggal.split("-"); + if (parts.length != 3) return tanggal; + + final tahun = parts[0]; + final bulan = int.parse(parts[1]); + final hari = parts[2]; + + const namaBulan = [ + "", "Januari", "Februari", "Maret", "April", "Mei", "Juni", + "Juli", "Agustus", "September", "Oktober", "November", "Desember" + ]; + + return "$hari ${namaBulan[bulan]} $tahun"; + } catch (e) { + return tanggal; + } + } + + Future fetchDetailRiwayat() async { + final String url = + "http://ta.myhost.id/E31230549/mposyandu_api/imunisasi/get_riwayat_detail.php?id_balita=${widget.balita['id']}"; + + try { + final response = await http.get(Uri.parse(url)); + if (response.statusCode == 200) { + final data = jsonDecode(response.body); + if (mounted) { + setState(() { + listRiwayat = data['data'] ?? []; + isLoading = false; + }); + } + } + } catch (e) { + debugPrint("ERROR FETCHING DETAIL: $e"); + if (mounted) { + setState(() => isLoading = false); + } + } + } + + List get _filteredList { + if (_query.isEmpty) return listRiwayat; + return listRiwayat.where((item) { + // Filter berdasarkan daftar imunisasi yang sudah digabung + final nama = item['daftar_imunisasi']?.toString().toLowerCase() ?? ""; + return nama.contains(_query.toLowerCase()); + }).toList(); + } + + List get _paginatedData { + final start = _currentPage * _rowsPerPage; + final end = start + _rowsPerPage; + if (start >= _filteredList.length) return []; + return _filteredList.sublist( + start, + end > _filteredList.length ? _filteredList.length : end, + ); + } + + @override + Widget build(BuildContext context) { + final totalPages = (_filteredList.length / _rowsPerPage).ceil() == 0 + ? 1 + : (_filteredList.length / _rowsPerPage).ceil(); + + return Scaffold( + backgroundColor: const Color(0xFFF5F5F5), + appBar: AppBar( + backgroundColor: Colors.blue, + elevation: 0, + leading: IconButton( + icon: const Icon(Icons.arrow_back, color: Colors.white, size: 18), + onPressed: () => Navigator.pop(context), + ), + ), + body: isLoading + ? const Center(child: CircularProgressIndicator()) + : Column( + children: [ + Expanded( + child: SingleChildScrollView( + child: Column( + children: [ + _buildSearchHeader(), + _paginatedData.isEmpty + ? Padding( + padding: const EdgeInsets.only(top: 50), + child: Text( + "Data tidak ditemukan", + style: GoogleFonts.poppins(fontSize: 12), + ), + ) + : ListView.builder( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + padding: + const EdgeInsets.symmetric(horizontal: 16), + itemCount: _paginatedData.length, + itemBuilder: (context, index) => + _buildHistoryCard(_paginatedData[index]), + ), + ], + ), + ), + ), + _buildPagination(totalPages), + ], + ), + ); + } + + Widget _buildSearchHeader() { + return Padding( + padding: const EdgeInsets.all(16.0), + child: Column( + children: [ + Center( + child: Text( + "Riwayat Detail Balita", + style: GoogleFonts.poppins( + fontSize: 18, fontWeight: FontWeight.bold), + ), + ), + const SizedBox(height: 15), + TextField( + onChanged: (v) => setState(() { + _query = v; + _currentPage = 0; + }), + style: const TextStyle(fontSize: 12), + decoration: InputDecoration( + hintText: "Cari jenis imunisasi...", + hintStyle: const TextStyle(fontSize: 12), + prefixIcon: const Icon(Icons.search, size: 20), + filled: true, + fillColor: Colors.white, + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: BorderSide(color: Colors.grey[300]!), + ), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: BorderSide(color: Colors.grey[300]!), + ), + contentPadding: const EdgeInsets.symmetric(vertical: 8), + ), + ), + ], + ), + ); + } + + Widget _buildHistoryCard(Map item) { + return Container( + margin: const EdgeInsets.only(bottom: 15), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.05), + blurRadius: 10, + offset: const Offset(0, 5), + ) + ], + ), + child: Column( + children: [ + Container( + padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 15), + width: double.infinity, + decoration: const BoxDecoration( + color: Colors.blue, + borderRadius: BorderRadius.only( + topLeft: Radius.circular(12), + topRight: Radius.circular(12), + ), + ), + child: Text( + widget.balita['nama_balita'] ?? "Nama Balita", + style: GoogleFonts.poppins( + color: Colors.white, + fontWeight: FontWeight.bold, + fontSize: 13, + ), + ), + ), + Padding( + padding: const EdgeInsets.all(15), + child: Column( + children: [ + // Menggunakan 'daftar_imunisasi' yang berisi string gabungan (HB0, BCG, dll) + _buildInfoRow("Jenis Imunisasi", + item['daftar_imunisasi']?.toString() ?? "-"), + const SizedBox(height: 8), + _buildInfoRow( + "Tanggal Posyandu", + formatTanggal( + item['tanggal_pemberian']?.toString() ?? "-")), + const SizedBox(height: 8), + _buildInfoRow("Status", item['status']?.toString() ?? "-"), + ], + ), + ) + ], + ), + ); + } + + Widget _buildInfoRow(String label, String value) { + return Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: 130, + child: Text( + label, + style: + GoogleFonts.poppins(fontSize: 12, fontWeight: FontWeight.w500), + ), + ), + Text(" : ", style: GoogleFonts.poppins(fontSize: 12)), + Expanded( + child: Text( + value, + style: GoogleFonts.poppins(fontSize: 12), + ), + ), + ], + ); + } + + Widget _buildPagination(int totalPages) { + return Container( + width: double.infinity, + color: Colors.white, + padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10), + decoration: BoxDecoration( + border: Border(top: BorderSide(color: Colors.grey[200]!)), + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text("Halaman ${_currentPage + 1} dari $totalPages", + style: GoogleFonts.poppins( + fontSize: 12, fontWeight: FontWeight.w500)), + Row( + children: [ + IconButton( + icon: const Icon(Icons.chevron_left), + onPressed: _currentPage == 0 + ? null + : () => setState(() => _currentPage--), + ), + IconButton( + icon: const Icon(Icons.chevron_right), + onPressed: _currentPage >= totalPages - 1 + ? null + : () => setState(() => _currentPage++), + ), + ], + ), + ], + ), + ); + } +} \ No newline at end of file diff --git a/lib/bidan/crud_imunisasi/tambah_imunisasi.dart b/lib/bidan/crud_imunisasi/tambah_imunisasi.dart new file mode 100644 index 0000000..2864ec0 --- /dev/null +++ b/lib/bidan/crud_imunisasi/tambah_imunisasi.dart @@ -0,0 +1,224 @@ +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:http/http.dart' as http; + +class TambahImunisasiPage extends StatefulWidget { + const TambahImunisasiPage({super.key}); + + @override + State createState() => _TambahImunisasiPageState(); +} + +class _TambahImunisasiPageState extends State { + final _formKey = GlobalKey(); + + final TextEditingController _namaController = TextEditingController(); + final TextEditingController _usiaMinController = TextEditingController(); + final TextEditingController _usiaMaxController = TextEditingController(); + final TextEditingController _ketController = TextEditingController(); + + bool isSubmitting = false; + + final String urlTambah = + "http://ta.myhost.id/E31230549/mposyandu_api/imunisasi/tambah_imunisasi.php"; + + Future _simpanData() async { + if (!_formKey.currentState!.validate()) return; + + setState(() => isSubmitting = true); + + try { + final response = await http.post( + Uri.parse(urlTambah), + body: { + "nama_imunisasi": _namaController.text, + "usia_min": _usiaMinController.text, + "usia_max": _usiaMaxController.text, + "keterangan": _ketController.text, + }, + ); + + final data = jsonDecode(response.body); + if (data['status'] == 'success') { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text("Data berhasil disimpan!")), + ); + Navigator.pop(context); + } + } catch (e) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text("Terjadi kesalahan: $e")), + ); + } finally { + if (mounted) setState(() => isSubmitting = false); + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: const Color(0xFFF5F5F5), + appBar: AppBar( + backgroundColor: Colors.blue, + elevation: 0, + centerTitle: true, + leading: IconButton( + icon: const Icon(Icons.arrow_back, color: Colors.white), + onPressed: () => Navigator.pop(context), + ), + title: Text( + "", + style: GoogleFonts.poppins( + color: Colors.white, fontSize: 16, fontWeight: FontWeight.w600), + ), + ), + body: SingleChildScrollView( + padding: const EdgeInsets.all(16), + child: Center( + child: Container( + constraints: const BoxConstraints(maxWidth: 850), + child: Card( + elevation: 3, + color: Colors.white, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10)), + child: Padding( + padding: const EdgeInsets.all(25), + child: Form( + key: _formKey, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // --- JUDUL --- + Center( + child: Text( + "Tambah Jenis Imunisasi", + style: GoogleFonts.poppins( + fontSize: 18, fontWeight: FontWeight.bold), + ), + ), + const Divider(height: 40), + + _buildLabel("Nama Imunisasi"), + _buildTextField( + _namaController, "Masukkan nama imunisasi"), + + const SizedBox(height: 20), + Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildLabel("Usia Min (Bulan)"), + _buildTextField(_usiaMinController, "0", + isNumber: true), + ], + ), + ), + const SizedBox(width: 15), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildLabel("Usia Max (Bulan)"), + _buildTextField(_usiaMaxController, "12", + isNumber: true), + ], + ), + ), + ], + ), + + const SizedBox(height: 20), + _buildLabel("Keterangan"), + _buildTextField(_ketController, + "Contoh: Diberikan pada bayi baru lahir", + maxLines: 3), + + const SizedBox(height: 35), + + // --- TOMBOL SIMPAN (OUTLINED STADIUM - TANPA IKON) --- + Row( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + SizedBox( + width: 150, // Menentukan lebar agar proporsional + child: OutlinedButton( + onPressed: isSubmitting ? null : _simpanData, + style: OutlinedButton.styleFrom( + side: const BorderSide(color: Colors.blue, width: 1.5), + shape: const StadiumBorder(), + padding: const EdgeInsets.symmetric(vertical: 12), + ), + child: isSubmitting + ? const SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator( + color: Colors.blue, strokeWidth: 2)) + : Text( + "Simpan", + style: GoogleFonts.poppins( + fontSize: 12, + color: Colors.blue, + fontWeight: FontWeight.bold), + ), + ), + ), + ], + ), + ], + ), + ), + ), + ), + ), + ), + ), + ); + } + + Widget _buildLabel(String label) { + return Padding( + padding: const EdgeInsets.only(bottom: 8), + child: Text( + label, + style: GoogleFonts.poppins( + fontSize: 12, fontWeight: FontWeight.w600, color: Colors.black87), + ), + ); + } + + Widget _buildTextField(TextEditingController controller, String hint, + {bool isNumber = false, int maxLines = 1}) { + return TextFormField( + controller: controller, + keyboardType: isNumber ? TextInputType.number : TextInputType.text, + maxLines: maxLines, + style: const TextStyle(fontSize: 12), + decoration: InputDecoration( + hintText: hint, + hintStyle: TextStyle(fontSize: 11, color: Colors.grey[400]), + filled: true, + fillColor: Colors.grey[50], + contentPadding: + const EdgeInsets.symmetric(vertical: 12, horizontal: 15), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: BorderSide(color: Colors.grey[300]!), + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: const BorderSide(color: Colors.blue, width: 1.5), + ), + errorStyle: const TextStyle(fontSize: 10), + ), + validator: (value) => + value == null || value.isEmpty ? "Wajib diisi" : null, + ); + } +} \ No newline at end of file diff --git a/lib/bidan/crud_jadwal/edit_jadwal.dart b/lib/bidan/crud_jadwal/edit_jadwal.dart new file mode 100644 index 0000000..4930e6c --- /dev/null +++ b/lib/bidan/crud_jadwal/edit_jadwal.dart @@ -0,0 +1,417 @@ +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:http/http.dart' as http; + +const String baseUrl = "http://ta.myhost.id/E31230549/mposyandu_api"; + +class Kader { + final int id; + final String nama; + final int dusunId; + + Kader({ + required this.id, + required this.nama, + required this.dusunId, + }); +} + +class EditJadwalPage extends StatefulWidget { + final Map data; + + const EditJadwalPage({ + super.key, + required this.data, + }); + + @override + State createState() => _EditJadwalPageState(); +} + +class _EditJadwalPageState extends State { + late TextEditingController _tanggalController; + late TextEditingController _jamMulaiController; + late TextEditingController _jamSelesaiController; + late TextEditingController _lokasiController; + late TextEditingController _keteranganController; + + List daftarDusun = []; + List daftarKader = []; + List dusunDipilih = []; + String dusunTeksAwal = ""; + + bool _isLoading = false; + + @override + void initState() { + super.initState(); + + _tanggalController = + TextEditingController(text: widget.data['tanggal']?.toString() ?? ""); + _jamMulaiController = + TextEditingController(text: widget.data['jam_mulai']?.toString() ?? ""); + _jamSelesaiController = TextEditingController( + text: widget.data['jam_selesai']?.toString() ?? ""); + _lokasiController = + TextEditingController(text: widget.data['lokasi']?.toString() ?? ""); + _keteranganController = TextEditingController( + text: widget.data['keterangan']?.toString() ?? ""); + + dusunTeksAwal = widget.data['dusun']?.toString() ?? "-"; + + _parseInitialDusun(); + + WidgetsBinding.instance.addPostFrameCallback((_) { + _initialLoad(); + }); + } + + void _parseInitialDusun() { + try { + var rawDusunIds = widget.data['dusun_ids']; + if (rawDusunIds != null && rawDusunIds.toString().isNotEmpty) { + dusunDipilih = rawDusunIds + .toString() + .split(',') + .map((e) => int.tryParse(e.trim()) ?? 0) + .where((e) => e > 0) + .toList(); + } + } catch (e) { + debugPrint("Error parsing dusun: $e"); + } + } + + Future _initialLoad() async { + await loadDusun(); + if (dusunDipilih.isNotEmpty) { + await loadKaderByDusun(); + } + } + + Future loadDusun() async { + try { + final res = await http.get(Uri.parse("$baseUrl/dusun/get_dusun.php")); + if (res.statusCode == 200) { + final responseData = jsonDecode(res.body); + setState(() { + daftarDusun = responseData['data'] ?? []; + }); + } + } catch (e) { + debugPrint("Error load dusun: $e"); + } + } + + Future loadKaderByDusun() async { + if (dusunDipilih.isEmpty) { + setState(() => daftarKader.clear()); + return; + } + String ids = dusunDipilih.join(","); + try { + final res = await http.get( + Uri.parse("$baseUrl/petugas/get_kader_by_dusun.php?ids=$ids"), + ); + if (res.statusCode == 200) { + final responseData = jsonDecode(res.body); + final List listData = responseData['data'] ?? []; + setState(() { + daftarKader = listData + .map((k) => Kader( + id: int.parse(k['id'].toString()), + nama: k['nama'].toString(), + dusunId: int.parse(k['dusun_id'].toString()), + )) + .toList(); + }); + } + } catch (e) { + debugPrint("Error load kader: $e"); + } + } + + Future _pickTanggal() async { + DateTime? picked = await showDatePicker( + context: context, + initialDate: DateTime.now(), + firstDate: DateTime(2024), + lastDate: DateTime(2030), + ); + if (picked != null) { + setState(() { + _tanggalController.text = + "${picked.year}-${picked.month.toString().padLeft(2, '0')}-${picked.day.toString().padLeft(2, '0')}"; + }); + } + } + + Future _pickJam(TextEditingController controller) async { + TimeOfDay? picked = await showTimePicker( + context: context, + initialTime: TimeOfDay.now(), + ); + if (picked != null) { + setState(() { + controller.text = + "${picked.hour.toString().padLeft(2, '0')}:${picked.minute.toString().padLeft(2, '0')}"; + }); + } + } + + Future _updateJadwal() async { + if (_tanggalController.text.isEmpty || dusunDipilih.isEmpty) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text("Data tidak boleh kosong!", + style: GoogleFonts.poppins(fontSize: 12))), + ); + return; + } + + setState(() => _isLoading = true); + try { + final response = await http.post( + Uri.parse("$baseUrl/jadwal_posyandu/edit_jadwal.php"), + body: { + "id": widget.data['id'].toString(), + "bidan_id": widget.data['bidan_id']?.toString() ?? "", + "tanggal": _tanggalController.text, + "jam_mulai": _jamMulaiController.text, + "jam_selesai": _jamSelesaiController.text, + "lokasi": _lokasiController.text, + "keterangan": _keteranganController.text, + "dusun_ids": dusunDipilih.join(","), + }, + ); + final result = jsonDecode(response.body); + if (result['success']) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text("Jadwal Berhasil Diperbarui", + style: GoogleFonts.poppins(fontSize: 12))), + ); + Navigator.pop(context, true); + } + } catch (e) { + ScaffoldMessenger.of(context).showSnackBar(SnackBar( + content: + Text("Error: $e", style: GoogleFonts.poppins(fontSize: 12)))); + } + setState(() => _isLoading = false); + } + + InputDecoration _input(String label) { + return InputDecoration( + labelText: label, + labelStyle: GoogleFonts.poppins(fontSize: 12), + border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)), + contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + ); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: Text("", + style: GoogleFonts.poppins( + color: Colors.white, + fontSize: 16, + fontWeight: FontWeight.w600)), + backgroundColor: Colors.blue, + iconTheme: const IconThemeData(color: Colors.white), + leading: IconButton( + icon: const Icon(Icons.arrow_back), + onPressed: () => Navigator.pop(context), + ), + ), + body: SingleChildScrollView( + padding: const EdgeInsets.all(16), + child: Center( + child: Container( + constraints: const BoxConstraints(maxWidth: 500), + padding: const EdgeInsets.all(20), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + boxShadow: const [ + BoxShadow(color: Colors.black12, blurRadius: 8) + ], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Center( + child: Text("Edit Data Jadwal", + style: GoogleFonts.poppins( + fontSize: 16, fontWeight: FontWeight.bold))), + const SizedBox(height: 15), + TextField( + controller: _tanggalController, + style: GoogleFonts.poppins(fontSize: 12), + readOnly: true, + onTap: _pickTanggal, + decoration: _input("Tanggal").copyWith( + suffixIcon: const Icon(Icons.calendar_today, size: 18), + ), + ), + const SizedBox(height: 10), + Row( + children: [ + Expanded( + child: TextField( + controller: _jamMulaiController, + style: GoogleFonts.poppins(fontSize: 12), + readOnly: true, + onTap: () => _pickJam(_jamMulaiController), + decoration: _input("Jam Mulai").copyWith( + suffixIcon: const Icon(Icons.access_time, size: 18), + ), + ), + ), + const SizedBox(width: 8), + Expanded( + child: TextField( + controller: _jamSelesaiController, + style: GoogleFonts.poppins(fontSize: 12), + readOnly: true, + onTap: () => _pickJam(_jamSelesaiController), + decoration: _input("Jam Selesai").copyWith( + suffixIcon: const Icon(Icons.access_time, size: 18), + ), + ), + ), + ], + ), + const SizedBox(height: 10), + TextField( + controller: _lokasiController, + style: GoogleFonts.poppins(fontSize: 12), + decoration: _input("Lokasi Posyandu")), + const SizedBox(height: 15), + Text("Dusun Yang Dilayani", + style: GoogleFonts.poppins( + fontWeight: FontWeight.w600, fontSize: 12)), + + Container( + width: double.infinity, + margin: const EdgeInsets.only(top: 5, bottom: 10), + padding: const EdgeInsets.all(10), + decoration: BoxDecoration( + color: Colors.blue.shade50, + borderRadius: BorderRadius.circular(8), + border: Border.all(color: Colors.blue.shade100), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text("Dusun sebelumnya:", + style: GoogleFonts.poppins( + fontSize: 11, + fontWeight: FontWeight.bold, + color: Colors.blue)), + Text(dusunTeksAwal, + style: GoogleFonts.poppins( + fontSize: 12, color: Colors.black87)), + const SizedBox(height: 4), + Text( + "*Silakan centang ulang di bawah jika ingin merubah pilihan dusun.", + style: GoogleFonts.poppins( + fontSize: 10, + fontStyle: FontStyle.italic, + color: Colors.grey)), + ], + ), + ), + + const Divider(), + daftarDusun.isEmpty + ? Center( + child: Text("Memuat daftar dusun...", + style: GoogleFonts.poppins( + fontSize: 12, color: Colors.grey))) + : Column( + children: daftarDusun.map((d) { + int id = int.parse(d['id'].toString()); + return CheckboxListTile( + visualDensity: VisualDensity.compact, + contentPadding: EdgeInsets.zero, + title: Text(d['nama_dusun'] ?? "", + style: GoogleFonts.poppins(fontSize: 12)), + value: dusunDipilih.contains(id), + onChanged: (val) { + setState(() { + if (val == true) { + if (!dusunDipilih.contains(id)) + dusunDipilih.add(id); + } else { + dusunDipilih.remove(id); + } + }); + loadKaderByDusun(); + }, + ); + }).toList(), + ), + + const SizedBox(height: 10), + Text("Kader Otomatis:", + style: GoogleFonts.poppins( + fontWeight: FontWeight.w600, fontSize: 12)), + const SizedBox(height: 5), + daftarKader.isEmpty + ? Text("-", + style: GoogleFonts.poppins( + color: Colors.grey, fontSize: 12)) + : Wrap( + spacing: 5, + children: daftarKader + .map((k) => Chip( + label: Text(k.nama, + style: GoogleFonts.poppins(fontSize: 12)), + padding: EdgeInsets.zero, + backgroundColor: Colors.blue.shade50, + )) + .toList(), + ), + const SizedBox(height: 15), + TextField( + controller: _keteranganController, + style: GoogleFonts.poppins(fontSize: 12), + decoration: _input("Keterangan")), + const SizedBox(height: 25), + + // --- TOMBOL SIMPAN PERUBAHAN (OUTLINED STADIUM) --- + SizedBox( + width: double.infinity, + child: OutlinedButton( + onPressed: _isLoading ? null : _updateJadwal, + style: OutlinedButton.styleFrom( + side: const BorderSide(color: Colors.blue), + shape: const StadiumBorder(), + padding: const EdgeInsets.symmetric(vertical: 14)), + child: _isLoading + ? const SizedBox( + height: 20, + width: 20, + child: CircularProgressIndicator( + color: Colors.blue, strokeWidth: 2)) + : Text( + "Simpan Perubahan", + style: GoogleFonts.poppins( + color: Colors.blue, + fontWeight: FontWeight.bold, + fontSize: 12), + ), + ), + ), + ], + ), + ), + ), + ), + ); + } +} diff --git a/lib/bidan/crud_jadwal/riwayat_jadwal_posyandu.dart b/lib/bidan/crud_jadwal/riwayat_jadwal_posyandu.dart new file mode 100644 index 0000000..3bb317a --- /dev/null +++ b/lib/bidan/crud_jadwal/riwayat_jadwal_posyandu.dart @@ -0,0 +1,342 @@ +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:http/http.dart' as http; + +const String baseUrl = "http://ta.myhost.id/E31230549/mposyandu_api"; + +class RiwayatJadwalPosyanduPage extends StatefulWidget { + const RiwayatJadwalPosyanduPage({super.key}); + + @override + State createState() => + _RiwayatJadwalPosyanduPageState(); +} + +class _RiwayatJadwalPosyanduPageState extends State { + List> dataRiwayat = []; + List> dataFilter = []; + bool isLoading = true; + final TextEditingController searchController = TextEditingController(); + + int _currentPage = 0; + final int _rowsPerPage = 5; + + List> get _paginatedData { + if (dataFilter.isEmpty) return []; + final start = _currentPage * _rowsPerPage; + final end = start + _rowsPerPage; + if (start >= dataFilter.length) return []; + return dataFilter.sublist( + start, end > dataFilter.length ? dataFilter.length : end); + } + + @override + void initState() { + super.initState(); + loadRiwayat(); + } + + Future loadRiwayat() async { + try { + final res = await http.get( + Uri.parse("$baseUrl/jadwal_posyandu/get_all_jadwal.php"), + ); + final data = jsonDecode(res.body); + if (data['success']) { + setState(() { + dataRiwayat = List>.from(data['data']); + dataFilter = dataRiwayat; + isLoading = false; + }); + } + } catch (e) { + debugPrint("Error riwayat : $e"); + setState(() => isLoading = false); + } + } + + String formatTanggal(String tanggal) { + try { + final parts = tanggal.split("-"); + String tahun = parts[0]; + int bulan = int.parse(parts[1]); + String hari = parts[2]; + List namaBulan = [ + "", + "Januari", + "Februari", + "Maret", + "April", + "Mei", + "Juni", + "Juli", + "Agustus", + "September", + "Oktober", + "November", + "Desember" + ]; + return "$hari ${namaBulan[bulan]} $tahun"; + } catch (e) { + return tanggal; + } + } + + void searchData(String keyword) { + final key = keyword.toLowerCase(); + setState(() { + dataFilter = dataRiwayat.where((item) { + return item['tanggal'].toString().toLowerCase().contains(key) || + item['lokasi'].toString().toLowerCase().contains(key) || + item['dusun'].toString().toLowerCase().contains(key); + }).toList(); + _currentPage = 0; + }); + } + + Future hapusJadwal(String id) async { + final res = await http.post( + Uri.parse("$baseUrl/jadwal_posyandu/hapus_jadwal_posyandu.php"), + body: {"id": id}, + ); + final data = jsonDecode(res.body); + if (data['success']) { + loadRiwayat(); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text("Jadwal berhasil dihapus", + style: GoogleFonts.poppins(fontSize: 12))), + ); + } + } + + void konfirmasiHapus(String id) { + showDialog( + context: context, + builder: (_) => AlertDialog( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)), + title: Text("Hapus Jadwal", + style: + GoogleFonts.poppins(fontWeight: FontWeight.bold, fontSize: 14)), + content: Text("Apakah yakin ingin menghapus jadwal ini?", + style: GoogleFonts.poppins(fontSize: 12)), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text("Batal", style: TextStyle(fontSize: 12))), + + // Button Hapus di Dialog juga disesuaikan + OutlinedButton( + style: OutlinedButton.styleFrom( + side: const BorderSide(color: Colors.redAccent), + shape: const StadiumBorder(), + ), + onPressed: () { + Navigator.pop(context); + hapusJadwal(id); + }, + child: const Text("Hapus", + style: TextStyle( + color: Colors.redAccent, + fontSize: 12, + fontWeight: FontWeight.bold)), + ) + ], + ), + ); + } + + Widget rowData(String label, String value) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 2), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: 70, + child: Text(label, + style: GoogleFonts.poppins( + fontSize: 12, fontWeight: FontWeight.w600)), + ), + Text(" : ", style: GoogleFonts.poppins(fontSize: 12)), + Expanded( + child: Text(value, + style: GoogleFonts.poppins(fontSize: 12), softWrap: true), + ) + ], + ), + ); + } + + Widget cardJadwal(Map item) { + return Center( + child: Container( + margin: const EdgeInsets.symmetric(horizontal: 25, vertical: 8), + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12), + border: Border.all(color: Colors.grey.shade300), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.03), + blurRadius: 5, + offset: const Offset(0, 2)), + ], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + const Icon(Icons.event_note, + size: 16, color: Colors.blueAccent), + const SizedBox(width: 6), + Text("Data Jadwal Posyandu", + style: GoogleFonts.poppins( + fontWeight: FontWeight.bold, fontSize: 13)), + ], + ), + const Divider(height: 16, thickness: 1), + rowData("Tanggal", formatTanggal(item['tanggal'] ?? "-")), + rowData("Jam", "${item['jam_mulai']} - ${item['jam_selesai']}"), + rowData("Lokasi", item['lokasi'] ?? "-"), + rowData("Dusun", item['dusun'] ?? "-"), + rowData("Kader", item['kader'] ?? "-"), + rowData("Ket", item['keterangan'] ?? "-"), + const SizedBox(height: 8), + Align( + alignment: Alignment.centerRight, + child: SizedBox( + height: 32, // Sedikit disesuaikan untuk Outlined Style + + // MENGUBAH GAYA BUTTON HAPUS DI SINI + child: OutlinedButton.icon( + onPressed: () => konfirmasiHapus(item['id'].toString()), + icon: const Icon(Icons.delete_outline, + size: 14, color: Colors.redAccent), + label: Text("Hapus", + style: GoogleFonts.poppins( + color: Colors.redAccent, + fontSize: 10, + fontWeight: FontWeight.bold)), + style: OutlinedButton.styleFrom( + side: const BorderSide(color: Colors.redAccent), + padding: const EdgeInsets.symmetric(horizontal: 12), + shape: const StadiumBorder(), // Membuat bentuk lonjong + ), + ), + ), + ) + ], + ), + ), + ); + } + + @override + Widget build(BuildContext context) { + final totalPages = + dataFilter.isEmpty ? 1 : (dataFilter.length / _rowsPerPage).ceil(); + + return Scaffold( + backgroundColor: const Color(0xFFFDFDFD), + appBar: AppBar( + backgroundColor: Colors.blueAccent, + elevation: 0, + leading: IconButton( + icon: const Icon(Icons.arrow_back, color: Colors.white), + onPressed: () => Navigator.pop(context), + ), + title: null, + ), + body: Column( + children: [ + Padding( + padding: const EdgeInsets.only(top: 20, bottom: 12), + child: Center( + child: Text( + "Riwayat Jadwal Posyandu", + style: GoogleFonts.poppins( + fontSize: 18, + fontWeight: FontWeight.bold, + color: Colors.black, + ), + ), + ), + ), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 20), + child: TextField( + controller: searchController, + onChanged: searchData, + style: GoogleFonts.poppins(fontSize: 12), + decoration: InputDecoration( + hintText: "Cari berdasarkan tanggal, lokasi, a...", + hintStyle: + GoogleFonts.poppins(fontSize: 12, color: Colors.grey), + prefixIcon: + const Icon(Icons.search, size: 20, color: Colors.grey), + contentPadding: const EdgeInsets.symmetric(vertical: 10), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: const BorderSide(color: Colors.grey), + ), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: const BorderSide(color: Colors.grey), + ), + ), + ), + ), + const SizedBox(height: 15), + Expanded( + child: isLoading + ? const Center(child: CircularProgressIndicator()) + : dataFilter.isEmpty + ? Center( + child: Text("Data tidak ditemukan", + style: GoogleFonts.poppins(fontSize: 12))) + : ListView.builder( + itemCount: _paginatedData.length, + itemBuilder: (context, index) { + return cardJadwal(_paginatedData[index]); + }, + ), + ), + Container( + padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 8), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + "Halaman ${_currentPage + 1} dari $totalPages", + style: GoogleFonts.poppins(fontSize: 12, color: Colors.black), + ), + Row( + children: [ + IconButton( + iconSize: 20, + icon: const Icon(Icons.chevron_left), + onPressed: _currentPage == 0 + ? null + : () => setState(() => _currentPage--), + ), + IconButton( + iconSize: 20, + icon: const Icon(Icons.chevron_right), + onPressed: _currentPage >= totalPages - 1 + ? null + : () => setState(() => _currentPage++), + ), + ], + ) + ], + ), + ) + ], + ), + ); + } +} diff --git a/lib/bidan/crud_kehamilan/edit_pemeriksaan_kehamilan.dart b/lib/bidan/crud_kehamilan/edit_pemeriksaan_kehamilan.dart new file mode 100644 index 0000000..09aeeae --- /dev/null +++ b/lib/bidan/crud_kehamilan/edit_pemeriksaan_kehamilan.dart @@ -0,0 +1,384 @@ +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:http/http.dart' as http; +import 'package:intl/intl.dart'; + +class EditPemeriksaanKehamilanPage extends StatefulWidget { + final Map data; + final String nama; + + const EditPemeriksaanKehamilanPage({ + super.key, + required this.data, + required this.nama, + }); + + @override + State createState() => + _EditPemeriksaanKehamilanPageState(); +} + +class _EditPemeriksaanKehamilanPageState + extends State { + final tanggalController = TextEditingController(); + final displayTanggalController = TextEditingController(); + + final bbSebelumController = TextEditingController(); + final beratController = TextEditingController(); + final tinggiController = TextEditingController(); + final lilaController = TextEditingController(); + final tekananController = TextEditingController(); + final fundusController = TextEditingController(); + final djjController = TextEditingController(); + final hbController = TextEditingController(); + final keluhanController = TextEditingController(); + final tindakanController = TextEditingController(); + + String? kakiBengkak; + String? statusGizi; + + final String url = + "http://ta.myhost.id/E31230549/mposyandu_api/pemeriksaan_kehamilan/edit_pemeriksaan_kehamilan.php"; + + @override + void initState() { + super.initState(); + + tanggalController.text = widget.data["tanggal_pemeriksaan"] ?? ""; + + DateTime date = DateTime.parse( + widget.data["tanggal_pemeriksaan"] ?? DateTime.now().toString()); + + displayTanggalController.text = formatKeIndonesia(date); + + bbSebelumController.text = widget.data["bb_sebelum_hamil"] ?? ""; + beratController.text = widget.data["berat_badan"] ?? ""; + tinggiController.text = widget.data["tinggi_badan"] ?? ""; + lilaController.text = widget.data["LILA"] ?? ""; + tekananController.text = widget.data["tekanan_darah"] ?? ""; + fundusController.text = widget.data["tinggi_fundus"] ?? ""; + djjController.text = widget.data["denyut_jantung_janin"] ?? ""; + hbController.text = widget.data["hb"] ?? ""; + keluhanController.text = widget.data["keluhan"] ?? ""; + tindakanController.text = widget.data["tindakan"] ?? ""; + + kakiBengkak = widget.data["kaki_bengkak"]; + statusGizi = widget.data["status_gizi"]; + } + + String formatKeIndonesia(DateTime date) { + List bulan = [ + "Januari", + "Februari", + "Maret", + "April", + "Mei", + "Juni", + "Juli", + "Agustus", + "September", + "Oktober", + "November", + "Desember" + ]; + return "${date.day} ${bulan[date.month - 1]} ${date.year}"; + } + + Future pilihTanggal() async { + final DateTime? picked = await showDatePicker( + context: context, + initialDate: DateTime.parse(tanggalController.text), + firstDate: DateTime(2000), + lastDate: DateTime(2100), + ); + + if (picked != null) { + setState(() { + tanggalController.text = DateFormat('yyyy-MM-dd').format(picked); + displayTanggalController.text = formatKeIndonesia(picked); + }); + } + } + + Future updateData() async { + try { + final response = await http.post( + Uri.parse(url), + body: { + "id": widget.data["id"].toString(), + "tanggal_pemeriksaan": tanggalController.text, + "bb_sebelum_hamil": bbSebelumController.text, + "berat_badan": beratController.text, + "tinggi_badan": tinggiController.text, + "LILA": lilaController.text, + "status_gizi": statusGizi ?? "", + "tekanan_darah": tekananController.text, + "tinggi_fundus": fundusController.text, + "denyut_jantung_janin": djjController.text, + "hb": hbController.text, + "kaki_bengkak": kakiBengkak ?? "", + "keluhan": keluhanController.text, + "tindakan": tindakanController.text, + }, + ); + + final res = jsonDecode(response.body); + + if (res["success"] == true) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + backgroundColor: Colors.green, + content: Text("Data berhasil diupdate", + style: GoogleFonts.poppins(color: Colors.white))), + ); + Navigator.pop(context, true); + } + } catch (e) { + debugPrint(e.toString()); + } + } + + Widget input(String label, TextEditingController controller, + {bool readOnly = false, + VoidCallback? onTap, + TextInputType type = TextInputType.text}) { + return Padding( + padding: const EdgeInsets.only(bottom: 14), + child: Row( + children: [ + SizedBox( + width: 160, + child: Text(label, + style: GoogleFonts.poppins( + fontSize: 12, fontWeight: FontWeight.w500)), + ), + Text(": ", style: GoogleFonts.poppins()), + Expanded( + child: TextField( + controller: controller, + readOnly: readOnly, + onTap: onTap, + keyboardType: type, + style: GoogleFonts.poppins(fontSize: 12), + decoration: InputDecoration( + contentPadding: + const EdgeInsets.symmetric(horizontal: 10, vertical: 10), + border: + OutlineInputBorder(borderRadius: BorderRadius.circular(8)), + ), + ), + ) + ], + ), + ); + } + + Widget dropdownStatusGizi() { + return Padding( + padding: const EdgeInsets.only(bottom: 14), + child: Row( + children: [ + SizedBox( + width: 160, + child: Text("Status Gizi", + style: GoogleFonts.poppins( + fontSize: 12, fontWeight: FontWeight.w500)), + ), + Text(": ", style: GoogleFonts.poppins()), + Expanded( + child: DropdownButtonFormField( + value: statusGizi, + style: GoogleFonts.poppins(fontSize: 12, color: Colors.black), + items: [ + DropdownMenuItem( + value: "KEK (Kekurangan Energi Kronis)", + child: Text("KEK", style: GoogleFonts.poppins())), + DropdownMenuItem( + value: "Normal", + child: Text("Normal", style: GoogleFonts.poppins())), + ], + onChanged: (value) { + setState(() { + statusGizi = value; + }); + }, + decoration: InputDecoration( + contentPadding: + const EdgeInsets.symmetric(horizontal: 10, vertical: 10), + border: + OutlineInputBorder(borderRadius: BorderRadius.circular(8)), + ), + ), + ) + ], + ), + ); + } + + Widget dropdownKakiBengkak() { + return Padding( + padding: const EdgeInsets.only(bottom: 14), + child: Row( + children: [ + SizedBox( + width: 160, + child: Text("Kaki Bengkak", + style: GoogleFonts.poppins( + fontSize: 12, fontWeight: FontWeight.w500)), + ), + Text(": ", style: GoogleFonts.poppins()), + Expanded( + child: DropdownButtonFormField( + value: kakiBengkak, + style: GoogleFonts.poppins(fontSize: 12, color: Colors.black), + items: [ + DropdownMenuItem( + value: "Iya", + child: Text("Iya", style: GoogleFonts.poppins())), + DropdownMenuItem( + value: "Tidak", + child: Text("Tidak", style: GoogleFonts.poppins())), + ], + onChanged: (value) { + setState(() { + kakiBengkak = value; + }); + }, + decoration: InputDecoration( + contentPadding: + const EdgeInsets.symmetric(horizontal: 10, vertical: 10), + border: + OutlineInputBorder(borderRadius: BorderRadius.circular(8)), + ), + ), + ) + ], + ), + ); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: Colors.white, + appBar: AppBar( + elevation: 0, + backgroundColor: Colors.blue, + leading: IconButton( + icon: const Icon(Icons.arrow_back, color: Colors.white), + onPressed: () => Navigator.pop(context), + ), + title: Text("", + style: GoogleFonts.poppins( + color: Colors.white, + fontSize: 16, + fontWeight: FontWeight.w600)), + ), + body: SingleChildScrollView( + padding: const EdgeInsets.all(16), + child: Column( + children: [ + Center( + child: Text( + "Edit Pemeriksaan Kehamilan", + style: GoogleFonts.poppins( + fontSize: 18, fontWeight: FontWeight.w600), + ), + ), + const SizedBox(height: 16), + + /// CARD + Center( + child: Container( + constraints: const BoxConstraints(maxWidth: 500), + child: Card( + color: Colors.white, + elevation: 4, + clipBehavior: Clip.antiAlias, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16), + ), + child: Column( + children: [ + /// HEADER BIRU + Container( + width: double.infinity, + padding: const EdgeInsets.all(14), + decoration: const BoxDecoration( + color: Colors.blue, + borderRadius: BorderRadius.vertical( + top: Radius.circular(16), + ), + ), + child: Text( + widget.nama, + style: GoogleFonts.poppins( + color: Colors.white, fontWeight: FontWeight.w600), + ), + ), + + /// ISI FORM + Padding( + padding: const EdgeInsets.all(16), + child: Column( + children: [ + input( + "Tanggal Pemeriksaan", displayTanggalController, + readOnly: true, onTap: pilihTanggal), + input("BB Sblm Hamil (kg)", bbSebelumController, + type: TextInputType.number), + input("Berat Badan (kg)", beratController, + type: TextInputType.number), + input("Tinggi Badan (cm)", tinggiController, + type: TextInputType.number), + input("LILA (cm)", lilaController, + type: TextInputType.number), + dropdownStatusGizi(), + input("Tekanan Darah", tekananController), + input("Tinggi Fundus (cm)", fundusController, + type: TextInputType.number), + input("Denyut Jantung Janin", djjController), + input("HB", hbController), + dropdownKakiBengkak(), + input("Keluhan", keluhanController), + input("Tindakan", tindakanController), + const SizedBox(height: 20), + + // --- TOMBOL SIMPAN PERUBAHAN (OUTLINED STADIUM) --- + SizedBox( + width: double.infinity, + child: OutlinedButton( + onPressed: updateData, + style: OutlinedButton.styleFrom( + side: const BorderSide( + color: Colors.blue, width: 2), + shape: const StadiumBorder(), + padding: + const EdgeInsets.symmetric(vertical: 15), + ), + child: Text( + "Simpan Perubahan", + style: GoogleFonts.poppins( + fontSize: 12, + color: Colors.blue, + fontWeight: FontWeight.bold, + ), + ), + ), + ) + ], + ), + ) + ], + ), + ), + ), + ) + ], + ), + ), + ); + } +} diff --git a/lib/bidan/crud_kehamilan/riwayat_pemeriksaan_kehamilan.dart b/lib/bidan/crud_kehamilan/riwayat_pemeriksaan_kehamilan.dart new file mode 100644 index 0000000..29a09f8 --- /dev/null +++ b/lib/bidan/crud_kehamilan/riwayat_pemeriksaan_kehamilan.dart @@ -0,0 +1,407 @@ +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:http/http.dart' as http; +import 'edit_pemeriksaan_kehamilan.dart'; + +class RiwayatPemeriksaanKehamilanPage extends StatefulWidget { + final String ibuHamilId; + final String nama; + + const RiwayatPemeriksaanKehamilanPage({ + super.key, + required this.ibuHamilId, + required this.nama, + }); + + @override + State createState() => + _RiwayatPemeriksaanKehamilanPageState(); +} + +class _RiwayatPemeriksaanKehamilanPageState + extends State { + List> _data = []; + List> _dataFilter = []; + bool _loading = true; + final TextEditingController searchController = TextEditingController(); + + int _currentPage = 0; + final int _rowsPerPage = 5; + + String _formatTanggalIndo(String? tanggal) { + if (tanggal == null || tanggal.isEmpty) return "-"; + try { + DateTime dt = DateTime.parse(tanggal); + List bulanIndo = [ + "", + "Januari", + "Februari", + "Maret", + "April", + "Mei", + "Juni", + "Juli", + "Agustus", + "September", + "Oktober", + "November", + "Desember" + ]; + return "${dt.day.toString().padLeft(2, '0')} ${bulanIndo[dt.month]} ${dt.year}"; + } catch (e) { + return tanggal; + } + } + + @override + void initState() { + super.initState(); + fetchRiwayat(); + } + + Future fetchRiwayat() async { + setState(() => _loading = true); + final url = Uri.parse( + "http://ta.myhost.id/E31230549/mposyandu_api/pemeriksaan_kehamilan/get_riwayat_pemeriksaan.php?ibu_hamil_id=${widget.ibuHamilId}"); + + try { + final response = await http.get(url); + if (response.statusCode == 200) { + final jsonData = json.decode(response.body); + if (jsonData["success"] == true) { + List> data = + List>.from(jsonData["data"]); + + data.sort((a, b) { + DateTime dateA = + DateTime.tryParse(a['tanggal_pemeriksaan'] ?? '') ?? + DateTime(1900); + DateTime dateB = + DateTime.tryParse(b['tanggal_pemeriksaan'] ?? '') ?? + DateTime(1900); + return dateB.compareTo(dateA); + }); + + setState(() { + _data = data; + _dataFilter = data; + }); + } + } + } catch (e) { + debugPrint(e.toString()); + } + setState(() => _loading = false); + } + + void _filterData(String keyword) { + final key = keyword.toLowerCase(); + setState(() { + _dataFilter = _data.where((item) { + return item['tanggal_pemeriksaan'] + .toString() + .toLowerCase() + .contains(key) || + item['keluhan'].toString().toLowerCase().contains(key) || + item['tindakan'].toString().toLowerCase().contains(key); + }).toList(); + _currentPage = 0; + }); + } + + List> get _paginatedData { + if (_dataFilter.isEmpty) return []; + final start = _currentPage * _rowsPerPage; + final end = start + _rowsPerPage; + if (start >= _dataFilter.length) return []; + return _dataFilter.sublist( + start, end > _dataFilter.length ? _dataFilter.length : end); + } + + Future hapusData(String id) async { + final confirm = await showDialog( + context: context, + builder: (context) => AlertDialog( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)), + title: Text("Konfirmasi", + style: + GoogleFonts.poppins(fontSize: 14, fontWeight: FontWeight.bold)), + content: Text("Yakin ingin menghapus data ini?", + style: GoogleFonts.poppins(fontSize: 12)), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context, false), + child: Text("Batal", + style: + GoogleFonts.poppins(fontSize: 12, color: Colors.grey))), + TextButton( + onPressed: () => Navigator.pop(context, true), + child: Text("Hapus", + style: GoogleFonts.poppins(fontSize: 12, color: Colors.red))), + ], + ), + ); + + if (confirm != true) return; + + final url = Uri.parse( + "http://ta.myhost.id/E31230549/mposyandu_api/pemeriksaan_kehamilan/hapus_pemeriksaan.php"); + try { + final response = await http.post(url, body: {"id": id}); + final result = json.decode(response.body); + if (result["success"] == true) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text("Data berhasil dihapus", + style: GoogleFonts.poppins(fontSize: 12))), + ); + fetchRiwayat(); + } + } catch (e) { + debugPrint(e.toString()); + } + } + + @override + Widget build(BuildContext context) { + final totalPages = + _dataFilter.isEmpty ? 1 : (_dataFilter.length / _rowsPerPage).ceil(); + + return Scaffold( + backgroundColor: const Color(0xFFFDFDFD), + appBar: AppBar( + backgroundColor: Colors.blueAccent, + elevation: 0, + leading: IconButton( + icon: const Icon(Icons.arrow_back, color: Colors.white), + onPressed: () => Navigator.pop(context, true), + ), + ), + body: _loading + ? const Center(child: CircularProgressIndicator()) + : Column( + children: [ + Padding( + padding: const EdgeInsets.only(top: 20, bottom: 12), + child: Center( + child: Text( + "Riwayat Pemeriksaan Kehamilan", + style: GoogleFonts.poppins( + fontSize: 18, + fontWeight: FontWeight.bold, + color: Colors.black, + ), + ), + ), + ), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 20), + child: TextField( + controller: searchController, + onChanged: _filterData, + style: GoogleFonts.poppins(fontSize: 12), + decoration: InputDecoration( + hintText: "Cari berdasarkan tanggal, keluhan...", + hintStyle: + GoogleFonts.poppins(fontSize: 12, color: Colors.grey), + prefixIcon: const Icon(Icons.search, + size: 20, color: Colors.grey), + contentPadding: const EdgeInsets.symmetric(vertical: 10), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: const BorderSide(color: Colors.grey), + ), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: const BorderSide(color: Colors.grey), + ), + ), + ), + ), + const SizedBox(height: 15), + Expanded( + child: _dataFilter.isEmpty + ? Center( + child: Text("Tidak ada riwayat pemeriksaan", + style: GoogleFonts.poppins( + fontSize: 12, color: Colors.grey))) + : ListView.builder( + itemCount: _paginatedData.length, + itemBuilder: (context, index) { + final data = _paginatedData[index]; + return _buildCard(data); + }, + ), + ), + Container( + padding: + const EdgeInsets.symmetric(horizontal: 20, vertical: 8), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text("Halaman ${_currentPage + 1} dari $totalPages", + style: GoogleFonts.poppins( + fontSize: 12, color: Colors.black)), + Row( + children: [ + IconButton( + iconSize: 20, + icon: const Icon(Icons.chevron_left), + onPressed: _currentPage == 0 + ? null + : () => setState(() => _currentPage--)), + IconButton( + iconSize: 20, + icon: const Icon(Icons.chevron_right), + onPressed: _currentPage >= totalPages - 1 + ? null + : () => setState(() => _currentPage++)), + ], + ) + ], + ), + ) + ], + ), + ); + } + + Widget _buildCard(Map data) { + return Center( + child: Container( + margin: const EdgeInsets.symmetric(horizontal: 25, vertical: 8), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(14), + border: Border.all(color: Colors.grey.shade300), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.03), + blurRadius: 5, + offset: const Offset(0, 2)), + ], + ), + child: Column( + children: [ + Container( + width: double.infinity, + padding: const EdgeInsets.all(12), + decoration: const BoxDecoration( + color: Colors.blueAccent, + borderRadius: BorderRadius.vertical(top: Radius.circular(14)), + ), + child: Text( + widget.nama, + style: GoogleFonts.poppins( + color: Colors.white, + fontWeight: FontWeight.bold, + fontSize: 12), + ), + ), + Padding( + padding: const EdgeInsets.all(12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _row("Tanggal", + _formatTanggalIndo(data["tanggal_pemeriksaan"])), + _row( + "BB Sblm Hamil", "${data["bb_sebelum_hamil"] ?? '-'} kg"), + _row("Berat Badan", "${data["berat_badan"] ?? '-'} kg"), + _row("Tinggi Badan", "${data["tinggi_badan"] ?? '-'} cm"), + _row("LILA", "${data["LILA"] ?? '-'} cm"), + _row("Status Gizi", data["status_gizi"]), + _row("Tekanan Darah", data["tekanan_darah"]), + _row("Tinggi Fundus", "${data["tinggi_fundus"] ?? '-'} cm"), + _row("DJJ", data["denyut_jantung_janin"]), + _row("HB", data["hb"]), + _row("Kaki Bengkak", data["kaki_bengkak"]), + _row("Keluhan", data["keluhan"]), + _row("Tindakan", data["tindakan"]), + const SizedBox(height: 12), + Row( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + SizedBox( + height: 32, + child: OutlinedButton.icon( + onPressed: () async { + final result = await Navigator.push( + context, + MaterialPageRoute( + builder: (_) => EditPemeriksaanKehamilanPage( + data: data, nama: widget.nama), + ), + ); + if (result == true) fetchRiwayat(); + }, + icon: const Icon(Icons.edit, + size: 16, color: Colors.orange), + label: Text("Edit", + style: GoogleFonts.poppins( + fontSize: 12, + color: Colors.orange, + fontWeight: FontWeight.w500)), + style: OutlinedButton.styleFrom( + side: const BorderSide(color: Colors.orange), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(20)), + padding: const EdgeInsets.symmetric(horizontal: 16), + ), + ), + ), + const SizedBox(width: 8), + SizedBox( + height: 32, + child: OutlinedButton.icon( + onPressed: () => hapusData(data["id"].toString()), + icon: const Icon(Icons.delete, + size: 16, color: Colors.redAccent), + label: Text("Hapus", + style: GoogleFonts.poppins( + fontSize: 12, + color: Colors.redAccent, + fontWeight: FontWeight.w500)), + style: OutlinedButton.styleFrom( + side: const BorderSide(color: Colors.redAccent), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(20)), + padding: const EdgeInsets.symmetric(horizontal: 16), + ), + ), + ), + ], + ) + ], + ), + ) + ], + ), + ), + ); + } + + Widget _row(String label, dynamic value) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 3), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: 110, // Sedikit diperlebar agar label panjang tidak terpotong + child: Text(label, + style: GoogleFonts.poppins( + fontSize: 11, fontWeight: FontWeight.w600)), + ), + Text(" : ", style: GoogleFonts.poppins(fontSize: 11)), + Expanded( + child: Text("${value ?? '-'}", + style: GoogleFonts.poppins(fontSize: 11)), + ) + ], + ), + ); + } +} diff --git a/lib/bidan/crud_kehamilan/tambah_pemeriksaan_kehamilan.dart b/lib/bidan/crud_kehamilan/tambah_pemeriksaan_kehamilan.dart new file mode 100644 index 0000000..643330b --- /dev/null +++ b/lib/bidan/crud_kehamilan/tambah_pemeriksaan_kehamilan.dart @@ -0,0 +1,416 @@ +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:http/http.dart' as http; +import 'package:intl/intl.dart'; + +class TambahPemeriksaanKehamilanPage extends StatefulWidget { + final String ibuHamilId; + final String nama; + + const TambahPemeriksaanKehamilanPage({ + super.key, + required this.ibuHamilId, + required this.nama, + }); + + @override + State createState() => + _TambahPemeriksaanKehamilanPageState(); +} + +class _TambahPemeriksaanKehamilanPageState + extends State { + final tanggalController = TextEditingController(); + final displayTanggalController = TextEditingController(); + + final bbSebelumController = TextEditingController(); // Baru + final beratController = TextEditingController(); + final tinggiController = TextEditingController(); // Baru + final lilaController = TextEditingController(); // Baru + final tekananController = TextEditingController(); + final fundusController = TextEditingController(); + final djjController = TextEditingController(); + final hbController = TextEditingController(); + final keluhanController = TextEditingController(); + final tindakanController = TextEditingController(); + + String? kakiBengkak; + String? statusGizi; // Baru + + final String url = + "http://ta.myhost.id/E31230549/mposyandu_api/pemeriksaan_kehamilan/tambah_pemeriksaan_kehamilan.php"; + + @override + void initState() { + super.initState(); + DateTime sekarang = DateTime.now(); + tanggalController.text = DateFormat('yyyy-MM-dd').format(sekarang); + displayTanggalController.text = formatKeIndonesia(sekarang); + } + + @override + void dispose() { + tanggalController.dispose(); + displayTanggalController.dispose(); + bbSebelumController.dispose(); + beratController.dispose(); + tinggiController.dispose(); + lilaController.dispose(); + tekananController.dispose(); + fundusController.dispose(); + djjController.dispose(); + hbController.dispose(); + keluhanController.dispose(); + tindakanController.dispose(); + super.dispose(); + } + + String formatKeIndonesia(DateTime date) { + List bulan = [ + "Januari", + "Februari", + "Maret", + "April", + "Mei", + "Juni", + "Juli", + "Agustus", + "September", + "Oktober", + "November", + "Desember" + ]; + return "${date.day} ${bulan[date.month - 1]} ${date.year}"; + } + + Future pilihTanggal() async { + final DateTime? picked = await showDatePicker( + context: context, + initialDate: DateTime.now(), + firstDate: DateTime(2000), + lastDate: DateTime(2100), + ); + + if (picked != null) { + setState(() { + tanggalController.text = DateFormat('yyyy-MM-dd').format(picked); + displayTanggalController.text = formatKeIndonesia(picked); + }); + } + } + + Future simpanData() async { + if (kakiBengkak == null || statusGizi == null) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text( + "Silahkan lengkapi status Kaki Bengkak dan Status Gizi", + style: GoogleFonts.poppins(fontSize: 12), + ), + ), + ); + return; + } + + try { + final response = await http.post( + Uri.parse(url), + body: { + "ibu_hamil_id": widget.ibuHamilId, + "tanggal_pemeriksaan": tanggalController.text, + "bb_sebelum_hamil": bbSebelumController.text, + "berat_badan": beratController.text, + "tinggi_badan": tinggiController.text, + "LILA": lilaController.text, + "status_gizi": statusGizi ?? "", + "tekanan_darah": tekananController.text, + "tinggi_fundus": fundusController.text, + "denyut_jantung_janin": djjController.text, + "hb": hbController.text, + "kaki_bengkak": kakiBengkak ?? "", + "keluhan": keluhanController.text, + "tindakan": tindakanController.text, + }, + ); + + final res = jsonDecode(response.body); + + if (res["success"] == true) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text( + "Data berhasil disimpan", + style: GoogleFonts.poppins(fontSize: 12), + ), + ), + ); + Navigator.pop(context, true); + } else { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text( + res["message"] ?? "Gagal menyimpan data", + style: GoogleFonts.poppins(fontSize: 12), + ), + ), + ); + } + } catch (e) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text( + "Terjadi kesalahan koneksi", + style: GoogleFonts.poppins(fontSize: 12), + ), + ), + ); + } + } + + Widget input(String label, TextEditingController controller, + {bool readOnly = false, + VoidCallback? onTap, + TextInputType type = TextInputType.text}) { + return Padding( + padding: const EdgeInsets.only(bottom: 14), + child: Row( + children: [ + SizedBox( + width: 160, + child: Text( + label, + style: GoogleFonts.poppins( + fontSize: 12, fontWeight: FontWeight.w500), + ), + ), + Text(" : ", style: GoogleFonts.poppins(fontSize: 12)), + Expanded( + child: TextField( + controller: controller, + readOnly: readOnly, + onTap: onTap, + keyboardType: type, + style: GoogleFonts.poppins(fontSize: 12), + decoration: InputDecoration( + contentPadding: + const EdgeInsets.symmetric(horizontal: 10, vertical: 10), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + ), + ), + ), + ) + ], + ), + ); + } + + Widget dropdownGizi() { + return Padding( + padding: const EdgeInsets.only(bottom: 14), + child: Row( + children: [ + SizedBox( + width: 160, + child: Text( + "Status Gizi", + style: GoogleFonts.poppins( + fontSize: 12, fontWeight: FontWeight.w500), + ), + ), + Text(" : ", style: GoogleFonts.poppins(fontSize: 12)), + Expanded( + child: DropdownButtonFormField( + value: statusGizi, + style: GoogleFonts.poppins(fontSize: 12, color: Colors.black), + hint: Text("Pilih Status", + style: GoogleFonts.poppins(fontSize: 12)), + items: [ + DropdownMenuItem( + value: "KEK (Kekurangan Energi Kronis)", + child: + Text("KEK", style: GoogleFonts.poppins(fontSize: 12))), + DropdownMenuItem( + value: "Normal", + child: Text("Normal", + style: GoogleFonts.poppins(fontSize: 12))), + ], + onChanged: (value) => setState(() => statusGizi = value), + decoration: InputDecoration( + contentPadding: + const EdgeInsets.symmetric(horizontal: 10, vertical: 10), + border: + OutlineInputBorder(borderRadius: BorderRadius.circular(8)), + ), + ), + ) + ], + ), + ); + } + + Widget dropdownKakiBengkak() { + return Padding( + padding: const EdgeInsets.only(bottom: 14), + child: Row( + children: [ + SizedBox( + width: 160, + child: Text( + "Kaki Bengkak", + style: GoogleFonts.poppins( + fontSize: 12, fontWeight: FontWeight.w500), + ), + ), + Text(" : ", style: GoogleFonts.poppins(fontSize: 12)), + Expanded( + child: DropdownButtonFormField( + value: kakiBengkak, + style: GoogleFonts.poppins(fontSize: 12, color: Colors.black), + hint: Text("Pilih", style: GoogleFonts.poppins(fontSize: 12)), + items: [ + DropdownMenuItem( + value: "Iya", + child: + Text("Iya", style: GoogleFonts.poppins(fontSize: 12))), + DropdownMenuItem( + value: "Tidak", + child: Text("Tidak", + style: GoogleFonts.poppins(fontSize: 12))), + ], + onChanged: (value) => setState(() => kakiBengkak = value), + decoration: InputDecoration( + contentPadding: + const EdgeInsets.symmetric(horizontal: 10, vertical: 10), + border: + OutlineInputBorder(borderRadius: BorderRadius.circular(8)), + ), + ), + ) + ], + ), + ); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: Text("", + style: GoogleFonts.poppins(color: Colors.white, fontSize: 16)), + backgroundColor: Colors.blue, + elevation: 0, + leading: IconButton( + icon: const Icon(Icons.arrow_back, color: Colors.white), + onPressed: () => Navigator.pop(context), + ), + ), + body: SingleChildScrollView( + padding: const EdgeInsets.all(16), + child: Column( + children: [ + Center( + child: Text( + "Tambah Pemeriksaan Kehamilan", + style: GoogleFonts.poppins( + fontSize: 18, + fontWeight: FontWeight.w600, + color: Colors.black, + ), + ), + ), + const SizedBox(height: 16), + Center( + child: SizedBox( + width: 500, + child: Card( + color: Colors.white, + elevation: 2, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + ), + child: Column( + children: [ + Container( + width: double.infinity, + padding: const EdgeInsets.all(14), + decoration: const BoxDecoration( + color: Colors.blue, + borderRadius: BorderRadius.vertical( + top: Radius.circular(12), + ), + ), + child: Text( + widget.nama, + style: GoogleFonts.poppins( + color: Colors.white, + fontWeight: FontWeight.w600, + fontSize: 13, + ), + ), + ), + Padding( + padding: const EdgeInsets.all(16), + child: Column( + children: [ + input( + "Tanggal Pemeriksaan", + displayTanggalController, + readOnly: true, + onTap: pilihTanggal, + ), + input("BB Sebelum Hamil (kg)", bbSebelumController, + type: TextInputType.number), + input("Berat Badan Sekarang (kg)", beratController, + type: TextInputType.number), + input("Tinggi Badan (cm)", tinggiController, + type: TextInputType.number), + input("LILA (cm)", lilaController, + type: TextInputType.number), + dropdownGizi(), + input("Tekanan Darah", tekananController), + input("Tinggi Fundus (cm)", fundusController, + type: TextInputType.number), + input("Denyut Jantung Janin", djjController), + input("HB", hbController), + dropdownKakiBengkak(), + input("Keluhan", keluhanController), + input("Tindakan", tindakanController), + const SizedBox(height: 20), + Center( + child: SizedBox( + width: 200, + child: OutlinedButton( + style: OutlinedButton.styleFrom( + side: const BorderSide( + color: Colors.blue, width: 2), + shape: const StadiumBorder(), + padding: const EdgeInsets.symmetric( + vertical: 14), + ), + onPressed: simpanData, + child: Text( + "Simpan", + style: GoogleFonts.poppins( + color: Colors.blue, + fontSize: 12, + fontWeight: FontWeight.bold), + ), + ), + ), + ), + ], + ), + ) + ], + ), + ), + ), + ), + ], + ), + ), + ); + } +} diff --git a/lib/bidan/dashboard_bidan.dart b/lib/bidan/dashboard_bidan.dart new file mode 100644 index 0000000..5dbdb37 --- /dev/null +++ b/lib/bidan/dashboard_bidan.dart @@ -0,0 +1,434 @@ +import 'dart:convert'; +import 'dart:math'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:http/http.dart' as http; + +import '../layout/main_layout.dart'; +import 'bidan_drawer.dart'; +import '../pages/login_page.dart'; +import '../bidan/data_gizi_balita.dart'; +import '../bidan/laporan.dart'; + +const String baseUrl = "http://ta.myhost.id/E31230549/mposyandu_api"; + +class DashboardBidanPage extends StatefulWidget { + const DashboardBidanPage({super.key}); + + @override + State createState() => _DashboardBidanPageState(); +} + +class _DashboardBidanPageState extends State { + int jumlahIbuHamil = 0; + int jumlahBalita = 0; + + // Variabel penampung data grafik Ibu Hamil + double bumilKek = 0; + double bumilNormal = 0; + + String namaUser = ""; + + final List listBulan = [ + 'Jan', + 'Feb', + 'Mar', + 'Apr', + 'Mei', + 'Jun', + 'Jul', + 'Agu', + 'Sep', + 'Okt', + 'Nov', + 'Des' + ]; + + @override + void initState() { + super.initState(); + _checkLogin(); + getDashboard(); + } + + Future _checkLogin() async { + final prefs = await SharedPreferences.getInstance(); + final isLogin = prefs.getBool('isLogin') ?? false; + + if (!isLogin) { + if (!mounted) return; + Navigator.pushAndRemoveUntil( + context, + MaterialPageRoute(builder: (_) => const LoginPage(fromGuard: true)), + (route) => false, + ); + } else { + setState(() { + namaUser = prefs.getString('nama') ?? "Bidan"; + }); + } + } + + Future getDashboard() async { + try { + final response = + await http.get(Uri.parse("$baseUrl/dashboard_bidan.php")); + final data = jsonDecode(response.body); + + if (data["success"] == true) { + setState(() { + jumlahIbuHamil = int.parse(data["ibu_hamil"].toString()); + jumlahBalita = int.parse(data["balita"].toString()); + + // Menangkap data kondisi pemeriksaan LILA terbaru dari JSON + bumilKek = double.parse((data["bumil_kek"] ?? 0).toString()); + bumilNormal = double.parse((data["bumil_normal"] ?? 0).toString()); + }); + } + } catch (e) { + debugPrint("ERROR DASHBOARD: $e"); + } + } + + // Fungsi untuk mendeteksi klik pada diagram batang + void _handleChartTap(TapUpDetails details, Size size) { + const double paddingLeft = 30; + const double paddingBottom = 30; + final double chartWidth = size.width - paddingLeft; + final double chartHeight = size.height - paddingBottom; + + double maxData = max(10, max(bumilNormal, bumilKek) + 5); + double groupWidth = chartWidth / listBulan.length; + double barWidth = groupWidth * 0.3; + + int currentMonthIndex = DateTime.now().month - 1; + + // Hitung posisi koordinat X pusat untuk bulan saat ini + double xCenter = + paddingLeft + (currentMonthIndex * groupWidth) + (groupWidth / 2); + + // Hitung area Rect untuk Batang Normal + double barHeightNormal = (bumilNormal / maxData) * chartHeight; + Rect rectNormal = Rect.fromLTWH(xCenter - barWidth, + chartHeight - barHeightNormal, barWidth, barHeightNormal); + + // Hitung area Rect untuk Batang KEK + double barHeightKek = (bumilKek / maxData) * chartHeight; + Rect rectKek = Rect.fromLTWH( + xCenter, chartHeight - barHeightKek, barWidth, barHeightKek); + + // Ambil posisi lokal ketukan jari user + Offset tapPosition = details.localPosition; + + // Cek apakah ketukan berada di dalam salah satu area batang + if (rectNormal.contains(tapPosition)) { + _showDetailDialog("Bumil Normal", bumilNormal.round()); + } else if (rectKek.contains(tapPosition)) { + _showDetailDialog("Berisiko KEK", bumilKek.round()); + } + } + + // Fungsi memunculkan pop-up angka pasti + void _showDetailDialog(String kategori, int jumlah) { + showDialog( + context: context, + builder: (context) => AlertDialog( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), + title: Text(kategori, + style: GoogleFonts.poppins(fontWeight: FontWeight.bold)), + content: Text( + "Jumlah saat ini: $jumlah Ibu Hamil", + style: GoogleFonts.poppins(fontSize: 15), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text("OK", + style: + TextStyle(fontWeight: FontWeight.bold, color: Colors.blue)), + ), + ], + ), + ); + } + + @override + Widget build(BuildContext context) { + return PopScope( + canPop: false, + onPopInvokedWithResult: (didPop, result) async { + if (didPop) return; + await SystemNavigator.pop(); + }, + child: Theme( + data: Theme.of(context).copyWith( + textTheme: GoogleFonts.poppinsTextTheme(Theme.of(context).textTheme), + dividerColor: Colors.transparent, + ), + child: MainLayout( + title: "", + drawer: const BidanDrawer(), + body: _buildBody(), + ), + ), + ); + } + + Widget _buildBody() { + return SingleChildScrollView( + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + RichText( + text: TextSpan( + children: [ + TextSpan( + text: 'Selamat Datang Bidan $namaUser\n', + style: GoogleFonts.poppins( + fontSize: 20, + fontWeight: FontWeight.w700, + color: Colors.blue, + ), + ), + TextSpan( + text: + 'Melayani dengan sepenuh hati untuk generasi tetap sehat ', + style: + GoogleFonts.poppins(fontSize: 13, color: Colors.black), + ), + const WidgetSpan( + alignment: PlaceholderAlignment.middle, + child: Icon(Icons.favorite, color: Colors.blue, size: 18), + ), + ], + ), + ), + const SizedBox(height: 15), + Center( + child: Image.asset( + 'assets/images/logoo.webp', + width: 300, + height: 180, + fit: BoxFit.contain, + ), + ), + const SizedBox(height: 25), + Row( + children: [ + _infoBox("$jumlahIbuHamil", "Ibu Hamil Aktif", Colors.pink), + const SizedBox(width: 10), + _infoBox("$jumlahBalita", "Balita Terdaftar", Colors.amber), + ], + ), + const SizedBox(height: 20), + Row( + children: [ + _actionButton('Lihat Data Gizi', () { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => const DataGiziBalitaPage())); + }), + const SizedBox(width: 10), + _actionButton('Lihat Laporan', () { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => const DataLaporanPage())); + }), + ], + ), + const SizedBox(height: 25), + Text( + 'Statistik Risiko KEK Ibu Hamil Bulan Ini', + style: GoogleFonts.poppins( + fontWeight: FontWeight.bold, fontSize: 16), + ), + const SizedBox(height: 15), + Container( + padding: const EdgeInsets.fromLTRB(10, 25, 15, 10), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12), + boxShadow: [ + BoxShadow( + color: Colors.grey.withOpacity(0.1), + spreadRadius: 2, + blurRadius: 10, + ), + ], + ), + child: Column( + children: [ + // Menggunakan LayoutBuilder agar size CustomPaint sinkron dengan pendeteksi klik + LayoutBuilder( + builder: (context, constraints) { + final size = Size(constraints.maxWidth, 250); + return GestureDetector( + onTapUp: (details) => _handleChartTap(details, size), + child: SizedBox( + height: size.height, + width: size.width, + child: CustomPaint( + painter: BarChartPainter( + normal: bumilNormal, + kek: bumilKek, + months: listBulan, + currentMonthIndex: DateTime.now().month - 1, + ), + ), + ), + ); + }, + ), + const SizedBox(height: 20), + Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + _legendItem(Colors.teal, "Bumil Normal"), + const SizedBox(width: 25), + _legendItem(Colors.pink.shade400, "Berisiko KEK"), + ], + ), + ], + ), + ), + const SizedBox(height: 20), + ], + ), + ), + ); + } + + Widget _actionButton(String title, VoidCallback onPressed) { + return Expanded( + child: ElevatedButton( + style: ElevatedButton.styleFrom( + backgroundColor: Colors.blue, + padding: const EdgeInsets.symmetric(vertical: 14), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), + ), + onPressed: onPressed, + child: Text(title, style: const TextStyle(color: Colors.white)), + ), + ); + } + + Widget _legendItem(Color color, String text) { + return Row( + children: [ + Container( + width: 14, + height: 14, + decoration: BoxDecoration(color: color, shape: BoxShape.circle), + ), + const SizedBox(width: 8), + Text(text, + style: const TextStyle(fontSize: 13, fontWeight: FontWeight.w500)), + ], + ); + } + + Widget _infoBox(String value, String label, Color color) { + return Expanded( + child: Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: color, borderRadius: BorderRadius.circular(12)), + child: Column( + children: [ + Text(value, + style: const TextStyle( + color: Colors.white, + fontSize: 24, + fontWeight: FontWeight.bold)), + const SizedBox(height: 5), + Text(label, + textAlign: TextAlign.center, + style: const TextStyle(color: Colors.white, fontSize: 12)), + ], + ), + ), + ); + } +} + +class BarChartPainter extends CustomPainter { + final double normal; + final double kek; + final List months; + final int currentMonthIndex; + + BarChartPainter({ + required this.normal, + required this.kek, + required this.months, + required this.currentMonthIndex, + }); + + @override + void paint(Canvas canvas, Size size) { + final paintGrid = Paint() + ..color = Colors.grey.shade300 + ..strokeWidth = 1; + const double paddingLeft = 30; + const double paddingBottom = 30; + final double chartWidth = size.width - paddingLeft; + final double chartHeight = size.height - paddingBottom; + + double maxData = max(10, max(normal, kek) + 5); + + int segments = 5; + for (int i = 0; i <= segments; i++) { + double y = chartHeight - (i * chartHeight / segments); + canvas.drawLine(Offset(paddingLeft, y), Offset(size.width, y), paintGrid); + _drawText(canvas, Offset(5, y - 7), + (maxData / segments * i).round().toString(), 10, Colors.grey); + } + + double groupWidth = chartWidth / months.length; + double barWidth = groupWidth * 0.3; + + for (int i = 0; i < months.length; i++) { + double xCenter = paddingLeft + (i * groupWidth) + (groupWidth / 2); + _drawText(canvas, Offset(xCenter - 10, chartHeight + 10), months[i], 9, + Colors.black); + + if (i == currentMonthIndex) { + double barHeightNormal = (normal / maxData) * chartHeight; + canvas.drawRect( + Rect.fromLTWH(xCenter - barWidth, chartHeight - barHeightNormal, + barWidth, barHeightNormal), + Paint()..color = Colors.teal, + ); + + double barHeightKek = (kek / maxData) * chartHeight; + canvas.drawRect( + Rect.fromLTWH( + xCenter, chartHeight - barHeightKek, barWidth, barHeightKek), + Paint()..color = Colors.pink.shade400, + ); + } + } + } + + void _drawText( + Canvas canvas, Offset offset, String text, double fontSize, Color color) { + final textPainter = TextPainter( + text: TextSpan( + text: text, + style: TextStyle( + color: color, fontSize: fontSize, fontWeight: FontWeight.bold)), + textDirection: TextDirection.ltr, + ); + textPainter.layout(); + textPainter.paint(canvas, offset); + } + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => true; +} diff --git a/lib/bidan/data_gizi_balita.dart b/lib/bidan/data_gizi_balita.dart new file mode 100644 index 0000000..209abaa --- /dev/null +++ b/lib/bidan/data_gizi_balita.dart @@ -0,0 +1,531 @@ +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:http/http.dart' as http; + +import '../layout/main_layout.dart'; +import 'bidan_drawer.dart'; +import '../bidan/crud_data_gizi/tambah_gizi_balita.dart'; +import '../bidan/crud_data_gizi/riwayat_gizi_balita.dart'; +import '../bidan/dashboard_bidan.dart'; + +class DataGiziBalitaPage extends StatefulWidget { + const DataGiziBalitaPage({super.key}); + + @override + State createState() => _DataGiziBalitaPageState(); +} + +class _DataGiziBalitaPageState extends State { + List> _dataBalita = []; + bool _isLoading = true; + int _currentPage = 0; + final int _rowsPerPage = 5; + String _searchQuery = ""; + + @override + void initState() { + super.initState(); + fetchData(); + } + + String formatAngka(dynamic value, String satuan) { + if (value == null || + value.toString().trim().isEmpty || + value.toString().toLowerCase() == "null") { + return "-"; + } + return "${value.toString()}$satuan"; + } + + String formatTanggal(String? tgl) { + if (tgl == null || tgl == "-" || tgl.isEmpty) return "-"; + try { + DateTime dt = DateTime.parse(tgl); + List bulanIndo = [ + "", + "Januari", + "Februari", + "Maret", + "April", + "Mei", + "Juni", + "Juli", + "Agustus", + "September", + "Oktober", + "November", + "Desember" + ]; + return "${dt.day} ${bulanIndo[dt.month]} ${dt.year}"; + } catch (e) { + return tgl; + } + } + + // PERBAIKAN: Menghitung usia berdasarkan Tanggal Pemeriksaan, bukan Tanggal Sekarang + String hitungUsia(String? tglLahir, String? tglPeriksa) { + if (tglLahir == null || tglLahir == "-" || tglLahir.isEmpty) return "-"; + try { + DateTime lahir = DateTime.parse(tglLahir); + + // Menggunakan tanggal pemeriksaan sebagai acuan utama, jika kosong baru pakai waktu sekarang + DateTime acuanPeriksa = + (tglPeriksa != null && tglPeriksa != "-" && tglPeriksa.isNotEmpty) + ? DateTime.parse(tglPeriksa) + : DateTime.now(); + + // Hitung selisih bulan dasar + int bulan = (acuanPeriksa.year - lahir.year) * 12 + + acuanPeriksa.month - + lahir.month; + + // Logika pembulatan hari: Jika sisa hari pada bulan berjalan > 15 hari, bulatkan ke atas (+1 bulan) + DateTime tanggalTargetUlangTahun = + DateTime(lahir.year, lahir.month + bulan, lahir.day); + Duration selisihHari = acuanPeriksa.difference(tanggalTargetUlangTahun); + if (selisihHari.inDays > 15) { + bulan += 1; + } + + // Pengondisian jika hasil hitung bernilai negatif karena variasi tanggal + if (bulan < 0) bulan = 0; + + return "$bulan Bulan"; + } catch (e) { + return "-"; + } + } + + Future fetchData() async { + try { + final response = await http.get( + Uri.parse( + "http://ta.myhost.id/E31230549/mposyandu_api/gizi_balita/get_gizi_balita.php"), + ); + + if (response.statusCode == 200) { + final data = json.decode(response.body); + setState(() { + _dataBalita = List>.from(data); + _isLoading = false; + }); + } else { + setState(() => _isLoading = false); + } + } catch (e) { + debugPrint("Error Fetch: $e"); + setState(() => _isLoading = false); + } + } + + List> get _filteredData { + return _dataBalita + .where((item) => item["nama"] + .toString() + .toLowerCase() + .contains(_searchQuery.toLowerCase())) + .toList(); + } + + List> get _paginatedData { + final start = _currentPage * _rowsPerPage; + final end = start + _rowsPerPage; + if (start >= _filteredData.length) return []; + return _filteredData.sublist( + start, end > _filteredData.length ? _filteredData.length : end); + } + + @override + Widget build(BuildContext context) { + final totalPages = (_filteredData.length / _rowsPerPage).ceil() == 0 + ? 1 + : (_filteredData.length / _rowsPerPage).ceil(); + + return PopScope( + canPop: false, + onPopInvokedWithResult: (didPop, result) async { + if (didPop) return; + Navigator.pushAndRemoveUntil( + context, + MaterialPageRoute(builder: (_) => const DashboardBidanPage()), + (route) => false); + }, + child: MainLayout( + title: "", + drawer: const BidanDrawer(), + body: Padding( + padding: const EdgeInsets.all(16), + child: Column( + children: [ + Center( + child: Text("Data Gizi Balita", + style: GoogleFonts.poppins( + fontSize: 18, + fontWeight: FontWeight.w600, + color: Colors.black87)), + ), + const SizedBox(height: 12), + TextField( + onChanged: (value) => setState(() { + _searchQuery = value; + _currentPage = 0; + }), + style: GoogleFonts.poppins(fontSize: 12), + decoration: InputDecoration( + hintText: "Cari nama balita...", + hintStyle: GoogleFonts.poppins(fontSize: 12), + prefixIcon: const Icon(Icons.search, size: 20), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10)), + contentPadding: const EdgeInsets.symmetric(vertical: 8), + ), + ), + const SizedBox(height: 15), + Expanded( + child: _isLoading + ? const Center(child: CircularProgressIndicator()) + : _filteredData.isEmpty + ? Center( + child: Text("Data tidak tersedia", + style: GoogleFonts.poppins(fontSize: 12))) + : ListView.builder( + itemCount: _paginatedData.length, + itemBuilder: (context, index) { + final balita = _paginatedData[index]; + final bb = formatAngka(balita["bb"], "kg"); + final tb = formatAngka(balita["tb"], "cm"); + final lk = formatAngka(balita["lk"], "cm"); + + return Container( + margin: const EdgeInsets.only(bottom: 16), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12), + boxShadow: const [ + BoxShadow( + color: Colors.black12, + blurRadius: 8, + offset: Offset(0, 4)) + ], + ), + child: Column( + children: [ + Container( + width: double.infinity, + padding: const EdgeInsets.all(15), + decoration: const BoxDecoration( + color: Colors.blue, + borderRadius: BorderRadius.vertical( + top: Radius.circular(12)), + ), + child: Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: + MainAxisAlignment.spaceBetween, + children: [ + Expanded( + child: Text( + balita["nama"] ?? "-", + style: GoogleFonts.poppins( + color: Colors.white, + fontWeight: + FontWeight.bold, + fontSize: 13)), + ), + _badgeHadir( + balita["status_hadir"]), + ], + ), + const Divider(color: Colors.white54), + _rowWhite("Orang Tua", + balita["nama_orang_tua"] ?? "-"), + _rowWhite("Alamat", + balita["alamat"] ?? "-"), + + // PERBAIKAN: Mengirimkan dua parameter (tanggal lahir & tanggal pemeriksaan) + _rowWhite( + "Usia", + hitungUsia( + balita["tanggal_lahir"], + balita[ + "tanggal_pemeriksaan"])), + + _rowWhite( + "Tgl Pemeriksaan", + formatTanggal(balita[ + "tanggal_pemeriksaan"])), + _rowWhite("BB / TB / LK", + "$bb / $tb / $lk"), + _rowWhite("Catatan Kader", + balita["catatan"] ?? "-"), + ], + ), + ), + Container( + width: double.infinity, + padding: const EdgeInsets.all(15), + decoration: const BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.vertical( + bottom: Radius.circular(12)), + ), + child: Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + Text("Pemeriksaan Gizi Terakhir", + style: GoogleFonts.poppins( + fontWeight: FontWeight.w600, + fontSize: 12)), + const SizedBox(height: 8), + _rowGizi("Z-Score BB/U", + balita["zscore_bb_u"] ?? "-"), + _rowGizi("Z-Score TB/U", + balita["zscore_tb_u"] ?? "-"), + _rowGizi("Z-Score BB/TB", + balita["zscore_bb_tb"] ?? "-"), + const Divider(), + _rowStatus("Status Gizi", balita), + _rowGizi("Tindak Lanjut", + balita["tindak_lanjut"] ?? "-"), + _rowGizi( + "Saran", balita["saran"] ?? "-"), + const SizedBox(height: 12), + Row( + children: [ + _smallButton(Icons.add, "Input", + Colors.blue, () async { + await Navigator.push( + context, + MaterialPageRoute( + builder: (context) => + TambahGiziBalitaPage( + balita: + balita))); + fetchData(); + }), + _smallButton( + Icons.history, + "Riwayat", + Colors.deepPurple, () async { + await Navigator.push( + context, + MaterialPageRoute( + builder: (context) => + RiwayatGiziBalitaPage( + balita: + balita))); + fetchData(); + }), + ], + ) + ], + ), + ), + ], + ), + ); + }, + ), + ), + _buildPagination(totalPages), + ], + ), + ), + ), + ); + } + + Widget _badgeHadir(String? status) { + String text = status ?? "Belum Absen"; + Color badgeColor; + + if (text.toLowerCase() == "hadir") { + badgeColor = Colors.greenAccent[700]!; + } else if (text.toLowerCase() == "tidak hadir") { + badgeColor = Colors.redAccent; + } else { + badgeColor = Colors.orangeAccent; + } + + return Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + decoration: BoxDecoration( + color: badgeColor.withOpacity(0.3), + borderRadius: BorderRadius.circular(20), + border: Border.all(color: Colors.white, width: 1), + ), + child: Text( + text.toUpperCase(), + style: GoogleFonts.poppins( + fontSize: 10, fontWeight: FontWeight.bold, color: Colors.white), + ), + ); + } + + Widget _rowWhite(String label, String value) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: 100, + child: Text(label, + style: GoogleFonts.poppins( + color: Colors.white, + fontSize: 12, + fontWeight: FontWeight.w600))), + Text(" : ", + style: GoogleFonts.poppins(color: Colors.white, fontSize: 12)), + Expanded( + child: Text(value, + style: + GoogleFonts.poppins(color: Colors.white, fontSize: 12))), + ], + ), + ); + } + + Widget _rowGizi(String label, String value) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: 120, + child: Text(label, + style: GoogleFonts.poppins( + fontSize: 12, + fontWeight: FontWeight.w600, + color: Colors.grey[800]))), + const Text(" : ", style: TextStyle(fontSize: 12)), + Expanded( + child: Text(value, + style: + GoogleFonts.poppins(fontSize: 12, color: Colors.black))), + ], + ), + ); + } + + Widget _rowStatus(String label, Map balita) { + return Container( + margin: const EdgeInsets.symmetric(vertical: 5), + padding: const EdgeInsets.all(10), + decoration: BoxDecoration( + color: Colors.orange[50], borderRadius: BorderRadius.circular(8)), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text("$label :", + style: GoogleFonts.poppins( + fontSize: 12, + fontWeight: FontWeight.w600, + color: Colors.orange[900])), + const SizedBox(height: 4), + Padding( + padding: const EdgeInsets.only(left: 12), + child: Column( + children: [ + _rowStatusDetail("BB / U", balita["status_bbu"] ?? "-"), + _rowStatusDetail("TB / U", balita["status_tbu"] ?? "-"), + _rowStatusDetail("BB / TB", balita["status_bbtb"] ?? "-"), + ], + ), + ), + ], + ), + ); + } + + Widget _rowStatusDetail(String indikator, String nilai) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 2), + child: Row( + children: [ + SizedBox( + width: 65, + child: Text( + indikator, + style: GoogleFonts.poppins( + fontSize: 12, + fontWeight: FontWeight.w600, + color: Colors.orange[900]), + ), + ), + Text( + " : ", + style: GoogleFonts.poppins( + fontSize: 12, + fontWeight: FontWeight.w600, + color: Colors.orange[900]), + ), + Expanded( + child: Text( + nilai, + style: GoogleFonts.poppins( + fontSize: 12, + fontWeight: FontWeight.bold, + color: Colors.orange[900]), + ), + ), + ], + ), + ); + } + + Widget _smallButton( + IconData icon, String text, Color color, VoidCallback onPressed) { + return Expanded( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 2), + child: OutlinedButton.icon( + onPressed: onPressed, + icon: Icon(icon, size: 14, color: color), + label: Text(text, + style: GoogleFonts.poppins( + fontSize: 12, color: color, fontWeight: FontWeight.w500)), + style: OutlinedButton.styleFrom( + padding: const EdgeInsets.symmetric(vertical: 8), + side: BorderSide(color: color.withOpacity(0.5)), + shape: + RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), + ), + ), + ), + ); + } + + Widget _buildPagination(int totalPages) { + return Padding( + padding: const EdgeInsets.only(top: 8.0), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text("Halaman ${_currentPage + 1} dari $totalPages", + style: GoogleFonts.poppins(fontSize: 12)), + Row( + children: [ + IconButton( + icon: const Icon(Icons.chevron_left), + onPressed: _currentPage == 0 + ? null + : () => setState(() => _currentPage--)), + IconButton( + icon: const Icon(Icons.chevron_right), + onPressed: _currentPage >= totalPages - 1 + ? null + : () => setState(() => _currentPage++)), + ], + ), + ], + ), + ); + } +} diff --git a/lib/bidan/edukasi.dart b/lib/bidan/edukasi.dart new file mode 100644 index 0000000..f605e25 --- /dev/null +++ b/lib/bidan/edukasi.dart @@ -0,0 +1,511 @@ +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:http/http.dart' as http; +import 'package:flutter_quill/flutter_quill.dart' as quill; + +// Import Halaman CRUD +import '../bidan/crud_edukasi/tambah_edukasi_balita.dart'; +import '../bidan/crud_edukasi/tambah_edukasi_ibu_hamil.dart'; +import '../bidan/crud_edukasi/edit_edukasi_balita.dart'; +import '../bidan/crud_edukasi/edit_edukasi_ibu_hamil.dart'; + +// Import Dashboard Bidan agar navigasi berfungsi +import '../bidan/dashboard_bidan.dart'; +import '../layout/main_layout.dart'; +import 'bidan_drawer.dart'; + +class DataEdukasiPage extends StatefulWidget { + const DataEdukasiPage({super.key}); + + @override + State createState() => _DataEdukasiPageState(); +} + +class _DataEdukasiPageState extends State { + // Base URL untuk API + final String baseUrlBalita = + "http://ta.myhost.id/E31230549/mposyandu_api/edukasi_balita/"; + final String baseUrlIbu = + "http://ta.myhost.id/E31230549/mposyandu_api/edukasi_ibu_hamil/"; + + // Base URL untuk Gambar - Mengarah ke hosting bukan localhost + final String baseImageUrl = + "http://ta.myhost.id/E31230549/mposyandu_api/upload/edukasi/"; + + List balitaList = []; + List ibuList = []; + List filteredBalita = []; + List filteredIbu = []; + bool isLoading = true; + + int _currentBalitaPage = 0; + int _currentIbuPage = 0; + final int _rowsPerPage = 5; + + final searchBalitaController = TextEditingController(); + final searchIbuController = TextEditingController(); + + @override + void initState() { + super.initState(); + loadAllData(); + + searchBalitaController.addListener(() { + filterBalita(searchBalitaController.text); + }); + + searchIbuController.addListener(() { + filterIbu(searchIbuController.text); + }); + } + + Future loadAllData() async { + setState(() => isLoading = true); + await loadBalita(); + await loadIbu(); + setState(() => isLoading = false); + } + + Future loadBalita() async { + try { + var response = + await http.get(Uri.parse("${baseUrlBalita}get_edukasi_balita.php")); + var data = jsonDecode(response.body); + if (data["success"]) { + setState(() { + balitaList = data["data"]; + filteredBalita = balitaList; + }); + } + } catch (e) { + debugPrint("Error Load Balita: $e"); + } + } + + Future loadIbu() async { + try { + var response = + await http.get(Uri.parse("${baseUrlIbu}get_edukasi_ibu_hamil.php")); + var data = jsonDecode(response.body); + if (data["success"]) { + setState(() { + ibuList = data["data"]; + filteredIbu = ibuList; + }); + } + } catch (e) { + debugPrint("Error Load Ibu: $e"); + } + } + + void filterBalita(String query) { + setState(() { + filteredBalita = balitaList + .where((item) => + item["judul"].toLowerCase().contains(query.toLowerCase())) + .toList(); + _currentBalitaPage = 0; + }); + } + + void filterIbu(String query) { + setState(() { + filteredIbu = ibuList + .where((item) => + item["judul"].toLowerCase().contains(query.toLowerCase())) + .toList(); + _currentIbuPage = 0; + }); + } + + Future hapusData(String id, String type) async { + String url = type == "balita" + ? "${baseUrlBalita}hapus_edukasi_balita.php" + : "${baseUrlIbu}hapus_edukasi_ibu_hamil.php"; + + try { + var response = await http.post(Uri.parse(url), body: {"id": id}); + var data = jsonDecode(response.body); + if (data["status"] == "success") { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text("Data berhasil dihapus"))); + loadAllData(); + } + } catch (e) { + debugPrint("Error Hapus: $e"); + } + } + + void confirmDelete(String id, String type) { + showDialog( + context: context, + builder: (_) => AlertDialog( + title: const Text("Konfirmasi"), + content: const Text("Yakin ingin menghapus data ini?"), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text("Batal")), + TextButton( + onPressed: () { + Navigator.pop(context); + hapusData(id, type); + }, + child: const Text("Hapus", style: TextStyle(color: Colors.red)), + ), + ], + ), + ); + } + + Widget buildDescriptionCell(String? description) { + String cleanText = description ?? ""; + if (cleanText.startsWith('[') && cleanText.endsWith(']')) { + try { + final List json = jsonDecode(cleanText); + final doc = quill.Document.fromJson(json); + cleanText = doc.toPlainText().trim(); + } catch (e) { + debugPrint("Gagal parsing JSON deskripsi: $e"); + } + } + + return Padding( + padding: const EdgeInsets.symmetric(vertical: 12), + child: SizedBox( + width: 300, + child: Text( + cleanText, + style: GoogleFonts.poppins(fontSize: 12, height: 1.5), + softWrap: true, + maxLines: 4, + overflow: TextOverflow.ellipsis, + ), + ), + ); + } + + List getPaginatedData(List data, int currentPage) { + int start = currentPage * _rowsPerPage; + int end = start + _rowsPerPage; + if (start >= data.length) return []; + return data.sublist(start, end > data.length ? data.length : end); + } + + @override + Widget build(BuildContext context) { + return PopScope( + canPop: false, + onPopInvokedWithResult: (didPop, result) async { + if (didPop) return; + + // ✅ FIX FINAL: selalu kembali ke Dashboard Bidan + Navigator.pushAndRemoveUntil( + context, + MaterialPageRoute( + builder: (_) => const DashboardBidanPage(), + ), + (route) => false, + ); + }, + child: MainLayout( + title: "", + drawer: const BidanDrawer(), + body: isLoading + ? const Center(child: CircularProgressIndicator()) + : RefreshIndicator( + onRefresh: loadAllData, + child: SingleChildScrollView( + padding: const EdgeInsets.symmetric(vertical: 20), + child: Column( + children: [ + sectionBalita(), + const SizedBox(height: 40), + sectionIbu(), + ], + ), + ), + ), + ), + ); + } + + Widget sectionBalita() { + int totalPages = (filteredBalita.length / _rowsPerPage).ceil(); + if (totalPages == 0) totalPages = 1; + + return Column( + children: [ + title("Edukasi Balita"), + const SizedBox(height: 15), + searchAndAddRow( + controller: searchBalitaController, + hint: "Cari Judul Edukasi Balita...", + onAdd: () async { + await Navigator.push( + context, + MaterialPageRoute( + builder: (_) => const TambahEdukasiBalitaPage())); + loadBalita(); + }, + ), + const SizedBox(height: 20), + tableData( + data: getPaginatedData(filteredBalita, _currentBalitaPage), + type: "balita", + ), + paginationControls(_currentBalitaPage, totalPages, + (i) => setState(() => _currentBalitaPage = i)), + ], + ); + } + + Widget sectionIbu() { + int totalPages = (filteredIbu.length / _rowsPerPage).ceil(); + if (totalPages == 0) totalPages = 1; + + return Column( + children: [ + title("Edukasi Ibu Hamil"), + const SizedBox(height: 15), + searchAndAddRow( + controller: searchIbuController, + hint: "Cari Judul Edukasi Ibu...", + onAdd: () async { + await Navigator.push( + context, + MaterialPageRoute( + builder: (_) => const TambahEdukasiBumilPage())); + loadIbu(); + }, + ), + const SizedBox(height: 20), + tableData( + data: getPaginatedData(filteredIbu, _currentIbuPage), + type: "ibu", + ), + paginationControls(_currentIbuPage, totalPages, + (i) => setState(() => _currentIbuPage = i)), + ], + ); + } + + Widget searchAndAddRow({ + required TextEditingController controller, + required String hint, + required VoidCallback onAdd, + }) { + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + searchField(controller, hint), + const SizedBox(height: 12), + Align( + alignment: Alignment.centerRight, + child: addBtn(onAdd), + ), + ], + ), + ); + } + + Widget tableData({required List data, required String type}) { + return Center( + child: Container( + constraints: const BoxConstraints(maxWidth: 1000), + padding: const EdgeInsets.symmetric(horizontal: 16), + child: tableCard( + headers: const ["Gambar", "Judul", "Deskripsi", "Aksi"], + rows: data + .map((e) => [ + imagePreview(e), + SizedBox( + width: 120, + child: Text(e["judul"] ?? "", + style: GoogleFonts.poppins(fontSize: 13))), + buildDescriptionCell(e["deskripsi"]), + actionButtons(e, type) + ]) + .toList(), + ), + ), + ); + } + + Widget imagePreview(Map item) { + String? fileName = item["gambar"]; + + if (fileName == null || fileName.isEmpty) { + return const Icon(Icons.image_not_supported, + color: Colors.grey, size: 40); + } + + String fullUrl = "$baseImageUrl$fileName"; + + return ClipRRect( + borderRadius: BorderRadius.circular(8), + child: Image.network( + fullUrl, + width: 60, + height: 60, + fit: BoxFit.cover, + errorBuilder: (context, error, stackTrace) { + return Container( + width: 60, + height: 60, + color: Colors.grey.shade200, + child: const Icon(Icons.broken_image, color: Colors.red, size: 30), + ); + }, + ), + ); + } + + Widget title(String text) { + return Text(text, + style: GoogleFonts.poppins(fontSize: 18, fontWeight: FontWeight.bold)); + } + + Widget searchField(TextEditingController controller, String hint) { + return TextField( + controller: controller, + style: GoogleFonts.poppins(fontSize: 13), + decoration: InputDecoration( + hintText: hint, + prefixIcon: const Icon(Icons.search, size: 20), + contentPadding: const EdgeInsets.symmetric(vertical: 15), + border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)), + filled: true, + fillColor: Colors.white, + ), + ); + } + + Widget addBtn(VoidCallback onTap) { + return SizedBox( + height: 45, + child: OutlinedButton.icon( + onPressed: onTap, + style: OutlinedButton.styleFrom( + side: const BorderSide(color: Colors.blue), + shape: + RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), + ), + icon: const Icon(Icons.add, size: 18, color: Colors.blue), + label: Text("Tambah", + style: GoogleFonts.poppins( + fontSize: 13, color: Colors.blue, fontWeight: FontWeight.bold)), + ), + ); + } + + Widget tableCard({ + required List headers, + required List> rows, + }) { + return Container( + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(15), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.05), + blurRadius: 10, + offset: const Offset(0, 4), + ) + ], + ), + child: ClipRRect( + borderRadius: BorderRadius.circular(15), + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: DataTable( + headingRowColor: MaterialStateProperty.all(Colors.blue), + dataRowMaxHeight: 100, + dataRowMinHeight: 70, + columnSpacing: 15, + columns: headers + .map((h) => DataColumn( + label: Text(h, + style: GoogleFonts.poppins( + color: Colors.white, + fontWeight: FontWeight.bold, + fontSize: 13)))) + .toList(), + rows: rows + .map((row) => DataRow( + cells: row.map((cell) { + if (cell is Widget) return DataCell(cell); + return DataCell(Text(cell.toString(), + style: GoogleFonts.poppins(fontSize: 12))); + }).toList())) + .toList(), + ), + ), + ), + ); + } + + Widget paginationControls( + int currentPage, int totalPages, Function(int) onPageChanged) { + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 15), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + "Halaman ${currentPage + 1} dari $totalPages", + style: GoogleFonts.poppins(fontSize: 12, color: Colors.black54), + ), + Row( + children: [ + IconButton( + icon: const Icon(Icons.chevron_left), + onPressed: currentPage == 0 + ? null + : () => onPageChanged(currentPage - 1), + ), + IconButton( + icon: const Icon(Icons.chevron_right), + onPressed: currentPage >= totalPages - 1 + ? null + : () => onPageChanged(currentPage + 1), + ), + ], + ), + ], + ), + ); + } + + Widget actionButtons(Map data, String type) { + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + IconButton( + icon: const Icon(Icons.edit, color: Colors.orange, size: 18), + onPressed: () async { + if (type == "balita") { + await Navigator.push( + context, + MaterialPageRoute( + builder: (_) => EditEdukasiBalitaPage(data: data))); + loadBalita(); + } else { + await Navigator.push( + context, + MaterialPageRoute( + builder: (_) => EditEdukasiBumilPage(data: data))); + loadIbu(); + } + }), + IconButton( + icon: const Icon(Icons.delete, color: Colors.red, size: 18), + onPressed: () => confirmDelete(data["id"].toString(), type)), + ], + ); + } +} diff --git a/lib/bidan/imunisasi.dart b/lib/bidan/imunisasi.dart new file mode 100644 index 0000000..9188123 --- /dev/null +++ b/lib/bidan/imunisasi.dart @@ -0,0 +1,433 @@ +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:http/http.dart' as http; + +import '../layout/main_layout.dart'; +import 'bidan_drawer.dart'; +// Import file crud +import '../bidan/crud_imunisasi/tambah_imunisasi.dart'; +import '../bidan/crud_imunisasi/edit_imunisasi.dart'; +import '../bidan/crud_imunisasi/data_imunisasi_balita.dart'; +// Import Dashboard Bidan agar navigasi berfungsi +import '../bidan/dashboard_bidan.dart'; + +class DataImunisasiPage extends StatefulWidget { + const DataImunisasiPage({super.key}); + + @override + State createState() => _DataImunisasiPageState(); +} + +class _DataImunisasiPageState extends State { + List masterImunisasi = []; + String _searchQuery = ""; + bool isLoading = true; + + // Variabel Pagination + int _currentPage = 0; + final int _rowsPerPage = 10; + + // Endpoint API + final String baseMaster = + "http://ta.myhost.id/E31230549/mposyandu_api/imunisasi/get_master_imunisasi.php"; + final String urlDelete = + "http://ta.myhost.id/E31230549/mposyandu_api/imunisasi/hapus_imunisasi.php"; + + @override + void initState() { + super.initState(); + fetchMasterData(); + } + + Future fetchMasterData() async { + try { + final resMaster = await http.get(Uri.parse(baseMaster)); + if (mounted) { + setState(() { + masterImunisasi = jsonDecode(resMaster.body)["data"] ?? []; + isLoading = false; + }); + } + } catch (e) { + if (mounted) setState(() => isLoading = false); + } + } + + Future _deleteData(String id) async { + try { + final response = await http.post( + Uri.parse(urlDelete), + body: {"id": id}, + ); + final data = jsonDecode(response.body); + + if (data['status'] == 'success') { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(data['message'] ?? "Data berhasil dihapus"), + backgroundColor: Colors.blue, + ), + ); + fetchMasterData(); + } else { + throw data['message'] ?? "Gagal menghapus data"; + } + } catch (e) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text("Kesalahan: $e"), backgroundColor: Colors.red), + ); + } + } + + void _showDeleteDialog(Map item) { + showDialog( + context: context, + builder: (context) => AlertDialog( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)), + title: Text("Konfirmasi Hapus", + style: + GoogleFonts.poppins(fontWeight: FontWeight.bold, fontSize: 16)), + content: Text( + "Apakah Anda yakin ingin menghapus '${item['nama_imunisasi']}'?", + style: GoogleFonts.poppins(fontSize: 13)), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: + Text("Batal", style: GoogleFonts.poppins(color: Colors.grey)), + ), + OutlinedButton( + onPressed: () { + Navigator.pop(context); + _deleteData(item['id'].toString()); + }, + style: OutlinedButton.styleFrom( + side: const BorderSide(color: Colors.red), + shape: const StadiumBorder(), + ), + child: Text("Hapus", + style: GoogleFonts.poppins( + color: Colors.red, fontWeight: FontWeight.bold)), + ), + ], + ), + ); + } + + List get _filteredMaster { + return masterImunisasi.where((item) { + final nama = item["nama_imunisasi"].toString().toLowerCase(); + final ket = item["keterangan"].toString().toLowerCase(); + final query = _searchQuery.toLowerCase(); + return nama.contains(query) || ket.contains(query); + }).toList(); + } + + List get _paginatedData { + final start = _currentPage * _rowsPerPage; + final end = start + _rowsPerPage; + if (start >= _filteredMaster.length) return []; + return _filteredMaster.sublist( + start, + end > _filteredMaster.length ? _filteredMaster.length : end, + ); + } + + @override + Widget build(BuildContext context) { + final totalPages = (_filteredMaster.length / _rowsPerPage).ceil() == 0 + ? 1 + : (_filteredMaster.length / _rowsPerPage).ceil(); + + return PopScope( + canPop: false, + onPopInvokedWithResult: (didPop, result) async { + if (didPop) return; + Navigator.pushAndRemoveUntil( + context, + MaterialPageRoute(builder: (_) => const DashboardBidanPage()), + (route) => false, + ); + }, + child: MainLayout( + title: "", + drawer: const BidanDrawer(), + body: isLoading + ? const Center(child: CircularProgressIndicator()) + : Column( + children: [ + Expanded( + child: SingleChildScrollView( + padding: const EdgeInsets.all(16), + child: Column( + children: [ + Text( + "Data Jenis Imunisasi", + style: GoogleFonts.poppins( + fontSize: 18, fontWeight: FontWeight.bold), + ), + const SizedBox(height: 15), + + // --- INPUT CARI --- + Center( + child: Container( + constraints: const BoxConstraints(maxWidth: 850), + child: TextField( + onChanged: (value) => setState(() { + _searchQuery = value; + _currentPage = 0; + }), + style: GoogleFonts.poppins(fontSize: 12), + decoration: InputDecoration( + hintText: "Cari nama atau keterangan...", + hintStyle: GoogleFonts.poppins(fontSize: 12), + prefixIcon: + const Icon(Icons.search, size: 20), + filled: true, + fillColor: Colors.grey[50], + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: + BorderSide(color: Colors.grey[300]!), + ), + contentPadding: + const EdgeInsets.symmetric(vertical: 8), + ), + ), + ), + ), + const SizedBox(height: 20), + + // --- TABEL DENGAN DATATABLE --- + Center( + child: Container( + constraints: const BoxConstraints(maxWidth: 850), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.05), + blurRadius: 10, + offset: const Offset(0, 4), + ), + ], + ), + child: ClipRRect( + borderRadius: BorderRadius.circular(12), + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: DataTable( + headingRowColor: + MaterialStateProperty.all(Colors.blue), + columnSpacing: 25, + columns: [ + _buildDataColumn("Nama Imunisasi"), + _buildDataColumn("Min"), + _buildDataColumn("Max"), + _buildDataColumn("Keterangan"), + _buildDataColumn("Aksi"), + ], + rows: _paginatedData.isEmpty + ? [ + DataRow(cells: [ + DataCell(Text( + "Data tidak ditemukan", + style: GoogleFonts.poppins( + fontSize: 12))), + const DataCell(SizedBox()), + const DataCell(SizedBox()), + const DataCell(SizedBox()), + const DataCell(SizedBox()), + ]) + ] + : _paginatedData.map((item) { + return DataRow(cells: [ + DataCell(Text( + item["nama_imunisasi"] ?? "-", + style: GoogleFonts.poppins( + fontSize: 12))), + DataCell(Text( + "${item["usia_min"]} Bln", + style: GoogleFonts.poppins( + fontSize: 12))), + DataCell(Text( + "${item["usia_max"]} Bln", + style: GoogleFonts.poppins( + fontSize: 12))), + DataCell( + Container( + constraints: + const BoxConstraints( + maxWidth: 180), + child: Text( + item["keterangan"] ?? "-", + style: GoogleFonts.poppins( + fontSize: 12), + overflow: + TextOverflow.ellipsis, + maxLines: 2, + ), + ), + ), + DataCell( + Row( + children: [ + IconButton( + icon: const Icon( + Icons.edit, + color: Colors.orange, + size: 20), + onPressed: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => + EditImunisasiPage( + data: item), + ), + ).then((value) { + if (value == true) + fetchMasterData(); + }); + }, + ), + IconButton( + icon: const Icon( + Icons.delete, + color: Colors.red, + size: 20), + onPressed: () => + _showDeleteDialog( + item), + ), + ], + ), + ), + ]); + }).toList(), + ), + ), + ), + ), + ), + + const SizedBox(height: 25), + + // --- BUTTON ACTION --- + Center( + child: Container( + constraints: const BoxConstraints(maxWidth: 850), + child: Row( + children: [ + Expanded( + child: _actionBtnLonjong( + Icons.add, "Tambah Jenis", Colors.blue, + () { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => + const TambahImunisasiPage(), + ), + ).then((_) => fetchMasterData()); + }), + ), + const SizedBox(width: 12), + Expanded( + child: _actionBtnLonjong( + Icons.visibility, + "Imunisasi Balita", + Colors.deepPurple, () { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => + const DataImunisasiBalitaPage(), + ), + ); + }), + ), + ], + ), + ), + ), + ], + ), + ), + ), + + // --- PAGINATION --- + Container( + width: double.infinity, + color: Colors.white, + padding: const EdgeInsets.symmetric( + horizontal: 20, vertical: 10), + decoration: BoxDecoration( + border: Border(top: BorderSide(color: Colors.grey[200]!)), + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text("Halaman ${_currentPage + 1} dari $totalPages", + style: GoogleFonts.poppins( + fontSize: 12, fontWeight: FontWeight.w500)), + Row( + children: [ + IconButton( + icon: const Icon(Icons.chevron_left), + onPressed: _currentPage == 0 + ? null + : () => setState(() => _currentPage--), + ), + IconButton( + icon: const Icon(Icons.chevron_right), + onPressed: _currentPage >= totalPages - 1 + ? null + : () => setState(() => _currentPage++), + ), + ], + ), + ], + ), + ), + ], + ), + ), + ); + } + + DataColumn _buildDataColumn(String label) { + return DataColumn( + label: Text( + label, + style: GoogleFonts.poppins( + color: Colors.white, + fontWeight: FontWeight.bold, + fontSize: 13, + ), + ), + ); + } + + Widget _actionBtnLonjong( + IconData icon, String label, Color color, VoidCallback onTap) { + return OutlinedButton.icon( + onPressed: onTap, + icon: Icon(icon, size: 18, color: color), + style: OutlinedButton.styleFrom( + side: BorderSide(color: color, width: 1.5), + shape: const StadiumBorder(), + padding: const EdgeInsets.symmetric(vertical: 14), + ), + label: Text( + label, + style: GoogleFonts.poppins( + fontSize: 12, color: color, fontWeight: FontWeight.bold), + ), + ); + } +} diff --git a/lib/bidan/jadwal_anc.dart b/lib/bidan/jadwal_anc.dart new file mode 100644 index 0000000..f4e46a7 --- /dev/null +++ b/lib/bidan/jadwal_anc.dart @@ -0,0 +1,545 @@ +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:intl/intl.dart'; +import 'package:http/http.dart' as http; +import 'dart:convert'; +import '../layout/main_layout.dart'; +import '../bidan/bidan_drawer.dart'; +// Import Dashboard Bidan agar navigasi PopScope berfungsi +import '../bidan/dashboard_bidan.dart'; + +class JadwalAncPage extends StatefulWidget { + const JadwalAncPage({super.key}); + + @override + State createState() => _JadwalAncPageState(); +} + +class _JadwalAncPageState extends State { + final TextEditingController _dateController = TextEditingController(); + final TextEditingController _timeController = TextEditingController(); + final TextEditingController _locationController = TextEditingController(); + final TextEditingController _noteController = TextEditingController(); + final TextEditingController _searchController = TextEditingController(); + + List _allJadwal = []; + List _filteredJadwal = []; + bool _isLoading = false; + bool _isFetching = true; + + int _currentPage = 1; + final int _itemsPerPage = 10; + + @override + void initState() { + super.initState(); + _loadData(); + } + + Future _loadData() async { + setState(() => _isFetching = true); + try { + final response = await http.get(Uri.parse( + "http://ta.myhost.id/E31230549/mposyandu_api/jadwal_anc/get_jadwal_anc.php")); + if (response.statusCode == 200) { + final data = jsonDecode(response.body); + setState(() { + _allJadwal = data['status'] == 'success' ? data['data'] : []; + _filteredJadwal = _allJadwal; + _isFetching = false; + }); + } + } catch (e) { + setState(() => _isFetching = false); + } + } + + void _filterJadwal(String query) { + setState(() { + _filteredJadwal = _allJadwal.where((item) { + final trimester = item['trimester_target'].toString().toLowerCase(); + final tanggal = item['tanggal_periksa'].toString().toLowerCase(); + return trimester.contains(query.toLowerCase()) || + tanggal.contains(query.toLowerCase()); + }).toList(); + _currentPage = 1; + }); + } + + Future _hapusJadwal(String id) async { + final response = await http.post( + Uri.parse( + "http://ta.myhost.id/E31230549/mposyandu_api/jadwal_anc/hapus_jadwal_anc.php"), + body: {"id_jadwal": id}, + ); + final data = jsonDecode(response.body); + if (data['status'] == 'success') { + _loadData(); + _showSnackBar("Jadwal berhasil dihapus", Colors.red); + } + } + + Future _simpanAtauUpdateJadwal(String trimester, + {String? idJadwal}) async { + if (_dateController.text.isEmpty || + _locationController.text.isEmpty || + _timeController.text.isEmpty) { + _showErrorSnackBar("Harap isi semua field!"); + return; + } + setState(() => _isLoading = true); + + String url = idJadwal == null + ? "http://ta.myhost.id/E31230549/mposyandu_api/jadwal_anc/tambah_jadwal_anc.php" + : "http://ta.myhost.id/E31230549/mposyandu_api/jadwal_anc/update_jadwal_anc.php"; + + Map body = { + "trimester_target": trimester, + "tanggal_periksa": _dateController.text, + "jam_periksa": _timeController.text, + "lokasi": _locationController.text, + "catatan": _noteController.text, + }; + if (idJadwal != null) body["id_jadwal"] = idJadwal; + + try { + final response = await http.post(Uri.parse(url), body: body); + final data = jsonDecode(response.body); + if (data['status'] == 'success') { + _clearForm(); + if (!mounted) return; + Navigator.pop(context); + _loadData(); + _showSnackBar(data['message'], Colors.green); + } + } catch (e) { + _showErrorSnackBar("Error: $e"); + } finally { + setState(() => _isLoading = false); + } + } + + void _tampilkanFormJadwal(String trimester, + {Map? editItem}) { + if (editItem != null) { + _dateController.text = editItem['tanggal_periksa']; + _timeController.text = editItem['jam_periksa']; + _locationController.text = editItem['lokasi']; + _noteController.text = editItem['catatan_bidan'] ?? ""; + } else { + _dateController.text = DateFormat('yyyy-MM-dd').format(DateTime.now()); + _timeController.clear(); + _locationController.clear(); + _noteController.clear(); + } + + showModalBottomSheet( + context: context, + isScrollControlled: true, + backgroundColor: Colors.transparent, + builder: (context) => Center( + child: Container( + constraints: const BoxConstraints(maxWidth: 450), + margin: const EdgeInsets.all(20), + decoration: BoxDecoration( + color: Colors.white, borderRadius: BorderRadius.circular(20)), + padding: EdgeInsets.only( + bottom: MediaQuery.of(context).viewInsets.bottom + 20, + left: 20, + right: 20, + top: 20), + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + editItem == null + ? "Tambah Jadwal $trimester" + : "Edit Jadwal $trimester", + style: GoogleFonts.poppins( + fontSize: 16, + fontWeight: FontWeight.bold, + color: MainLayout.mainColor)), + const SizedBox(height: 15), + _buildTextField( + "Tanggal", Icons.calendar_today, _dateController, + isDate: true), + const SizedBox(height: 10), + _buildTextField("Jam", Icons.access_time, _timeController, + isTime: true), + const SizedBox(height: 10), + _buildTextField( + "Lokasi", Icons.location_on, _locationController), + const SizedBox(height: 10), + _buildTextField("Catatan", Icons.event_note, _noteController, + maxLines: 2), + const SizedBox(height: 20), + Row( + children: [ + Expanded( + child: OutlinedButton( + onPressed: () { + _clearForm(); + Navigator.pop(context); + }, + child: const Text("Batal"))), + const SizedBox(width: 10), + Expanded( + flex: 2, + child: ElevatedButton( + style: ElevatedButton.styleFrom( + backgroundColor: MainLayout.mainColor), + onPressed: _isLoading + ? null + : () => _simpanAtauUpdateJadwal(trimester, + idJadwal: editItem?['id_jadwal']), + child: _isLoading + ? const CircularProgressIndicator( + color: Colors.white) + : const Text("Simpan", + style: TextStyle(color: Colors.white)))), + ], + ), + ], + ), + ), + ), + ), + ); + } + + void _clearForm() { + _dateController.clear(); + _timeController.clear(); + _locationController.clear(); + _noteController.clear(); + } + + @override + Widget build(BuildContext context) { + int totalPages = (_filteredJadwal.length / _itemsPerPage).ceil(); + if (totalPages == 0) totalPages = 1; + final startIndex = (_currentPage - 1) * _itemsPerPage; + final pagedJadwal = + _filteredJadwal.skip(startIndex).take(_itemsPerPage).toList(); + + return PopScope( + canPop: false, + onPopInvokedWithResult: (didPop, result) async { + if (didPop) return; + + // FIX FINAL: selalu kembali ke Dashboard Bidan + Navigator.pushAndRemoveUntil( + context, + MaterialPageRoute( + builder: (_) => const DashboardBidanPage(), + ), + (route) => false, + ); + }, + child: Scaffold( + appBar: AppBar( + backgroundColor: MainLayout.mainColor, + elevation: 0, + iconTheme: const IconThemeData(color: Colors.white)), + drawer: const BidanDrawer(), + body: SingleChildScrollView( + padding: const EdgeInsets.all(20), + child: Column( + children: [ + _headerSection(), + const SizedBox(height: 20), + Center( + child: Wrap( + spacing: 15, + runSpacing: 15, + children: [ + _buildCompactControlCard( + "Trimester 1", Colors.blue.shade600, Icons.looks_one), + _buildCompactControlCard( + "Trimester 2", Colors.teal.shade600, Icons.looks_two), + _buildCompactControlCard( + "Trimester 3", Colors.orange.shade700, Icons.looks_3), + ], + ), + ), + const SizedBox(height: 40), + Text("Data Jadwal", + style: GoogleFonts.poppins( + fontSize: 18, fontWeight: FontWeight.bold)), + const SizedBox(height: 20), + SizedBox( + width: double.infinity, + child: TextField( + controller: _searchController, + onChanged: _filterJadwal, + style: GoogleFonts.poppins(color: Colors.black, fontSize: 14), + decoration: InputDecoration( + hintText: "Cari Trimester atau Tanggal...", + hintStyle: + GoogleFonts.poppins(fontSize: 13, color: Colors.grey), + prefixIcon: Icon(Icons.search, color: Colors.grey.shade700), + filled: true, + fillColor: Colors.white, + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: BorderSide(color: Colors.grey.shade300)), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: BorderSide(color: Colors.grey.shade300)), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: const BorderSide( + color: MainLayout.mainColor, width: 2)), + ), + ), + ), + const SizedBox(height: 20), + _isFetching + ? const Center(child: CircularProgressIndicator()) + : ListView.builder( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + itemCount: pagedJadwal.length, + itemBuilder: (context, index) => + _buildResultCard(pagedJadwal[index]), + ), + const SizedBox(height: 20), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text("Halaman $_currentPage dari $totalPages", + style: GoogleFonts.poppins( + fontSize: 12, color: Colors.black)), + Row( + children: [ + IconButton( + icon: const Icon(Icons.arrow_back_ios, + size: 16, color: Colors.black), + onPressed: _currentPage > 1 + ? () => setState(() => _currentPage--) + : null, + ), + IconButton( + icon: const Icon(Icons.arrow_forward_ios, + size: 16, color: Colors.black), + onPressed: _currentPage < totalPages + ? () => setState(() => _currentPage++) + : null, + ), + ], + ), + ], + ), + ], + ), + ), + ), + ); + } + + Widget _buildResultCard(Map item) { + return Card( + margin: const EdgeInsets.only(bottom: 12), + color: Colors.white, + elevation: 0.5, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(15), + side: BorderSide(color: Colors.grey.shade200, width: 1), + ), + child: Padding( + padding: const EdgeInsets.all(16.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text(item['trimester_target'], + style: GoogleFonts.poppins( + fontWeight: FontWeight.bold, + color: MainLayout.mainColor, + fontSize: 15)), + Row( + children: [ + IconButton( + icon: const Icon(Icons.edit, + color: Colors.orange, size: 20), + onPressed: () => _tampilkanFormJadwal( + item['trimester_target'], + editItem: item)), + IconButton( + icon: + const Icon(Icons.delete, color: Colors.red, size: 20), + onPressed: () => + _showDeleteDialog(item['id_jadwal'].toString()), + ), + ], + ), + ], + ), + const Divider(), + _infoRow("Tanggal", item['tanggal_periksa']), + _infoRow("Jam", item['jam_periksa']), + _infoRow("Lokasi", item['lokasi']), + if (item['catatan_bidan'] != null && item['catatan_bidan'] != "") + _infoRow("Catatan", item['catatan_bidan']), + ], + ), + ), + ); + } + + Widget _infoRow(String label, String value) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 3), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: 70, + child: Text(label, + style: GoogleFonts.poppins( + fontSize: 12, + fontWeight: FontWeight.bold, + color: Colors.black)), + ), + Text(": ", + style: GoogleFonts.poppins( + fontSize: 12, + fontWeight: FontWeight.bold, + color: Colors.black)), + Expanded( + child: Text(value, + style: GoogleFonts.poppins(fontSize: 12, color: Colors.black)), + ), + ], + ), + ); + } + + void _showDeleteDialog(String id) { + showDialog( + context: context, + builder: (context) => AlertDialog( + title: Text("Hapus Jadwal?", + style: GoogleFonts.poppins(fontWeight: FontWeight.bold)), + content: Text("Data ini akan dihapus permanen.", + style: GoogleFonts.poppins()), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text("Batal")), + TextButton( + onPressed: () { + Navigator.pop(context); + _hapusJadwal(id); + }, + child: const Text("Hapus", style: TextStyle(color: Colors.red))), + ], + ), + ); + } + + Widget _buildCompactControlCard( + String trimester, Color color, IconData icon) { + return Container( + width: 140, + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12), + border: Border.all(color: color.withOpacity(0.3))), + child: Column( + children: [ + Icon(icon, color: color, size: 28), + const SizedBox(height: 5), + Text(trimester, + style: GoogleFonts.poppins( + fontSize: 11, + fontWeight: FontWeight.bold, + color: Colors.black)), + const SizedBox(height: 10), + ElevatedButton( + style: ElevatedButton.styleFrom( + backgroundColor: color, + padding: EdgeInsets.zero, + minimumSize: const Size(80, 30)), + onPressed: () => _tampilkanFormJadwal(trimester), + child: const Text("Buat", + style: TextStyle( + fontSize: 11, + color: Colors.white, + fontWeight: FontWeight.bold)), + ) + ], + ), + ); + } + + Widget _headerSection() { + return Column(children: [ + Center( + child: Text("Manajemen Jadwal ANC", + style: GoogleFonts.poppins( + fontSize: 18, + fontWeight: FontWeight.bold, + color: Colors.black))), + Center( + child: Text("Kelola pemeriksaan rutin berdasarkan trimester.", + style: GoogleFonts.poppins(fontSize: 12, color: Colors.black54))), + ]); + } + + Widget _buildTextField( + String label, IconData icon, TextEditingController controller, + {bool isDate = false, bool isTime = false, int maxLines = 1}) { + return TextField( + controller: controller, + readOnly: isDate || isTime, + maxLines: maxLines, + style: GoogleFonts.poppins(color: Colors.black, fontSize: 14), + decoration: InputDecoration( + labelText: label, + labelStyle: GoogleFonts.poppins(fontSize: 13, color: Colors.black87), + prefixIcon: Icon(icon, size: 18, color: MainLayout.mainColor), + filled: true, + fillColor: Colors.grey.shade50, + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: BorderSide(color: Colors.grey.shade300)), + ), + onTap: () { + if (isDate) _selectDate(context); + if (isTime) _selectTime(context); + }, + ); + } + + Future _selectDate(BuildContext context) async { + DateTime? picked = await showDatePicker( + context: context, + initialDate: DateTime.now(), + firstDate: DateTime.now(), + lastDate: DateTime(2100)); + if (picked != null) + setState( + () => _dateController.text = DateFormat('yyyy-MM-dd').format(picked)); + } + + Future _selectTime(BuildContext context) async { + TimeOfDay? picked = + await showTimePicker(context: context, initialTime: TimeOfDay.now()); + if (picked != null) + setState(() => _timeController.text = picked.format(context)); + } + + void _showSnackBar(String msg, Color color) { + ScaffoldMessenger.of(context).showSnackBar(SnackBar( + content: Text(msg), + backgroundColor: color, + behavior: SnackBarBehavior.floating)); + } + + void _showErrorSnackBar(String msg) => _showSnackBar(msg, Colors.red); +} diff --git a/lib/bidan/jadwal_posyandu.dart b/lib/bidan/jadwal_posyandu.dart new file mode 100644 index 0000000..d045d57 --- /dev/null +++ b/lib/bidan/jadwal_posyandu.dart @@ -0,0 +1,522 @@ +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:http/http.dart' as http; +import 'package:intl/intl.dart'; +import 'package:intl/date_symbol_data_local.dart'; + +import '../layout/main_layout.dart'; +import 'bidan_drawer.dart'; +import '../bidan/crud_jadwal/riwayat_jadwal_posyandu.dart'; +import '../bidan/crud_jadwal/edit_jadwal.dart'; +// Import Dashboard Bidan agar navigasi PopScope tidak error +import '../bidan/dashboard_bidan.dart'; + +const String baseUrl = "http://ta.myhost.id/E31230549/mposyandu_api"; + +class Dusun { + final int id; + final String nama; + Dusun({required this.id, required this.nama}); +} + +class Kader { + final int id; + final String nama; + final int dunsunId; + Kader({required this.id, required this.nama, required this.dunsunId}); +} + +class DataJadwalPosyanduPage extends StatefulWidget { + const DataJadwalPosyanduPage({super.key}); + + @override + State createState() => _DataJadwalPosyanduPageState(); +} + +class _DataJadwalPosyanduPageState extends State { + final _tanggalController = TextEditingController(); + final _jamMulaiController = TextEditingController(); + final _jamSelesaiController = TextEditingController(); + final _lokasiController = TextEditingController(); + final _keteranganController = TextEditingController(); + + List daftarDusun = []; + List daftarKader = []; + List dunsunDipilih = []; + List> _dataJadwalLokal = []; + bool _isLoading = false; + + @override + void initState() { + super.initState(); + initializeDateFormatting('id', null); + loadDusun(); + loadLatestJadwal(); + } + + String _formatTanggal(String? dateStr) { + if (dateStr == null || dateStr == "-" || dateStr.isEmpty) return "-"; + try { + DateTime dt = DateTime.parse(dateStr); + return DateFormat('dd MMMM yyyy', 'id').format(dt); + } catch (e) { + return dateStr; + } + } + + Future loadLatestJadwal() async { + try { + final res = await http + .get(Uri.parse("$baseUrl/jadwal_posyandu/get_latest_jadwal.php")); + if (res.statusCode == 200) { + final responseData = jsonDecode(res.body); + if (responseData['success'] == true && responseData['data'] != null) { + setState(() { + if (responseData['data'] is List) { + _dataJadwalLokal = + List>.from(responseData['data']); + } else { + _dataJadwalLokal = [responseData['data']]; + } + }); + } + } + } catch (e) { + debugPrint("Error load latest jadwal: $e"); + } + } + + Future loadDusun() async { + try { + final res = await http.get(Uri.parse("$baseUrl/dusun/get_dusun.php")); + if (res.statusCode == 200) { + final responseData = jsonDecode(res.body); + final List listData = responseData['data']; + setState(() { + daftarDusun = listData + .map((d) => Dusun( + id: int.parse(d['id'].toString()), + nama: d['nama_dusun'].toString(), + )) + .toList(); + }); + } + } catch (e) { + debugPrint("Error load dunsun: $e"); + } + } + + Future loadKaderByDusun() async { + if (dunsunDipilih.isEmpty) { + setState(() => daftarKader.clear()); + return; + } + final String ids = dunsunDipilih.join(","); + try { + final res = await http + .get(Uri.parse("$baseUrl/petugas/get_kader_by_dusun.php?ids=$ids")); + if (res.statusCode == 200) { + final responseData = jsonDecode(res.body); + final List listData = responseData['data'] ?? []; + setState(() { + daftarKader = listData + .map((k) => Kader( + id: int.parse(k['id'].toString()), + nama: k['nama'].toString(), + dunsunId: int.parse(k['dusun_id'].toString()), + )) + .toList(); + }); + } + } catch (e) { + debugPrint("Error load kader: $e"); + } + } + + Future _simpanJadwal() async { + if (_tanggalController.text.isEmpty || dunsunDipilih.isEmpty) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text("Lengkapi Tanggal dan Dusun!", + style: GoogleFonts.poppins(fontSize: 12))), + ); + return; + } + + setState(() => _isLoading = true); + try { + final response = await http.post( + Uri.parse("$baseUrl/jadwal_posyandu/tambah_jadwal.php"), + body: { + "bidan_id": "1", + "tanggal": _tanggalController.text, + "jam_mulai": _jamMulaiController.text, + "jam_selesai": _jamSelesaiController.text, + "lokasi": _lokasiController.text, + "keterangan": _keteranganController.text, + "dusun_ids": dunsunDipilih.join(","), + }, + ); + + final result = jsonDecode(response.body); + if (result['success']) { + loadLatestJadwal(); + setState(() { + _tanggalController.clear(); + _jamMulaiController.clear(); + _jamSelesaiController.clear(); + _lokasiController.clear(); + _keteranganController.clear(); + dunsunDipilih.clear(); + daftarKader.clear(); + }); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text("Jadwal Berhasil Disimpan", + style: GoogleFonts.poppins(fontSize: 12))), + ); + } + } catch (e) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text("Terjadi kesalahan: $e", + style: GoogleFonts.poppins(fontSize: 12))), + ); + } finally { + setState(() => _isLoading = false); + } + } + + InputDecoration _input(String label) => InputDecoration( + labelText: label, + labelStyle: GoogleFonts.poppins(fontSize: 12), + border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)), + contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + ); + + Widget rowData(String label, String value) { + return Padding( + padding: const EdgeInsets.only(bottom: 6), + child: Table( + columnWidths: const { + 0: FixedColumnWidth(140), + 1: FixedColumnWidth(15), + 2: FlexColumnWidth() + }, + children: [ + TableRow(children: [ + Text(label, + style: GoogleFonts.poppins( + fontSize: 12, fontWeight: FontWeight.w500)), + Text(" : ", + style: GoogleFonts.poppins( + fontSize: 12, fontWeight: FontWeight.w500)), + Text(value.isEmpty ? "-" : value, + style: GoogleFonts.poppins(fontSize: 12)), + ]) + ], + ), + ); + } + + @override + Widget build(BuildContext context) { + return PopScope( + canPop: false, + onPopInvokedWithResult: (didPop, result) async { + if (didPop) return; + // ✅ FIX FINAL: selalu kembali ke Dashboard Bidan + Navigator.pushAndRemoveUntil( + context, + MaterialPageRoute( + builder: (_) => const DashboardBidanPage(), + ), + (route) => false, + ); + }, + child: MainLayout( + title: "", + drawer: const BidanDrawer(), + body: SingleChildScrollView( + padding: const EdgeInsets.all(16), + child: Column( + children: [ + // FORM TAMBAH + Center( + child: Container( + constraints: const BoxConstraints(maxWidth: 500), + padding: const EdgeInsets.all(20), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + boxShadow: const [ + BoxShadow(color: Colors.black12, blurRadius: 8) + ], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Center( + child: Text("Tambah Jadwal", + style: GoogleFonts.poppins( + fontSize: 18, fontWeight: FontWeight.bold))), + const SizedBox(height: 15), + TextField( + controller: _tanggalController, + style: GoogleFonts.poppins(fontSize: 12), + readOnly: true, + onTap: () async { + DateTime? picked = await showDatePicker( + context: context, + initialDate: DateTime.now(), + firstDate: DateTime(2024), + lastDate: DateTime(2030)); + if (picked != null) + setState(() => _tanggalController.text = + "${picked.year}-${picked.month.toString().padLeft(2, '0')}-${picked.day.toString().padLeft(2, '0')}"); + }, + decoration: _input("Tanggal").copyWith( + suffixIcon: + const Icon(Icons.calendar_today, size: 18)), + ), + const SizedBox(height: 10), + Row( + children: [ + Expanded( + child: TextField( + controller: _jamMulaiController, + style: GoogleFonts.poppins(fontSize: 12), + readOnly: true, + onTap: () async { + TimeOfDay? t = await showTimePicker( + context: context, + initialTime: TimeOfDay.now()); + if (t != null) + setState(() => _jamMulaiController.text = + "${t.hour.toString().padLeft(2, '0')}:${t.minute.toString().padLeft(2, '0')}"); + }, + decoration: _input("Jam Mulai"))), + const SizedBox(width: 8), + Expanded( + child: TextField( + controller: _jamSelesaiController, + style: GoogleFonts.poppins(fontSize: 12), + readOnly: true, + onTap: () async { + TimeOfDay? t = await showTimePicker( + context: context, + initialTime: TimeOfDay.now()); + if (t != null) + setState(() => _jamSelesaiController + .text = + "${t.hour.toString().padLeft(2, '0')}:${t.minute.toString().padLeft(2, '0')}"); + }, + decoration: _input("Jam Selesai"))), + ], + ), + const SizedBox(height: 10), + TextField( + controller: _lokasiController, + style: GoogleFonts.poppins(fontSize: 12), + decoration: _input("Lokasi Posyandu")), + const SizedBox(height: 15), + Text("Dusun Yang Dilayani", + style: GoogleFonts.poppins( + fontWeight: FontWeight.w600, fontSize: 12)), + const Divider(), + ...daftarDusun.map((d) => CheckboxListTile( + visualDensity: VisualDensity.compact, + contentPadding: EdgeInsets.zero, + title: Text(d.nama, + style: GoogleFonts.poppins(fontSize: 12)), + value: dunsunDipilih.contains(d.id), + onChanged: (val) { + setState(() { + if (val == true) { + dunsunDipilih.add(d.id); + } else { + dunsunDipilih.remove(d.id); + } + }); + loadKaderByDusun(); + }, + )), + const SizedBox(height: 10), + Text("Kader Otomatis Bertugas:", + style: GoogleFonts.poppins( + fontWeight: FontWeight.w600, fontSize: 12)), + const SizedBox(height: 5), + daftarKader.isEmpty + ? Text("-", + style: GoogleFonts.poppins( + color: Colors.grey, fontSize: 12)) + : Wrap( + spacing: 5, + runSpacing: 5, + children: daftarKader + .map((k) => Chip( + label: Text(k.nama, + style: GoogleFonts.poppins( + fontSize: 12)), + padding: EdgeInsets.zero, + backgroundColor: Colors.blue.shade50, + )) + .toList(), + ), + const SizedBox(height: 15), + TextField( + controller: _keteranganController, + style: GoogleFonts.poppins(fontSize: 12), + decoration: _input("Keterangan")), + const SizedBox(height: 20), + + // BUTTON SIMPAN JADWAL + SizedBox( + width: double.infinity, + child: OutlinedButton( + onPressed: _isLoading ? null : _simpanJadwal, + style: OutlinedButton.styleFrom( + side: const BorderSide(color: Colors.blue), + padding: const EdgeInsets.symmetric(vertical: 12), + shape: const StadiumBorder()), + child: _isLoading + ? const SizedBox( + height: 18, + width: 18, + child: CircularProgressIndicator( + color: Colors.blue, strokeWidth: 2)) + : Text( + "Simpan Jadwal", + style: GoogleFonts.poppins( + color: Colors.blue, + fontWeight: FontWeight.bold, + fontSize: 12, + ), + ), + ), + ), + ], + ), + ), + ), + const SizedBox(height: 15), + // BUTTON RIWAYAT + Container( + constraints: const BoxConstraints(maxWidth: 500), + child: ElevatedButton.icon( + onPressed: () => Navigator.push( + context, + MaterialPageRoute( + builder: (context) => + const RiwayatJadwalPosyanduPage())), + icon: const Icon(Icons.history, + size: 18, color: Colors.black87), + label: Text("Riwayat Jadwal Posyandu", + style: GoogleFonts.poppins( + color: Colors.black87, fontSize: 12)), + style: ElevatedButton.styleFrom( + backgroundColor: const Color(0xFFF1F1F1), + minimumSize: const Size(double.infinity, 45), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10))), + ), + ), + const SizedBox(height: 20), + // CARD HASIL + if (_dataJadwalLokal.isNotEmpty) ...[ + Container( + constraints: const BoxConstraints(maxWidth: 500), + child: Column( + children: [ + Align( + alignment: Alignment.centerLeft, + child: Text("Jadwal Posyandu Terbaru", + style: GoogleFonts.poppins( + fontWeight: FontWeight.bold, + fontSize: 12, + color: Colors.green))), + const SizedBox(height: 8), + ListView.builder( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + itemCount: _dataJadwalLokal.length, + itemBuilder: (context, index) { + final item = _dataJadwalLokal[index]; + return Card( + color: Colors.white, + elevation: 3, + margin: const EdgeInsets.only(bottom: 12), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12)), + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + children: [ + Row( + children: [ + const Icon(Icons.calendar_month, + size: 18, color: Colors.blue), + const SizedBox(width: 8), + Text("Data Jadwal Posyandu", + style: GoogleFonts.poppins( + fontWeight: FontWeight.bold, + fontSize: 12)), + const Spacer(), + + // BUTTON EDIT + OutlinedButton.icon( + onPressed: () async { + bool? refresh = await Navigator.push( + context, + MaterialPageRoute( + builder: (context) => + EditJadwalPage( + data: item))); + if (refresh == true) + loadLatestJadwal(); + }, + icon: const Icon(Icons.edit, + size: 16, color: Colors.orange), + label: Text("Edit", + style: GoogleFonts.poppins( + fontSize: 12, + fontWeight: FontWeight.bold, + color: Colors.orange)), + style: OutlinedButton.styleFrom( + side: const BorderSide( + color: Colors.orange), + padding: const EdgeInsets.symmetric( + horizontal: 12), + shape: const StadiumBorder()), + ), + ], + ), + const Divider(), + rowData("Tanggal Posyandu", + _formatTanggal(item['tanggal'])), + rowData("Jam", + "${item['jam_mulai']} - ${item['jam_selesai']}"), + rowData("Lokasi", item['lokasi'] ?? "-"), + rowData("Dusun", item['dusun'] ?? "-"), + rowData( + "Kader Bertugas", item['kader'] ?? "-"), + rowData( + "Keterangan", item['keterangan'] ?? "-"), + ], + ), + ), + ); + }, + ), + ], + ), + ), + ] + ], + ), + ), + ), + ); + } +} diff --git a/lib/bidan/laporan.dart b/lib/bidan/laporan.dart new file mode 100644 index 0000000..b7954bd --- /dev/null +++ b/lib/bidan/laporan.dart @@ -0,0 +1,674 @@ +import 'dart:convert'; +import 'dart:typed_data'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:http/http.dart' as http; +import 'package:pdf/pdf.dart'; +import 'package:pdf/widgets.dart' as pw; +import 'package:printing/printing.dart'; + +import '../layout/main_layout.dart'; +import 'bidan_drawer.dart'; +import '../bidan/dashboard_bidan.dart'; + +class DataLaporanPage extends StatefulWidget { + const DataLaporanPage({super.key}); + + @override + State createState() => _DataLaporanPageStatus(); +} + +class _DataLaporanPageStatus extends State { + int _currentPage = 0; + final int _rowsPerPage = 10; + String _searchQuery = ""; + List _allData = []; + + final List _namaBulan = [ + "Januari", + "Februari", + "Maret", + "April", + "Mei", + "Juni", + "Juli", + "Agustus", + "September", + "Oktober", + "November", + "Desember" + ]; + + Future> fetchPemeriksaanBalita() async { + try { + final response = await http.get(Uri.parse( + 'http://ta.myhost.id/E31230549/mposyandu_api/laporan/get_laporan.php')); + + if (response.statusCode == 200) { + Map data = json.decode(response.body); + _allData = data['data'] ?? []; + return data; + } else { + throw Exception('Gagal mengambil data dari database'); + } + } catch (e) { + throw Exception('Kesalahan koneksi: $e'); + } + } + + void _showMonthSelectionDialog() async { + List selectedMonths = []; + + await showDialog( + context: context, + builder: (context) { + return StatefulBuilder( + builder: (context, setDialogState) { + return AlertDialog( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12)), + title: Text("Pilih Bulan", + style: GoogleFonts.poppins( + fontSize: 16, fontWeight: FontWeight.bold)), + content: SizedBox( + width: 300, + height: 300, + child: GridView.builder( + shrinkWrap: true, + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: 2, + childAspectRatio: 3, + ), + itemCount: _namaBulan.length, + itemBuilder: (context, index) { + return CheckboxListTile( + contentPadding: EdgeInsets.zero, + title: Text(_namaBulan[index], + style: GoogleFonts.poppins(fontSize: 12)), + value: selectedMonths.contains(index + 1), + controlAffinity: ListTileControlAffinity.leading, + onChanged: (bool? value) { + setDialogState(() { + if (value == true) { + selectedMonths.add(index + 1); + } else { + selectedMonths.remove(index + 1); + } + }); + }, + ); + }, + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: Text("Batal", + style: GoogleFonts.poppins(color: Colors.grey)), + ), + ElevatedButton( + style: ElevatedButton.styleFrom(backgroundColor: Colors.blue), + onPressed: () { + Navigator.pop(context); + if (selectedMonths.isNotEmpty) { + _generateFilteredPdf(selectedMonths); + } + }, + child: Text("Cetak", + style: GoogleFonts.poppins(color: Colors.white)), + ), + ], + ); + }, + ); + }, + ); + } + + // ================= GENERATE PDF DENGAN REKAP GIZI BARU ================= + Future _generateFilteredPdf(List selectedMonths) async { + List filteredData = _allData.where((item) { + final tglString = item['tgl_periksa']?.toString() ?? ''; + if (tglString.isEmpty || tglString == '-') return false; + try { + final parts = tglString.split('-'); + if (parts.length != 3) return false; + final bulan = int.parse(parts[1]); + return selectedMonths.contains(bulan); + } catch (e) { + return false; + } + }).toList(); + + if (filteredData.isEmpty) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text("Tidak ada data pada bulan yang dipilih"), + backgroundColor: Colors.orange), + ); + return; + } + + // Variabel Rekapitulasi (Sudah digunakan di bawah agar garis kuning hilang) + int bbuGiziBuruk = 0, + bbuGiziKurang = 0, + bbuGiziBaik = 0, + bbuRisikoLebih = 0; + int tbuSangatPendek = 0, tbuPendek = 0, tbuNormal = 0, tbuTinggi = 0; + int bbtbGiziBuruk = 0, + bbtbGiziKurang = 0, + bbtbGiziBaik = 0, + bbtbRisikoLebih = 0, + bbtbObesitas = 0; + + for (var item in filteredData) { + String bbu = (item['status_bbu'] ?? '').toString().trim().toLowerCase(); + String tbu = (item['status_tbu'] ?? '').toString().trim().toLowerCase(); + String bbtb = (item['status_bbtb'] ?? '').toString().trim().toLowerCase(); + + if (bbu.contains('buruk')) + bbuGiziBuruk++; + else if (bbu.contains('kurang')) + bbuGiziKurang++; + else if (bbu.contains('baik') || bbu.contains('normal')) + bbuGiziBaik++; + else if (bbu.contains('lebih')) bbuRisikoLebih++; + + if (tbu.contains('sangat pendek')) + tbuSangatPendek++; + else if (tbu.contains('pendek') || tbu.contains('stunting')) + tbuPendek++; + else if (tbu.contains('normal')) + tbuNormal++; + else if (tbu.contains('tinggi')) tbuTinggi++; + + if (bbtb.contains('buruk') || bbtb.contains('wasting')) + bbtbGiziBuruk++; + else if (bbtb.contains('kurang')) + bbtbGiziKurang++; + else if (bbtb.contains('baik') || bbtb.contains('normal')) + bbtbGiziBaik++; + else if (bbtb.contains('risiko') || bbtb.contains('overweight')) + bbtbRisikoLebih++; + else if (bbtb.contains('obesitas')) bbtbObesitas++; + } + + final pdf = pw.Document(); + pw.MemoryImage? logoImage; + + try { + final ByteData assetImage = + await rootBundle.load('assets/images/logo sumberasih.png'); + logoImage = pw.MemoryImage(assetImage.buffer.asUint8List()); + } catch (e) { + debugPrint("Logo gagal dimuat"); + } + + const int pdfItemsPerPage = 12; + final int totalPages = (filteredData.length / pdfItemsPerPage).ceil(); + final currentYear = DateTime.now().year; + + for (int i = 0; i < totalPages; i++) { + final int start = i * pdfItemsPerPage; + final int end = (start + pdfItemsPerPage < filteredData.length) + ? start + pdfItemsPerPage + : filteredData.length; + final List pageData = filteredData.sublist(start, end); + + pdf.addPage( + pw.Page( + pageFormat: PdfPageFormat.a4.landscape, + margin: const pw.EdgeInsets.all(15), + build: (pw.Context context) { + return pw.Column( + crossAxisAlignment: pw.CrossAxisAlignment.start, + children: [ + // ================= HEADER ================= + pw.Row( + crossAxisAlignment: pw.CrossAxisAlignment.center, + children: [ + if (logoImage != null) + pw.Container( + width: 50, height: 50, child: pw.Image(logoImage)), + pw.SizedBox(width: 15), + pw.Expanded( + child: pw.Column( + children: [ + pw.Text("LAPORAN KEGIATAN KUNJUNGAN BALITA", + style: pw.TextStyle( + fontSize: 16, + fontWeight: pw.FontWeight.bold)), + pw.SizedBox(height: 2), + pw.Text("Posyandu Desa Mentor", + style: const pw.TextStyle(fontSize: 11)), + pw.Text("Kecamatan Sumberasih, Kabupaten Probolinggo", + style: const pw.TextStyle(fontSize: 11)), + pw.SizedBox(height: 2), + pw.Text( + "Bulan: ${selectedMonths.map((m) => _namaBulan[m - 1]).join(', ')} $currentYear", + style: pw.TextStyle( + fontSize: 10, + fontWeight: pw.FontWeight.bold)), + ], + ), + ), + ], + ), + pw.SizedBox(height: 5), + pw.Divider(thickness: 1.5), + pw.SizedBox(height: 5), + + // ================= TABEL DATA ================= + pw.TableHelper.fromTextArray( + border: + pw.TableBorder.all(color: PdfColors.grey700, width: 0.5), + cellAlignment: pw.Alignment.centerLeft, + headerAlignment: pw.Alignment.center, + headers: [ + 'No', + 'NIK', + 'Nama Balita', + 'Orang Tua', + 'TTL', + 'Umur', + 'JK', + 'Anak', + 'Alamat', + 'Tgl Periksa', + 'BB', + 'TB', + 'LK', + 'Imunisasi', + 'BB/U', + 'TB/U', + 'BB/TB', + 'Hadir' + ], + data: List>.generate(pageData.length, (index) { + final data = pageData[index]; + return [ + (start + index + 1).toString(), + data['nik_balita'] ?? "-", + data['nama'] ?? "-", + data['nama_orang_tua'] ?? "-", + "${data['tempat_lahir'] ?? '-'}, ${data['tgl_lahir'] ?? '-'}", + "${data['umur'] ?? '-'} Bln", + data['jenis_kelamin'] ?? "-", + data['anak_ke']?.toString() ?? "-", + data['alamat_lengkap'] ?? "-", + data['tgl_periksa'] ?? "-", + data['berat_badan']?.toString() ?? "-", + data['tinggi_badan']?.toString() ?? "-", + data['lingkar_kepala']?.toString() ?? "-", + data['pemberian_imunisasi'] ?? "-", + data['status_bbu'] ?? "-", + data['status_tbu'] ?? "-", + data['status_bbtb'] ?? "-", + data['kehadiran_posyandu'] ?? "-", + ]; + }), + headerStyle: pw.TextStyle( + fontSize: 7, + fontWeight: pw.FontWeight.bold, + color: PdfColors.white), + headerDecoration: + const pw.BoxDecoration(color: PdfColors.blue700), + cellStyle: const pw.TextStyle(fontSize: 6.5), + cellHeight: 24, + columnWidths: { + 0: const pw.FixedColumnWidth(20), + 1: const pw.FixedColumnWidth(60), + 2: const pw.FixedColumnWidth(65), + 3: const pw.FixedColumnWidth(70), + 4: const pw.FixedColumnWidth(75), + 5: const pw.FixedColumnWidth(30), + 6: const pw.FixedColumnWidth(20), + 7: const pw.FixedColumnWidth(25), + 8: const pw.FixedColumnWidth(90), + 9: const pw.FixedColumnWidth(45), + 10: const pw.FixedColumnWidth(25), + 11: const pw.FixedColumnWidth(25), + 12: const pw.FixedColumnWidth(25), + 13: const pw.FixedColumnWidth(50), + 14: const pw.FixedColumnWidth(50), + 15: const pw.FixedColumnWidth(50), + 16: const pw.FixedColumnWidth(50), + 17: const pw.FixedColumnWidth(40), + }, + ), + + // ================= FOOTER REKAPITULASI (HALAMAN TERAKHIR) ================= + if (i == totalPages - 1) ...[ + pw.SizedBox(height: 12), + pw.Row( + // PERBAIKAN: Menggunakan pw.MainAxisAlignment.spaceBetween agar tidak error garis merah + mainAxisAlignment: pw.MainAxisAlignment.spaceBetween, + crossAxisAlignment: pw.CrossAxisAlignment.start, + children: [ + pw.Text("Total Data: ${filteredData.length} Anak", + style: pw.TextStyle( + fontSize: 9, fontWeight: pw.FontWeight.bold)), + pw.Container( + width: 480, + padding: const pw.EdgeInsets.all(6), + decoration: pw.BoxDecoration( + border: pw.Border.all( + color: PdfColors.black, width: 0.5)), + child: pw.Column( + crossAxisAlignment: pw.CrossAxisAlignment.start, + children: [ + pw.Text("Keterangan Rekapitulasi Status Gizi", + style: pw.TextStyle( + fontWeight: pw.FontWeight.bold, + fontSize: 9)), + pw.SizedBox(height: 4), + pw.Row( + mainAxisAlignment: + pw.MainAxisAlignment.spaceBetween, + children: [ + pw.Column( + crossAxisAlignment: + pw.CrossAxisAlignment.start, + children: [ + pw.Text("[BB/U] Berat Badan / Umur:", + style: pw.TextStyle( + fontSize: 7, + fontWeight: pw.FontWeight.bold)), + pw.Text( + "- Gizi Baik: $bbuGiziBaik\n- Gizi Kurang: $bbuGiziKurang\n- Gizi Buruk: $bbuGiziBuruk\n- Risiko Lebih: $bbuRisikoLebih", + style: const pw.TextStyle(fontSize: 7)), + ], + ), + pw.Column( + crossAxisAlignment: + pw.CrossAxisAlignment.start, + children: [ + pw.Text("[TB/U] Tinggi Badan / Umur:", + style: pw.TextStyle( + fontSize: 7, + fontWeight: pw.FontWeight.bold)), + pw.Text( + "- Normal: $tbuNormal\n- Pendek: $tbuPendek\n- Sangat Pendek: $tbuSangatPendek\n- Tinggi: $tbuTinggi", + style: const pw.TextStyle(fontSize: 7)), + ], + ), + pw.Column( + crossAxisAlignment: + pw.CrossAxisAlignment.start, + children: [ + pw.Text("[BB/TB] Berat Badan / Tinggi:", + style: pw.TextStyle( + fontSize: 7, + fontWeight: pw.FontWeight.bold)), + pw.Text( + "- Normal: $bbtbGiziBaik\n- Gizi Kurang: $bbtbGiziKurang\n- Gizi Buruk: $bbtbGiziBuruk\n- Overweight: $bbtbRisikoLebih\n- Obesitas: $bbtbObesitas", + style: const pw.TextStyle(fontSize: 7)), + ], + ), + ], + ), + ], + ), + ), + ], + ), + ], + ], + ); + }, + ), + ); + } + + await Printing.layoutPdf( + onLayout: (PdfPageFormat format) async => pdf.save()); + } + + @override + Widget build(BuildContext context) { + return PopScope( + canPop: false, + onPopInvokedWithResult: (didPop, result) async { + if (didPop) return; + Navigator.pushAndRemoveUntil( + context, + MaterialPageRoute(builder: (_) => const DashboardBidanPage()), + (route) => false); + }, + child: MainLayout( + title: "", + drawer: const BidanDrawer(), + body: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Center( + child: Text("Laporan Pemeriksaan Balita", + style: GoogleFonts.poppins( + fontSize: 18, fontWeight: FontWeight.w600)), + ), + const SizedBox(height: 10), + Align( + alignment: Alignment.centerRight, + child: SizedBox( + height: 35, + child: OutlinedButton.icon( + onPressed: () => _allData.isNotEmpty + ? _showMonthSelectionDialog() + : null, + icon: const Icon(Icons.print, size: 16, color: Colors.blue), + label: Text("Cetak PDF", + style: GoogleFonts.poppins( + fontSize: 11, + color: Colors.blue, + fontWeight: FontWeight.w500)), + style: OutlinedButton.styleFrom( + backgroundColor: Colors.white, + side: const BorderSide(color: Colors.blue, width: 1), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(6)), + ), + ), + ), + ), + const SizedBox(height: 15), + TextField( + onChanged: (value) => setState(() { + _searchQuery = value; + _currentPage = 0; + }), + style: GoogleFonts.poppins(fontSize: 12), + decoration: InputDecoration( + hintText: "Cari nama balita...", + prefixIcon: const Icon(Icons.search, size: 20), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10)), + contentPadding: const EdgeInsets.symmetric(vertical: 0), + ), + ), + const SizedBox(height: 20), + Row( + children: [ + const Icon(Icons.swipe_left_alt, + size: 14, color: Colors.grey), + const SizedBox(width: 5), + Text("Geser ke kanan untuk melihat lebih lanjut", + style: GoogleFonts.poppins( + fontSize: 10, + color: Colors.grey.shade600, + fontStyle: FontStyle.italic)), + ], + ), + const SizedBox(height: 5), + Expanded( + child: FutureBuilder>( + future: fetchPemeriksaanBalita(), + builder: (context, snapshot) { + if (snapshot.connectionState == ConnectionState.waiting) + return const Center(child: CircularProgressIndicator()); + if (snapshot.hasError) + return Center(child: Text("Error: ${snapshot.error}")); + + final List rawData = snapshot.data?['data'] ?? []; + final filteredData = rawData + .where((item) => item["nama"] + .toString() + .toLowerCase() + .contains(_searchQuery.toLowerCase())) + .toList(); + + if (filteredData.isEmpty) + return const Center(child: Text("Data tidak ditemukan")); + + final totalPages = + (filteredData.length / _rowsPerPage).ceil(); + final start = _currentPage * _rowsPerPage; + final end = (start + _rowsPerPage > filteredData.length) + ? filteredData.length + : start + _rowsPerPage; + final paginatedData = filteredData.sublist(start, end); + + return Column( + children: [ + Expanded( + child: SingleChildScrollView( + scrollDirection: Axis.vertical, + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: _buildTable(paginatedData, start), + ), + ), + ), + _buildPaginationControls(totalPages), + ], + ); + }, + ), + ), + ], + ), + ), + ), + ); + } + + Widget _buildTable(List dataList, int startIndex) { + return DataTable( + headingRowColor: WidgetStateProperty.all(Colors.blue.shade600), + columnSpacing: 18, + horizontalMargin: 10, + columns: [ + _headerCell("No"), + _headerCell("NIK"), + _headerCell("Nama Balita"), + _headerCell("Nama Orang Tua"), + _headerCell("TTL"), + _headerCell("Umur"), + _headerCell("JK"), + _headerCell("Anak Ke"), + _headerCell("Alamat"), + _headerCell("Tgl Periksa"), + _headerCell("BB (kg)"), + _headerCell("TB (cm)"), + _headerCell("LK (cm)"), + _headerCell("Imunisasi"), + _headerCell("BB/U"), + _headerCell("TB/U"), + _headerCell("BB/TB"), + _headerCell("Kehadiran"), + ], + rows: List.generate(dataList.length, (index) { + final data = dataList[index]; + return DataRow(cells: [ + DataCell(_textCell((startIndex + index + 1).toString())), + DataCell(_textCell(data['nik_balita'] ?? "-")), + DataCell(_textCell(data['nama'] ?? "-")), + DataCell(_textCell(data['nama_orang_tua'] ?? "-")), + DataCell(_textCell( + "${data['tempat_lahir'] ?? ''}, ${data['tgl_lahir'] ?? ''}")), + DataCell(_textCell("${data['umur'] ?? '-'} Bln")), + DataCell(_textCell(data['jenis_kelamin'] ?? "-")), + DataCell(_textCell(data['anak_ke']?.toString() ?? "-")), + DataCell(_textCell(data['alamat_lengkap'] ?? "-")), + DataCell(_textCell(data['tgl_periksa'] ?? "-")), + DataCell(_textCell(data['berat_badan']?.toString() ?? "-")), + DataCell(_textCell(data['tinggi_badan']?.toString() ?? "-")), + DataCell(_textCell(data['lingkar_kepala']?.toString() ?? "-")), + DataCell(_textCell(data['pemberian_imunisasi'] ?? "-")), + DataCell(_statusGiziBadge(data['status_bbu'])), + DataCell(_statusGiziBadge(data['status_tbu'])), + DataCell(_statusGiziBadge(data['status_bbtb'])), + DataCell(_textCell(data['kehadiran_posyandu'] ?? "-")), + ]); + }), + ); + } + + DataColumn _headerCell(String label) => DataColumn( + label: Text(label, + style: GoogleFonts.poppins( + color: Colors.white, fontWeight: FontWeight.bold, fontSize: 11))); + + Widget _textCell(String text) => + Text(text, style: GoogleFonts.poppins(fontSize: 11)); + + Widget _statusGiziBadge(String? status) { + if (status == null || status == "-") return _textCell("-"); + + String normalValue = status.toLowerCase(); + Color color = Colors.grey; + + if (normalValue.contains('baik') || normalValue.contains('normal')) { + color = Colors.green; + } else if (normalValue.contains('kurang') || + normalValue.contains('pendek')) { + color = Colors.orange; + } else if (normalValue.contains('buruk') || + normalValue.contains('sangat pendek') || + normalValue.contains('wasting')) { + color = Colors.red; + } else if (normalValue.contains('lebih') || + normalValue.contains('obesitas') || + normalValue.contains('overweight')) { + color = Colors.purple; + } + + return Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 4), + decoration: + BoxDecoration(color: color, borderRadius: BorderRadius.circular(4)), + child: Text(status, + style: GoogleFonts.poppins( + color: Colors.white, fontSize: 9, fontWeight: FontWeight.bold)), + ); + } + + Widget _buildPaginationControls(int totalPages) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 10), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text("Halaman ${_currentPage + 1} dari $totalPages", + style: GoogleFonts.poppins(fontSize: 11)), + Row( + children: [ + IconButton( + icon: const Icon(Icons.arrow_back_ios, size: 16), + onPressed: _currentPage == 0 + ? null + : () => setState(() => _currentPage--)), + IconButton( + icon: const Icon(Icons.arrow_forward_ios, size: 16), + onPressed: _currentPage >= totalPages - 1 + ? null + : () => setState(() => _currentPage++)), + ], + ), + ], + ), + ); + } +} diff --git a/lib/bidan/periksa_kehamilan.dart b/lib/bidan/periksa_kehamilan.dart new file mode 100644 index 0000000..0687881 --- /dev/null +++ b/lib/bidan/periksa_kehamilan.dart @@ -0,0 +1,541 @@ +import 'dart:async'; +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:http/http.dart' as http; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../layout/main_layout.dart'; +import 'bidan_drawer.dart'; +import '../pages/login_page.dart'; +import '../bidan/crud_kehamilan/tambah_pemeriksaan_kehamilan.dart'; +import '../bidan/crud_kehamilan/riwayat_pemeriksaan_kehamilan.dart'; +import '../bidan/dashboard_bidan.dart'; + +class DataPemeriksaanKehamilanPage extends StatefulWidget { + const DataPemeriksaanKehamilanPage({super.key}); + + @override + State createState() => + _DataPemeriksaanKehamilanPageState(); +} + +class _DataPemeriksaanKehamilanPageState + extends State { + List> _dataHamil = []; + List> _allDataHamil = []; + bool _loading = true; + bool _checkingLogin = true; + + int _currentPage = 0; + final int _rowsPerPage = 5; + + String _formatTanggalIndo(String? tanggal) { + if (tanggal == null || + tanggal.isEmpty || + tanggal == "-" || + tanggal == "0000-00-00") return "-"; + try { + DateTime dt = DateTime.parse(tanggal); + List bulanIndo = [ + "", + "Januari", + "Februari", + "Maret", + "April", + "Mei", + "Juni", + "Juli", + "Agustus", + "September", + "Oktober", + "November", + "Desember" + ]; + return "${dt.day.toString().padLeft(2, '0')} ${bulanIndo[dt.month]} ${dt.year}"; + } catch (e) { + return tanggal; + } + } + + @override + void initState() { + super.initState(); + _checkLogin(); + } + + Future _checkLogin() async { + final prefs = await SharedPreferences.getInstance(); + final isLogin = prefs.getBool('isLogin') ?? false; + + if (!isLogin) { + if (!mounted) return; + Navigator.pushReplacement( + context, + MaterialPageRoute(builder: (_) => const LoginPage()), + ); + return; + } + + setState(() => _checkingLogin = false); + _fetchDataKehamilan(); + } + + Future _fetchDataKehamilan() async { + setState(() => _loading = true); + final url = Uri.parse( + 'http://ta.myhost.id/E31230549/mposyandu_api/pemeriksaan_kehamilan/get_pemeriksaan_kehamilan.php', + ); + + try { + final response = await http.get(url); + if (response.statusCode == 200) { + final jsonData = json.decode(response.body); + if (jsonData["success"] == true) { + final List> data = + List>.from(jsonData["data"]); + + // FITUR FIX: Mengurutkan list data berdasarkan nama ibu secara alfabetis A-Z + data.sort((a, b) { + String namaA = (a['nama'] ?? '').toString().trim().toLowerCase(); + String namaB = (b['nama'] ?? '').toString().trim().toLowerCase(); + return namaA.compareTo(namaB); + }); + + setState(() { + _allDataHamil = data; + _dataHamil = data; + _loading = false; + }); + } else { + setState(() { + _dataHamil = []; + _loading = false; + }); + } + } else { + setState(() => _loading = false); + } + } catch (e) { + debugPrint("ERROR FETCH: $e"); + setState(() => _loading = false); + } + } + + // Fungsi Validasi Status + bool _checkStatus(String? status) { + String s = (status ?? "").toLowerCase(); + if (s == "melahirkan" || s == "keguguran") { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + backgroundColor: Colors.red, + content: Text( + "Maaf ibu sudah melahirkan/keguguran", + style: GoogleFonts.poppins(color: Colors.white, fontSize: 12), + ), + ), + ); + return false; + } + return true; + } + + List> get _paginatedData { + if (_dataHamil.isEmpty) return []; + final start = _currentPage * _rowsPerPage; + final end = start + _rowsPerPage; + if (start >= _dataHamil.length) return []; + return _dataHamil.sublist( + start, + end > _dataHamil.length ? _dataHamil.length : end, + ); + } + + @override + Widget build(BuildContext context) { + if (_checkingLogin) { + return const Scaffold( + body: Center(child: CircularProgressIndicator()), + ); + } + + final totalPages = + _dataHamil.isEmpty ? 1 : (_dataHamil.length / _rowsPerPage).ceil(); + + return PopScope( + canPop: false, + onPopInvokedWithResult: (didPop, result) async { + if (didPop) return; + Navigator.pushAndRemoveUntil( + context, + MaterialPageRoute(builder: (_) => const DashboardBidanPage()), + (route) => false, + ); + }, + child: MainLayout( + title: "", + drawer: const BidanDrawer(), + body: _loading + ? const Center(child: CircularProgressIndicator()) + : Padding( + padding: const EdgeInsets.all(16), + child: Column( + children: [ + Center( + child: Text( + "Data Pemeriksaan Kehamilan", + style: GoogleFonts.poppins( + fontSize: 18, + fontWeight: FontWeight.w600, + color: Colors.black87, + ), + ), + ), + const SizedBox(height: 12), + TextField( + style: GoogleFonts.poppins(fontSize: 12), + decoration: InputDecoration( + hintText: "Cari nama ibu...", + hintStyle: GoogleFonts.poppins(fontSize: 12), + prefixIcon: const Icon(Icons.search, size: 20), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + ), + ), + onChanged: (value) { + setState(() { + _dataHamil = _allDataHamil + .where((b) => (b['nama'] ?? '') + .toLowerCase() + .contains(value.toLowerCase())) + .toList(); + _currentPage = 0; + }); + }, + ), + const SizedBox(height: 15), + Expanded( + child: _dataHamil.isEmpty + ? Center( + child: Text( + "Tidak ada data pemeriksaan", + style: GoogleFonts.poppins(fontSize: 12), + ), + ) + : ListView.builder( + itemCount: _paginatedData.length, + itemBuilder: (context, index) { + final ibu = _paginatedData[index]; + String statusIbu = + ibu['status_ibu_hamil'] ?? "aktif"; + bool isInactive = + (statusIbu.toLowerCase() == "melahirkan" || + statusIbu.toLowerCase() == "keguguran"); + + String alamatLengkap = + "Desa ${ibu['nama_desa'] ?? '-'}, Dusun ${ibu['nama_dusun'] ?? '-'}, ${ibu['alamat_detail'] ?? '-'}"; + + return Container( + margin: + const EdgeInsets.symmetric(vertical: 8), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(14), + boxShadow: const [ + BoxShadow( + color: Colors.black12, + blurRadius: 8, + offset: Offset(0, 4), + ), + ], + ), + child: Column( + children: [ + Container( + width: double.infinity, + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: isInactive + ? Colors.grey + : Colors.blueAccent, + borderRadius: + const BorderRadius.vertical( + top: Radius.circular(14), + ), + ), + child: Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + Text( + ibu["nama"] ?? "-", + style: GoogleFonts.poppins( + color: Colors.white, + fontWeight: FontWeight.bold, + fontSize: 13, + ), + ), + const SizedBox(height: 6), + _rowWhite("Nama Suami", + ibu["nama_suami"]), + _rowWhite("Alamat", alamatLengkap), + const Divider( + color: Colors.white24), + _rowWhite( + "HPHT", + _formatTanggalIndo( + ibu["hpht"])), + _rowWhite("Usia Kandungan", + "${ibu["usia_kehamilan"] ?? '-'} Minggu"), + _rowWhite("HPL", + _formatTanggalIndo(ibu["hpl"])), + _rowWhite("G-P-A", + "${ibu["gravida"]}-${ibu["para"]}-${ibu["abortus"]}"), + _rowWhite("Status Ibu", + statusIbu.toUpperCase()), + ], + ), + ), + Container( + width: double.infinity, + padding: const EdgeInsets.all(12), + child: Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + Text( + "Riwayat Pemeriksaan Terakhir", + style: GoogleFonts.poppins( + fontWeight: FontWeight.w600, + fontSize: 13, + color: Colors.black87, + ), + ), + const Divider(), + _riwayatList(ibu), + const SizedBox(height: 12), + Row( + children: [ + Expanded( + child: OutlinedButton.icon( + onPressed: () async { + if (!_checkStatus( + statusIbu)) return; + final result = + await Navigator.push( + context, + MaterialPageRoute( + builder: (_) => + TambahPemeriksaanKehamilanPage( + ibuHamilId: + ibu["id"] + .toString(), + nama: ibu["nama"], + ), + ), + ); + if (result == true) { + _fetchDataKehamilan(); + } + }, + icon: Icon(Icons.add, + size: 16, + color: isInactive + ? Colors.grey + : Colors.blue), + label: Text("Input Data", + style: + GoogleFonts.poppins( + fontSize: 12, + fontWeight: + FontWeight + .bold, + color: isInactive + ? Colors + .grey + : Colors + .blue)), + style: OutlinedButton.styleFrom( + side: BorderSide( + color: isInactive + ? Colors.grey + : Colors.blue), + shape: + const StadiumBorder(), + padding: + const EdgeInsets + .symmetric( + vertical: 8)), + ), + ), + const SizedBox(width: 8), + Expanded( + child: OutlinedButton.icon( + onPressed: () async { + if (!_checkStatus( + statusIbu)) return; + await Navigator.push( + context, + MaterialPageRoute( + builder: (_) => + RiwayatPemeriksaanKehamilanPage( + ibuHamilId: + ibu["id"] + .toString(), + nama: ibu["nama"], + ), + ), + ); + _fetchDataKehamilan(); + }, + icon: Icon(Icons.history, + size: 16, + color: isInactive + ? Colors.grey + : Colors + .deepPurple), + label: Text("Riwayat", + style: GoogleFonts.poppins( + fontSize: 12, + fontWeight: + FontWeight.bold, + color: isInactive + ? Colors.grey + : Colors + .deepPurple)), + style: OutlinedButton.styleFrom( + side: BorderSide( + color: isInactive + ? Colors.grey + : Colors + .deepPurple), + shape: + const StadiumBorder(), + padding: + const EdgeInsets + .symmetric( + vertical: 8)), + ), + ), + ], + ), + ], + ), + ), + ], + ), + ); + }, + ), + ), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text("Halaman ${_currentPage + 1} dari $totalPages", + style: GoogleFonts.poppins(fontSize: 12)), + Row( + children: [ + IconButton( + icon: const Icon(Icons.chevron_left), + onPressed: _currentPage == 0 + ? null + : () => setState(() => _currentPage--)), + IconButton( + icon: const Icon(Icons.chevron_right), + onPressed: _currentPage >= totalPages - 1 + ? null + : () => setState(() => _currentPage++)), + ], + ), + ], + ), + ], + ), + ), + ), + ); + } + + Widget _rowWhite(String label, dynamic value) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 2), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: 115, + child: Text( + label, + style: GoogleFonts.poppins( + fontSize: 12, + fontWeight: FontWeight.w600, + color: Colors.white), + ), + ), + Text(" : ", + style: GoogleFonts.poppins( + color: Colors.white, + fontSize: 12, + fontWeight: FontWeight.bold)), + Expanded( + child: Text( + "${value ?? '-'}", + style: GoogleFonts.poppins( + fontSize: 12, + color: Colors.white, + fontWeight: FontWeight.w500), + ), + ), + ], + ), + ); + } + + Widget _riwayatList(Map data) { + final items = { + "Tgl Periksa": _formatTanggalIndo(data["tanggal_pemeriksaan"]), + "BB Sblm Hamil": "${data["bb_sebelum_hamil"] ?? '-'} kg", + "BB Sekarang": "${data["berat_badan"] ?? '-'} kg", + "Tinggi Badan": "${data["tinggi_badan"] ?? '-'} cm", + "LILA": "${data["lila_periksa"] ?? '-'} cm", + "Status Gizi": data["status_gizi"], + "Tekanan Darah": data["tekanan_darah"], + "Tinggi Fundus": "${data["tinggi_fundus"] ?? '-'} cm", + "DJJ (Jantung)": data["denyut_jantung_janin"], + "HB": data["hb"], + "Kaki Bengkak": data["kaki_bengkak"], + "Keluhan": data["keluhan"], + "Tindak Lanjut": data["tindakan"], + }; + + return Column( + children: items.entries.map((entry) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: 115, + child: Text( + entry.key, + style: GoogleFonts.poppins( + fontSize: 12, + fontWeight: FontWeight.w600, + color: Colors.black), + ), + ), + Text(" : ", style: GoogleFonts.poppins(fontSize: 12)), + Expanded( + child: Text( + "${entry.value ?? '-'}", + style: GoogleFonts.poppins(fontSize: 12, color: Colors.black), + ), + ), + ], + ), + ); + }).toList(), + ); + } +} diff --git a/lib/bidan/profile_bidan.dart b/lib/bidan/profile_bidan.dart new file mode 100644 index 0000000..b0173d4 --- /dev/null +++ b/lib/bidan/profile_bidan.dart @@ -0,0 +1,472 @@ +import 'dart:io'; +import 'dart:convert'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:image_picker/image_picker.dart'; +import 'package:http/http.dart' as http; +import '../pages/login_page.dart'; +import '../bidan/dashboard_bidan.dart'; + +class ProfileBidanPage extends StatefulWidget { + const ProfileBidanPage({super.key}); + + @override + State createState() => _ProfileBidanPageState(); +} + +class _ProfileBidanPageState extends State { + final TextEditingController namaC = TextEditingController(); + final TextEditingController emailC = TextEditingController(); + final TextEditingController passwordC = TextEditingController(); + final TextEditingController roleC = TextEditingController(); + final TextEditingController noHpC = TextEditingController(); + final TextEditingController statusC = TextEditingController(); + + String? idUser; + String? fotoUser; + XFile? _pickedFile; + bool _obscurePassword = true; + bool isEditMode = false; + + @override + void initState() { + super.initState(); + _loadUserData(); + } + + @override + void dispose() { + namaC.dispose(); + emailC.dispose(); + passwordC.dispose(); + roleC.dispose(); + noHpC.dispose(); + statusC.dispose(); + super.dispose(); + } + + Future _loadUserData() async { + final prefs = await SharedPreferences.getInstance(); + final isLogin = prefs.getBool('isLogin') ?? false; + + if (!isLogin) { + if (!mounted) return; + Navigator.pushAndRemoveUntil( + context, + MaterialPageRoute(builder: (_) => const LoginPage(fromGuard: true)), + (route) => false, + ); + return; + } + + setState(() { + idUser = prefs.getString('id_user') ?? ""; + namaC.text = prefs.getString('nama') ?? ""; + emailC.text = prefs.getString('email') ?? ""; + passwordC.text = prefs.getString('password') ?? ""; + roleC.text = (prefs.getString('role') ?? "Bidan").toLowerCase(); + String savedNoHp = prefs.getString('no_hp') ?? ""; + noHpC.text = (savedNoHp.isEmpty || savedNoHp == "-") ? "-" : savedNoHp; + + statusC.text = prefs.getString('status_aktif') ?? "Aktif"; + fotoUser = prefs.getString('foto'); + }); + } + + // Fungsi Helper untuk SnackBar Peringatan + void _showEditWarning() { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text("Klik tombol edit di bawah untuk mengubah foto"), + backgroundColor: Colors.red, + ), + ); + } + + Future _pickImage() async { + if (!isEditMode) { + _showEditWarning(); + return; + } + final ImagePicker picker = ImagePicker(); + final XFile? image = await picker.pickImage(source: ImageSource.gallery); + + if (image != null) { + setState(() { + _pickedFile = image; + }); + } + } + + void _removeImage() { + if (!isEditMode) { + _showEditWarning(); + return; + } + setState(() { + _pickedFile = null; + fotoUser = ""; + }); + } + + void _enableEdit() { + setState(() { + isEditMode = true; + }); + } + + bool _validatePassword(String value) { + String pattern = r'^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6}$'; + RegExp regExp = RegExp(pattern); + return regExp.hasMatch(value); + } + + bool _validateNoHp(String value) { + String pattern = r'^[0-9]{10,13}$'; + RegExp regExp = RegExp(pattern); + return regExp.hasMatch(value); + } + + void _saveProfile() async { + if (!isEditMode) return; + + if (!_validateNoHp(noHpC.text)) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text("No. HP harus berupa angka dan berjumlah 10-13 digit!"), + backgroundColor: Colors.red, + ), + ); + return; + } + + if (!_validatePassword(passwordC.text)) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text("Password harus 6 digit (kombinasi huruf & angka)!"), + backgroundColor: Colors.red, + ), + ); + return; + } + + try { + var request = http.MultipartRequest( + 'POST', + Uri.parse( + "http://ta.myhost.id/E31230549/mposyandu_api/users/update_profile_bidan.php"), + ); + + request.fields['id_user'] = idUser ?? ""; + request.fields['nama'] = namaC.text; + request.fields['email'] = emailC.text; + request.fields['password'] = passwordC.text; + request.fields['no_hp'] = noHpC.text; + request.fields['foto_lama'] = fotoUser ?? ""; + + if (_pickedFile != null) { + Uint8List data = await _pickedFile!.readAsBytes(); + request.files.add(http.MultipartFile.fromBytes( + 'foto', + data, + filename: _pickedFile!.name, + )); + } + + var response = await request.send(); + var responseData = await response.stream.bytesToString(); + var result = json.decode(responseData); + + if (result['status'] == 'success') { + final prefs = await SharedPreferences.getInstance(); + + await prefs.setString('nama', namaC.text); + await prefs.setString('email', emailC.text); + await prefs.setString('password', passwordC.text); + await prefs.setString('no_hp', noHpC.text); + + if (result['foto'] != null) { + await prefs.setString('foto', result['foto']); + setState(() { + fotoUser = result['foto']; + }); + } + + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text("Profil berhasil diperbarui")), + ); + + setState(() { + isEditMode = false; + _pickedFile = null; + }); + } else { + throw result['message']; + } + } catch (e) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text("Gagal menyimpan: $e")), + ); + } + } + + @override + Widget build(BuildContext context) { + bool hasPhoto = + _pickedFile != null || (fotoUser != null && fotoUser!.isNotEmpty); + + return PopScope( + canPop: false, + onPopInvokedWithResult: (didPop, result) async { + if (didPop) return; + // Selalu kembali ke Dashboard Bidan + Navigator.pushAndRemoveUntil( + context, + MaterialPageRoute( + builder: (_) => const DashboardBidanPage(), + ), + (route) => false, + ); + }, + child: Scaffold( + backgroundColor: const Color(0xfff4f6fb), + appBar: AppBar( + backgroundColor: Colors.blue, + elevation: 0, + leading: IconButton( + icon: const Icon(Icons.arrow_back, color: Colors.white), + onPressed: () { + Navigator.pushAndRemoveUntil( + context, + MaterialPageRoute( + builder: (context) => const DashboardBidanPage()), + (route) => false, + ); + }, + ), + title: Text("", + style: GoogleFonts.poppins(color: Colors.white, fontSize: 18)), + ), + body: SingleChildScrollView( + child: Column( + children: [ + Container( + width: double.infinity, + decoration: const BoxDecoration( + color: Colors.blue, + borderRadius: BorderRadius.only( + bottomLeft: Radius.circular(30), + bottomRight: Radius.circular(30), + ), + ), + padding: const EdgeInsets.only(bottom: 30), + child: Column( + children: [ + Stack( + children: [ + CircleAvatar( + radius: 65, + backgroundColor: Colors.white, + child: CircleAvatar( + radius: 60, + backgroundColor: Colors.blue.shade100, + backgroundImage: _pickedFile != null + ? (kIsWeb + ? NetworkImage(_pickedFile!.path) + : FileImage(File(_pickedFile!.path)) + as ImageProvider) + : (fotoUser != null && fotoUser!.isNotEmpty) + ? NetworkImage( + "http://ta.myhost.id/E31230549/mposyandu_api/uploads/$fotoUser") + : null, + child: !hasPhoto + ? const Icon(Icons.person, + size: 60, color: Colors.blue) + : null, + ), + ), + Positioned( + bottom: 0, + right: hasPhoto ? 40 : 0, + child: GestureDetector( + onTap: _pickImage, + child: const CircleAvatar( + radius: 18, + backgroundColor: Colors.black, + child: Icon(Icons.camera_alt, + color: Colors.white, size: 18), + ), + ), + ), + if (hasPhoto) + Positioned( + bottom: 0, + right: 0, + child: GestureDetector( + onTap: _removeImage, + child: const CircleAvatar( + radius: 18, + backgroundColor: Colors.red, + child: Icon(Icons.delete, + color: Colors.white, size: 18), + ), + ), + ), + ], + ), + const SizedBox(height: 12), + Text( + namaC.text, + style: GoogleFonts.poppins( + fontSize: 18, + fontWeight: FontWeight.bold, + color: Colors.white), + ), + ], + ), + ), + Padding( + padding: const EdgeInsets.all(20), + child: Column( + children: [ + Card( + color: Colors.white, + elevation: 2, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(15)), + child: Padding( + padding: const EdgeInsets.all(20), + child: Column( + children: [ + _buildField("Nama Lengkap", namaC), + _buildField("Email", emailC), + _buildPasswordField( + "Password (6 Digit Huruf & Angka)", passwordC), + _buildField("Role User", roleC, isReadOnly: true), + _buildField("No.HP", noHpC, isNumber: true), + _buildField("Status", statusC, isReadOnly: true), + ], + ), + ), + ), + const SizedBox(height: 30), + Row( + children: [ + Expanded( + child: _buildActionButton( + label: "Edit Profil", + color: Colors.orange, + onTap: _enableEdit, + ), + ), + const SizedBox(width: 15), + Expanded( + child: _buildActionButton( + label: "Simpan", + color: Colors.blue, + onTap: _saveProfile, + ), + ), + ], + ), + ], + ), + ), + ], + ), + ), + ), + ); + } + + Widget _buildField(String label, TextEditingController controller, + {bool isReadOnly = false, bool isNumber = false}) { + return Padding( + padding: const EdgeInsets.only(bottom: 15), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(label, + style: GoogleFonts.poppins( + fontSize: 12, + fontWeight: FontWeight.w600, + color: Colors.grey[600])), + const SizedBox(height: 5), + TextField( + controller: controller, + readOnly: isReadOnly || !isEditMode, + keyboardType: isNumber ? TextInputType.phone : TextInputType.text, + style: GoogleFonts.poppins(fontSize: 14), + decoration: InputDecoration( + filled: true, + fillColor: Colors.white, + contentPadding: + const EdgeInsets.symmetric(horizontal: 12, vertical: 12), + border: + OutlineInputBorder(borderRadius: BorderRadius.circular(8)), + ), + ), + ], + ), + ); + } + + Widget _buildPasswordField(String label, TextEditingController controller) { + return Padding( + padding: const EdgeInsets.only(bottom: 15), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(label, + style: GoogleFonts.poppins( + fontSize: 12, + fontWeight: FontWeight.w600, + color: Colors.grey[600])), + const SizedBox(height: 5), + TextField( + controller: controller, + obscureText: _obscurePassword, + readOnly: !isEditMode, + maxLength: 6, + style: GoogleFonts.poppins(fontSize: 14), + decoration: InputDecoration( + counterText: "", + filled: true, + fillColor: Colors.white, + suffixIcon: IconButton( + icon: Icon( + _obscurePassword ? Icons.visibility_off : Icons.visibility), + onPressed: () => + setState(() => _obscurePassword = !_obscurePassword), + ), + border: + OutlineInputBorder(borderRadius: BorderRadius.circular(8)), + ), + ), + ], + ), + ); + } + + Widget _buildActionButton( + {required String label, + required Color color, + required VoidCallback onTap}) { + return OutlinedButton( + onPressed: onTap, + style: OutlinedButton.styleFrom( + foregroundColor: color, + side: BorderSide(color: color, width: 1.5), + padding: const EdgeInsets.symmetric(vertical: 15), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)), + backgroundColor: Colors.white, + ), + child: Text(label, + style: + GoogleFonts.poppins(fontWeight: FontWeight.bold, fontSize: 14)), + ); + } +} diff --git a/lib/ibu/crud_edukasi/edukasi_balita.dart b/lib/ibu/crud_edukasi/edukasi_balita.dart new file mode 100644 index 0000000..0c4dbd6 --- /dev/null +++ b/lib/ibu/crud_edukasi/edukasi_balita.dart @@ -0,0 +1,273 @@ +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:http/http.dart' as http; +import 'dart:convert'; +import 'package:flutter_quill/flutter_quill.dart' + as quill; // Pastikan package ini ada di pubspec.yaml + +import '../../layout/main_layout.dart'; +import '../ibu_drawer.dart'; +import '../dashboard_ibu.dart'; + +class EdukasiBalitaPage extends StatefulWidget { + const EdukasiBalitaPage({super.key}); + + @override + State createState() => _EdukasiBalitaPageState(); +} + +class _EdukasiBalitaPageState extends State { + List _listEdukasi = []; + bool _isLoading = true; + + // Base URL Gambar disesuaikan dengan folder edukasi + final String baseImageUrl = + "http://ta.myhost.id/E31230549/mposyandu_api/upload/edukasi/"; + + @override + void initState() { + super.initState(); + _fetchData(); + } + + Future _fetchData() async { + try { + final response = await http.get( + Uri.parse( + "http://ta.myhost.id/E31230549/mposyandu_api/edukasi_balita/get_edukasi_balita.php", + ), + ); + + if (response.statusCode == 200) { + final data = jsonDecode(response.body); + + if (data['success'] == true) { + setState(() { + _listEdukasi = data['data']; + _isLoading = false; + }); + } else { + setState(() => _isLoading = false); + } + } else { + setState(() => _isLoading = false); + } + } catch (e) { + setState(() => _isLoading = false); + debugPrint("Error fetching data: $e"); + } + } + + // Fungsi untuk membersihkan JSON Quill menjadi teks paragraf biasa + String _parseDescription(String? description) { + String cleanText = description ?? ""; + if (cleanText.startsWith('[') && cleanText.endsWith(']')) { + try { + final List json = jsonDecode(cleanText); + final doc = quill.Document.fromJson(json); + return doc.toPlainText().trim(); + } catch (e) { + return cleanText; + } + } + return cleanText; + } + + @override + Widget build(BuildContext context) { + return PopScope( + canPop: false, + onPopInvokedWithResult: (didPop, result) async { + if (didPop) return; + + Navigator.pushAndRemoveUntil( + context, + MaterialPageRoute( + builder: (_) => const DashboardIbuPage(), + ), + (route) => false, + ); + }, + child: MainLayout( + title: "", + drawer: const IbuDrawer(), + body: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16), + child: Column( + children: [ + /// ===== JUDUL ===== + Text( + "Edukasi Balita", + style: GoogleFonts.poppins( + fontSize: 18, + fontWeight: FontWeight.w600, + color: const Color.fromARGB(255, 24, 25, 26), + ), + ), + + const SizedBox(height: 16), + + Expanded( + child: _isLoading + ? const Center(child: CircularProgressIndicator()) + : _listEdukasi.isEmpty + ? const Center( + child: Text("Belum ada data edukasi balita."), + ) + : RefreshIndicator( + onRefresh: _fetchData, + child: ListView.builder( + itemCount: _listEdukasi.length, + itemBuilder: (context, index) { + final item = _listEdukasi[index]; + + // Gabungkan Base URL dengan nama file gambar + String fullImageUrl = ""; + if (item['gambar'] != null && + item['gambar'].toString().isNotEmpty) { + fullImageUrl = + "$baseImageUrl${item['gambar']}"; + } + + return _EdukasiCard( + title: item['judul'] ?? '', + content: _parseDescription(item['deskripsi']), + ageRange: + "Edukasi untuk balita umur ${item['umur_min']} - ${item['umur_max']} bulan", + imageUrl: fullImageUrl, + icon: Icons.menu_book_rounded, + ); + }, + ), + ), + ), + ], + ), + ), + ), + ); + } +} + +/// ================= CARD EDUKASI ================= +class _EdukasiCard extends StatelessWidget { + final String title; + final String content; + final String ageRange; + final String imageUrl; + final IconData icon; + + const _EdukasiCard({ + required this.title, + required this.content, + required this.ageRange, + required this.imageUrl, + required this.icon, + }); + + @override + Widget build(BuildContext context) { + return Container( + margin: const EdgeInsets.only(bottom: 20), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(14), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.05), + blurRadius: 10, + offset: const Offset(0, 4), + ), + ], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + /// ===== GAMBAR EDUKASI ===== + if (imageUrl.isNotEmpty) + ClipRRect( + borderRadius: + const BorderRadius.vertical(top: Radius.circular(14)), + child: Image.network( + imageUrl, + width: double.infinity, + height: 200, + fit: BoxFit.cover, + errorBuilder: (context, error, stackTrace) { + return Container( + width: double.infinity, + height: 150, + color: Colors.grey[200], + child: const Icon(Icons.broken_image, + color: Colors.grey, size: 50), + ); + }, + ), + ), + + Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + /// ===== HEADER ===== + Row( + children: [ + Container( + padding: const EdgeInsets.all(8), + decoration: BoxDecoration( + color: const Color(0xFFE8F1FF), + borderRadius: BorderRadius.circular(8), + ), + child: Icon( + icon, + color: Colors.blueAccent, + size: 20, + ), + ), + const SizedBox(width: 12), + Expanded( + child: Text( + title, + style: GoogleFonts.poppins( + fontWeight: FontWeight.bold, + fontSize: 15, + color: Colors.black87, + ), + ), + ), + ], + ), + + const SizedBox(height: 12), + + /// ===== UMUR ===== + Text( + ageRange, + style: GoogleFonts.poppins( + fontSize: 12, + fontWeight: FontWeight.w600, + color: Colors.blueAccent, + ), + ), + + const SizedBox(height: 8), + + /// ===== DESKRIPSI (Rapi & Justify) ===== + Text( + content, + textAlign: TextAlign.justify, + style: GoogleFonts.poppins( + fontSize: 13, + height: 1.6, + color: Colors.black54, + ), + ), + ], + ), + ), + ], + ), + ); + } +} diff --git a/lib/ibu/crud_edukasi/edukasi_ibu_hamil.dart b/lib/ibu/crud_edukasi/edukasi_ibu_hamil.dart new file mode 100644 index 0000000..243d65b --- /dev/null +++ b/lib/ibu/crud_edukasi/edukasi_ibu_hamil.dart @@ -0,0 +1,257 @@ +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:http/http.dart' as http; +import 'dart:convert'; +import 'package:flutter_quill/flutter_quill.dart' + as quill; // Tambahkan library ini + +import '../../layout/main_layout.dart'; +import '../ibu_drawer.dart'; +import '../dashboard_ibu.dart'; + +class EdukasiHamilPage extends StatefulWidget { + const EdukasiHamilPage({super.key}); + + @override + State createState() => _EdukasiHamilPageState(); +} + +class _EdukasiHamilPageState extends State { + List _listEdukasi = []; + bool _isLoading = true; + + // Base URL Gambar disesuaikan dengan referensi kode Bidan Anda + final String baseImageUrl = + "http://ta.myhost.id/E31230549/mposyandu_api/upload/edukasi/"; + + @override + void initState() { + super.initState(); + _fetchData(); + } + + Future _fetchData() async { + try { + final response = await http.get( + Uri.parse( + "http://ta.myhost.id/E31230549/mposyandu_api/edukasi_ibu_hamil/get_edukasi_ibu_hamil.php", + ), + ); + + if (response.statusCode == 200) { + final data = jsonDecode(response.body); + + if (data['success'] == true) { + setState(() { + _listEdukasi = data['data']; + _isLoading = false; + }); + } else { + setState(() => _isLoading = false); + } + } else { + setState(() => _isLoading = false); + } + } catch (e) { + setState(() => _isLoading = false); + debugPrint("Error fetching data: $e"); + } + } + + // Fungsi untuk membersihkan JSON Quill menjadi teks paragraf biasa + String _parseDescription(String? description) { + String cleanText = description ?? ""; + if (cleanText.startsWith('[') && cleanText.endsWith(']')) { + try { + final List json = jsonDecode(cleanText); + final doc = quill.Document.fromJson(json); + return doc.toPlainText().trim(); + } catch (e) { + return cleanText; + } + } + return cleanText; + } + + @override + Widget build(BuildContext context) { + return PopScope( + canPop: false, + onPopInvokedWithResult: (didPop, result) async { + if (didPop) return; + Navigator.pushAndRemoveUntil( + context, + MaterialPageRoute(builder: (_) => const DashboardIbuPage()), + (route) => false, + ); + }, + child: MainLayout( + title: "", + drawer: const IbuDrawer(), + body: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16), + child: Column( + children: [ + Text( + "Edukasi Ibu Hamil", + style: GoogleFonts.poppins( + fontSize: 18, + fontWeight: FontWeight.w600, + color: const Color.fromARGB(255, 24, 25, 26), + ), + ), + const SizedBox(height: 16), + Expanded( + child: _isLoading + ? const Center(child: CircularProgressIndicator()) + : _listEdukasi.isEmpty + ? const Center( + child: Text("Belum ada data edukasi hamil.")) + : RefreshIndicator( + onRefresh: _fetchData, + child: ListView.builder( + itemCount: _listEdukasi.length, + itemBuilder: (context, index) { + final item = _listEdukasi[index]; + + // Gabungkan Base URL dengan nama file gambar dari database + String fullImageUrl = ""; + if (item['gambar'] != null && + item['gambar'].toString().isNotEmpty) { + fullImageUrl = + "$baseImageUrl${item['gambar']}"; + } + + return _EdukasiHamilCard( + title: item['judul'] ?? '', + content: _parseDescription(item['deskripsi']), + info: + "Saran untuk usia kehamilan ${item['usia_min']} - ${item['usia_max']} minggu", + imageUrl: fullImageUrl, + icon: Icons.pregnant_woman, + ); + }, + ), + ), + ), + ], + ), + ), + ), + ); + } +} + +class _EdukasiHamilCard extends StatelessWidget { + final String title; + final String content; + final String info; + final String imageUrl; + final IconData icon; + + const _EdukasiHamilCard({ + required this.title, + required this.content, + required this.info, + required this.imageUrl, + required this.icon, + }); + + @override + Widget build(BuildContext context) { + return Container( + margin: const EdgeInsets.only(bottom: 20), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(14), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.05), + blurRadius: 10, + offset: const Offset(0, 4), + ), + ], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + /// ===== GAMBAR EDUKASI ===== + if (imageUrl.isNotEmpty) + ClipRRect( + borderRadius: + const BorderRadius.vertical(top: Radius.circular(14)), + child: Image.network( + imageUrl, + width: double.infinity, + height: 200, + fit: BoxFit.cover, + errorBuilder: (context, error, stackTrace) { + return Container( + width: double.infinity, + height: 150, + color: Colors.grey[200], + child: const Icon(Icons.broken_image, + color: Colors.grey, size: 50), + ); + }, + ), + ), + + Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Container( + padding: const EdgeInsets.all(8), + decoration: BoxDecoration( + color: const Color(0xFFFFE8F0), + borderRadius: BorderRadius.circular(8), + ), + child: Icon(icon, color: Colors.pink, size: 20), + ), + const SizedBox(width: 12), + Expanded( + child: Text( + title, + style: GoogleFonts.poppins( + fontWeight: FontWeight.bold, + fontSize: 15, + color: Colors.black87, + ), + ), + ), + ], + ), + const SizedBox(height: 12), + Text( + info, + style: GoogleFonts.poppins( + fontSize: 12, + fontWeight: FontWeight.w600, + color: Colors.pinkAccent, + ), + ), + const SizedBox(height: 8), + + /// DESKRIPSI (Teks Paragraf Rapi) + Text( + content, + textAlign: + TextAlign.justify, // Agar paragraf rapi rata kanan-kiri + style: GoogleFonts.poppins( + fontSize: 13, + height: 1.6, + color: Colors.black54, + ), + ), + ], + ), + ), + ], + ), + ); + } +} diff --git a/lib/ibu/crud_grafik/grafik_anak_bb_tb.dart b/lib/ibu/crud_grafik/grafik_anak_bb_tb.dart new file mode 100644 index 0000000..d124359 --- /dev/null +++ b/lib/ibu/crud_grafik/grafik_anak_bb_tb.dart @@ -0,0 +1,684 @@ +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:fl_chart/fl_chart.dart'; +import 'package:http/http.dart' as http; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../../layout/main_layout.dart'; +import '../ibu_drawer.dart'; +// Import Dashboard Ibu agar navigasi PopScope berfungsi +import '../dashboard_ibu.dart'; + +class GrafikAnakBBTBPage extends StatefulWidget { + const GrafikAnakBBTBPage({super.key}); + + @override + State createState() => _GrafikAnakBBTBPageState(); +} + +class _GrafikAnakBBTBPageState extends State { + List anakList = []; + bool isLoading = true; + + @override + void initState() { + super.initState(); + getData(); + } + + Future getData() async { + SharedPreferences prefs = await SharedPreferences.getInstance(); + String userId = prefs.getString("id_user") ?? ""; + + if (userId.isEmpty) { + if (mounted) setState(() => isLoading = false); + return; + } + + try { + var response = await http.post( + Uri.parse( + "http://ta.myhost.id/E31230549/mposyandu_api/grafik_balita/get_grafik_bb_tb.php"), + body: {"user_id": userId}, + ); + + var jsonData = json.decode(response.body); + + if (jsonData["success"] && jsonData["data"] != null) { + setState(() { + anakList = jsonData["data"]; + isLoading = false; + }); + } else { + setState(() => isLoading = false); + } + } catch (e) { + if (mounted) setState(() => isLoading = false); + } + } + + String formatUsiaDetail(String tglLahir, String tglPeriksa) { + DateTime birth = DateTime.parse(tglLahir); + DateTime now = DateTime.parse(tglPeriksa); + int years = now.year - birth.year; + int months = now.month - birth.month; + int days = now.day - birth.day; + if (days < 0) { + DateTime lastMonth = DateTime(now.year, now.month, 0); + days += lastMonth.day; + months--; + } + if (months < 0) { + years--; + months += 12; + } + return "$years Thn $months Bln $days Hari"; + } + + @override + Widget build(BuildContext context) { + return PopScope( + canPop: false, + onPopInvokedWithResult: (didPop, result) async { + if (didPop) return; + + // ✅ FIX FINAL: selalu kembali ke Dashboard Ibu + Navigator.pushAndRemoveUntil( + context, + MaterialPageRoute( + builder: (_) => const DashboardIbuPage(), + ), + (route) => false, + ); + }, + child: MainLayout( + title: "", + drawer: const IbuDrawer(), + body: isLoading + ? const Center(child: CircularProgressIndicator()) + : anakList.isEmpty + ? const Center(child: Text("Tidak ada data pemeriksaan BB/TB.")) + : SingleChildScrollView( + padding: const EdgeInsets.all(10), + child: Column( + children: [ + // List Card Grafik dan Status per Anak + ListView.builder( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + itemCount: anakList.length, + itemBuilder: (context, index) { + var anak = anakList[index]; + List spots = []; + List> riwayatDetails = []; + + double lastBB = 0; + double lastTB = 0; + String lastTgl = ""; + + if (anak["riwayat_bbtb"] != null && + anak["riwayat_bbtb"].isNotEmpty) { + for (var p in anak["riwayat_bbtb"]) { + double bb = + double.tryParse(p["bb"].toString()) ?? 0.0; + double tb = + double.tryParse(p["tb"].toString()) ?? 0.0; + + if (bb > 0 && tb >= 45 && tb <= 120) { + String usiaFormat = formatUsiaDetail( + anak["tanggal_lahir"], + p["tanggal_pemeriksaan"]); + spots.add(FlSpot(tb, bb)); + riwayatDetails.add({ + "x": tb, + "y": bb, + "usia_lengkap": usiaFormat + }); + lastBB = bb; + lastTB = tb; + lastTgl = p["tanggal_pemeriksaan"]; + } + } + } + + return GrafikCardKIA_BBTB( + nama: anak["nama"], + jk: anak["jenis_kelamin"], + bb: lastBB, + tb: lastTB, + detailUsiaTerakhir: lastTgl.isNotEmpty + ? formatUsiaDetail( + anak["tanggal_lahir"], lastTgl) + : "-", + historySpots: spots, + historyDetails: riwayatDetails, + ); + }, + ), + + // Keterangan Warna Grafik (Tanpa Card) + _buildGlobalLegendNoCard(), + ], + ), + ), + ), + ); + } + + Widget _buildGlobalLegendNoCard() { + return Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 20), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text("Panduan Membaca Grafik BB/TB:", + style: GoogleFonts.poppins( + fontWeight: FontWeight.bold, + fontSize: 13, + color: Colors.black87)), + const SizedBox(height: 15), + _legendRow(Colors.green, "Garis Hijau (Ideal)", + "Menunjukkan berat badan ideal sesuai tinggi badan anak"), + _legendRow(Colors.red, "Garis Merah (Batas Normal)", + "Batas normal pertumbuhan. Jika titik anak masih di antara garis merah atas dan bawah, maka status gizi masih normal."), + _legendRow(Colors.black, "Garis Hitam (Batas Waspada)", + "Batas waspada. Jika titik berada di luar garis hitam, sebaiknya segera konsultasi ke bidan atau tenaga kesehatan."), + ], + ), + ); + } + + Widget _legendRow(Color color, String label, String desc) { + return Padding( + padding: const EdgeInsets.only(bottom: 15), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Container( + width: 18, + height: 4, + decoration: BoxDecoration( + color: color, borderRadius: BorderRadius.circular(2)), + ), + const SizedBox(width: 12), + Text(label, + style: GoogleFonts.poppins( + fontSize: 11, + fontWeight: FontWeight.bold, + color: Colors.black87)), + ], + ), + const SizedBox(height: 5), + Padding( + padding: const EdgeInsets.only(left: 30), + child: Text(desc, + textAlign: TextAlign.justify, + style: GoogleFonts.poppins( + fontSize: 11, color: Colors.black54, height: 1.4)), + ), + ], + ), + ); + } +} + +class GrafikCardKIA_BBTB extends StatelessWidget { + final String nama; + final String jk; + final double bb; + final double tb; + final String detailUsiaTerakhir; + final List historySpots; + final List> historyDetails; + + const GrafikCardKIA_BBTB({ + super.key, + required this.nama, + required this.jk, + required this.bb, + required this.tb, + required this.detailUsiaTerakhir, + required this.historySpots, + required this.historyDetails, + }); + + double getSDValueAtTB(List spots, double targetTB) { + if (spots.isEmpty) return 0; + if (targetTB <= spots.first.x) return spots.first.y; + if (targetTB >= spots.last.x) return spots.last.y; + for (int i = 0; i < spots.length - 1; i++) { + if (targetTB >= spots[i].x && targetTB <= spots[i + 1].x) { + double ratio = (targetTB - spots[i].x) / (spots[i + 1].x - spots[i].x); + return spots[i].y + ratio * (spots[i + 1].y - spots[i].y); + } + } + return spots.last.y; + } + + Map analisisStatusBBTB(bool isLaki, double tb, double bb) { + if (bb == 0) return {"status": "Belum ada data", "warna": Colors.grey}; + double sd3 = getSDValueAtTB(_getSDRefBBTB_Gabungan(isLaki, 3), tb); + double sd2 = getSDValueAtTB(_getSDRefBBTB_Gabungan(isLaki, 2), tb); + double sdM2 = getSDValueAtTB(_getSDRefBBTB_Gabungan(isLaki, -2), tb); + double sdM3 = getSDValueAtTB(_getSDRefBBTB_Gabungan(isLaki, -3), tb); + + if (bb < sdM3) + return {"status": "Sangat Kurus (Gizi Buruk)", "warna": Colors.black}; + if (bb < sdM2) + return {"status": "Kurus (Gizi Kurang)", "warna": Colors.red}; + if (bb > sd3) return {"status": "Obesitas", "warna": Colors.purple}; + if (bb > sd2) + return {"status": "Berat Badan Lebih", "warna": Colors.orange}; + return {"status": "Normal", "warna": Colors.green}; + } + + @override + Widget build(BuildContext context) { + final bool isLaki = jk == "L"; + final Color headerColor = isLaki ? Colors.blue.shade700 : Colors.pink; + final analisis = analisisStatusBBTB(isLaki, tb, bb); + final Color statusColor = analisis["warna"]; + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Card( + elevation: 2, + shape: + RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)), + margin: const EdgeInsets.only(bottom: 10), + clipBehavior: Clip.antiAlias, + child: Column( + children: [ + Container( + padding: + const EdgeInsets.symmetric(horizontal: 20, vertical: 15), + color: headerColor, + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text(nama.toUpperCase(), + style: GoogleFonts.poppins( + color: Colors.white, + fontWeight: FontWeight.bold, + fontSize: 12)), + Text(isLaki ? "Laki-laki" : "Perempuan", + style: GoogleFonts.poppins( + color: Colors.white, + fontWeight: FontWeight.w500, + fontSize: 12)), + ], + ), + ), + const Divider(height: 1, thickness: 1, color: Colors.black12), + if (historySpots.isEmpty) + Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(vertical: 40), + color: Colors.white, + child: Text("Belum ada riwayat pemeriksaan.", + textAlign: TextAlign.center, + style: GoogleFonts.poppins( + color: Colors.black45, + fontStyle: FontStyle.italic, + fontSize: 13)), + ) + else + Padding( + padding: const EdgeInsets.fromLTRB(10, 25, 25, 20), + child: SizedBox( + width: double.infinity, + height: 250, + child: LineChart( + LineChartData( + lineTouchData: LineTouchData( + touchTooltipData: LineTouchTooltipData( + getTooltipColor: (touchedSpot) => + Colors.blueGrey.withOpacity(0.9), + getTooltipItems: (List touchedSpots) { + return touchedSpots.map((spot) { + if (spot.barIndex != 5) return null; + var detail = historyDetails.firstWhere( + (element) => + element["x"] == spot.x && + element["y"] == spot.y, + orElse: () => {"usia_lengkap": "?"}); + return LineTooltipItem( + "Data Balita\n", + GoogleFonts.poppins( + color: Colors.white, + fontSize: 11, + fontWeight: FontWeight.bold), + children: [ + TextSpan( + text: + "TB: ${spot.x} cm\nBB: ${spot.y} kg\nUsia: ${detail["usia_lengkap"]}", + style: GoogleFonts.poppins( + color: Colors.white, + fontSize: 10, + fontWeight: FontWeight.normal)) + ], + ); + }).toList(); + }, + ), + ), + minX: 45, + maxX: 120, + minY: 2, + maxY: 32, + titlesData: FlTitlesData( + rightTitles: AxisTitles( + sideTitles: SideTitles( + showTitles: true, + reservedSize: 30, + interval: 4, + getTitlesWidget: (val, _) => Text( + val.toInt().toString(), + style: GoogleFonts.poppins( + fontSize: 10, + color: Colors.black54)))), + leftTitles: AxisTitles( + axisNameWidget: Text("BB (kg)", + style: GoogleFonts.poppins( + fontSize: 10, + fontWeight: FontWeight.bold)), + sideTitles: SideTitles( + showTitles: true, + reservedSize: 30, + interval: 4, + getTitlesWidget: (val, _) => Text( + val.toInt().toString(), + style: GoogleFonts.poppins( + fontSize: 10, + color: Colors.black54)))), + topTitles: const AxisTitles( + sideTitles: SideTitles(showTitles: false)), + bottomTitles: AxisTitles( + axisNameWidget: Text("Tinggi Badan (cm)", + style: GoogleFonts.poppins( + fontSize: 10, + fontWeight: FontWeight.bold)), + sideTitles: SideTitles( + showTitles: true, + interval: 10, + getTitlesWidget: (val, _) => Text( + val.toInt().toString(), + style: + GoogleFonts.poppins(fontSize: 9)))), + ), + gridData: const FlGridData( + show: true, + drawVerticalLine: true, + horizontalInterval: 2, + verticalInterval: 5), + borderData: FlBorderData( + show: true, + border: Border.all(color: Colors.black12)), + lineBarsData: [ + _sdLine( + _getSDRefBBTB_Gabungan(isLaki, 3), Colors.black), + _sdLine( + _getSDRefBBTB_Gabungan(isLaki, 2), Colors.red), + _sdLine( + _getSDRefBBTB_Gabungan(isLaki, 0), Colors.green), + _sdLine( + _getSDRefBBTB_Gabungan(isLaki, -2), Colors.red), + _sdLine( + _getSDRefBBTB_Gabungan(isLaki, -3), Colors.black), + LineChartBarData( + spots: historySpots, + isCurved: true, + color: isLaki + ? Colors.blue.shade700 + : Colors.pink.shade600, + barWidth: 4, + dotData: FlDotData( + show: true, + getDotPainter: (spot, p, bar, i) => + FlDotCirclePainter( + radius: 6, + color: Colors.white, + strokeWidth: 3, + strokeColor: isLaki + ? Colors.blue.shade700 + : Colors.pink.shade600))), + ], + ), + ), + ), + ), + ], + ), + ), + + // Kotak Status Gizi di pinggir kiri + if (historySpots.isNotEmpty) + Align( + alignment: Alignment.centerLeft, + child: SizedBox( + width: MediaQuery.of(context).size.width * 0.75, + child: Card( + elevation: 4, + clipBehavior: Clip.antiAlias, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(15)), + margin: const EdgeInsets.only(bottom: 25), + color: statusColor, + child: Padding( + padding: const EdgeInsets.all(12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text("Keterangan Warna Status Gizi:", + style: GoogleFonts.poppins( + fontWeight: FontWeight.bold, + fontSize: 10, + color: Colors.white70)), + const SizedBox(height: 6), + Wrap( + spacing: 8, + runSpacing: 4, + children: [ + _statusLegend(Colors.green, "Normal"), + _statusLegend(Colors.red, "Kurus"), + _statusLegend(Colors.orange, "BB Lebih"), + _statusLegend(Colors.purple, "Obesitas"), + ], + ), + const Divider(color: Colors.white24, height: 20), + RichText( + text: TextSpan( + style: GoogleFonts.poppins( + fontSize: 12, color: Colors.white), + children: [ + const TextSpan( + text: "Status Gizi: ", + style: + TextStyle(fontWeight: FontWeight.normal)), + TextSpan( + text: "${analisis["status"]}", + style: const TextStyle( + fontWeight: FontWeight.bold)), + ], + ), + ), + const SizedBox(height: 4), + Text( + "Terakhir: ${bb}kg / ${tb}cm | Usia: $detailUsiaTerakhir", + style: GoogleFonts.poppins( + fontSize: 10, + fontWeight: FontWeight.w500, + color: Colors.white.withOpacity(0.9))), + ], + ), + ), + ), + ), + ), + ], + ); + } + + Widget _statusLegend(Color color, String text) { + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + width: 7, + height: 7, + decoration: BoxDecoration( + color: color, + shape: BoxShape.circle, + border: Border.all(color: Colors.white, width: 0.5))), + const SizedBox(width: 4), + Text(text, + style: GoogleFonts.poppins(fontSize: 8, color: Colors.white70)), + ], + ); + } + + LineChartBarData _sdLine(List spots, Color color) { + return LineChartBarData( + spots: spots, + color: color.withOpacity(0.35), + barWidth: 1.5, + dotData: const FlDotData(show: false), + isCurved: true); + } + + List _getSDRefBBTB_Gabungan(bool isLaki, int type) { + if (isLaki) { + switch (type) { + case 3: + return const [ + FlSpot(45, 3.0), + FlSpot(50, 4.3), + FlSpot(60, 7.3), + FlSpot(70, 10.1), + FlSpot(80, 12.8), + FlSpot(90, 15.6), + FlSpot(100, 19.1), + FlSpot(110, 23.1), + FlSpot(120, 27.7) + ]; + case 2: + return const [ + FlSpot(45, 2.8), + FlSpot(50, 4.0), + FlSpot(60, 6.7), + FlSpot(70, 9.3), + FlSpot(80, 11.8), + FlSpot(90, 14.3), + FlSpot(100, 17.5), + FlSpot(110, 21.1), + FlSpot(120, 25.2) + ]; + case 0: + return const [ + FlSpot(45, 2.4), + FlSpot(50, 3.4), + FlSpot(60, 5.7), + FlSpot(70, 7.9), + FlSpot(80, 10.0), + FlSpot(90, 12.2), + FlSpot(100, 14.8), + FlSpot(110, 17.8), + FlSpot(120, 21.1) + ]; + case -2: + return const [ + FlSpot(45, 2.1), + FlSpot(50, 2.9), + FlSpot(60, 4.9), + FlSpot(70, 6.8), + FlSpot(80, 8.6), + FlSpot(90, 10.5), + FlSpot(100, 12.8), + FlSpot(110, 15.3), + FlSpot(120, 18.0) + ]; + case -3: + return const [ + FlSpot(45, 1.9), + FlSpot(50, 2.7), + FlSpot(60, 4.5), + FlSpot(70, 6.3), + FlSpot(80, 7.9), + FlSpot(90, 9.7), + FlSpot(100, 11.8), + FlSpot(110, 14.1), + FlSpot(120, 16.5) + ]; + } + } else { + switch (type) { + case 3: + return const [ + FlSpot(45, 2.9), + FlSpot(50, 4.2), + FlSpot(60, 7.0), + FlSpot(70, 9.8), + FlSpot(80, 12.6), + FlSpot(90, 15.7), + FlSpot(100, 19.5), + FlSpot(110, 23.9), + FlSpot(120, 29.1) + ]; + case 2: + return const [ + FlSpot(45, 2.7), + FlSpot(50, 3.8), + FlSpot(60, 6.4), + FlSpot(70, 9.0), + FlSpot(80, 11.6), + FlSpot(90, 14.4), + FlSpot(100, 17.8), + FlSpot(110, 21.7), + FlSpot(120, 26.3) + ]; + case 0: + return const [ + FlSpot(45, 2.3), + FlSpot(50, 3.3), + FlSpot(60, 5.4), + FlSpot(70, 7.6), + FlSpot(80, 9.8), + FlSpot(90, 12.2), + FlSpot(100, 15.0), + FlSpot(110, 18.3), + FlSpot(120, 21.9) + ]; + case -2: + return const [ + FlSpot(45, 2.0), + FlSpot(50, 2.8), + FlSpot(60, 4.6), + FlSpot(70, 6.5), + FlSpot(80, 8.3), + FlSpot(90, 10.3), + FlSpot(100, 12.8), + FlSpot(110, 15.4), + FlSpot(120, 18.4) + ]; + case -3: + return const [ + FlSpot(45, 1.8), + FlSpot(50, 2.6), + FlSpot(60, 4.3), + FlSpot(70, 6.0), + FlSpot(80, 7.7), + FlSpot(90, 9.5), + FlSpot(100, 11.7), + FlSpot(110, 14.1), + FlSpot(120, 16.8) + ]; + } + } + return []; + } +} diff --git a/lib/ibu/crud_grafik/grafik_anak_bb_usia.dart b/lib/ibu/crud_grafik/grafik_anak_bb_usia.dart new file mode 100644 index 0000000..dc3950a --- /dev/null +++ b/lib/ibu/crud_grafik/grafik_anak_bb_usia.dart @@ -0,0 +1,725 @@ +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:fl_chart/fl_chart.dart'; +import 'package:http/http.dart' as http; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../../layout/main_layout.dart'; +import '../ibu_drawer.dart'; +// Import Dashboard Ibu agar navigasi PopScope berfungsi +import '../dashboard_ibu.dart'; + +class GrafikAnakBBUsiaPage extends StatefulWidget { + const GrafikAnakBBUsiaPage({super.key}); + + @override + State createState() => _GrafikAnakIbuPageState(); +} + +class _GrafikAnakIbuPageState extends State { + List anakList = []; + bool isLoading = true; + + @override + void initState() { + super.initState(); + getData(); + } + + Future getData() async { + SharedPreferences prefs = await SharedPreferences.getInstance(); + String userId = prefs.getString("id_user") ?? ""; + + try { + var response = await http.post( + Uri.parse( + "http://ta.myhost.id/E31230549/mposyandu_api/grafik_balita/get_grafik_balita.php"), + body: {"user_id": userId}, + ); + + var jsonData = json.decode(response.body); + + if (jsonData["success"] && + jsonData["data"] != null && + jsonData["data"].isNotEmpty) { + Map groupedAnak = {}; + for (var item in jsonData["data"]) { + String id = item["id"].toString(); + if (!groupedAnak.containsKey(id)) { + groupedAnak[id] = { + "nama": item["nama"], + "jenis_kelamin": item["jenis_kelamin"], + "tanggal_lahir": item["tanggal_lahir"], + "pemeriksaan": [] + }; + } + + if (item["bb"] != null && + item["bb"] != "-" && + item["tanggal_pemeriksaan"] != null) { + groupedAnak[id]["pemeriksaan"].add({ + "tgl_periksa": item["tanggal_pemeriksaan"], + "bb": double.tryParse(item["bb"].toString()) ?? 0.0 + }); + } + } + + setState(() { + anakList = groupedAnak.values.toList(); + isLoading = false; + }); + } else { + setState(() { + anakList = []; + isLoading = false; + }); + } + } catch (e) { + debugPrint("Error fetching data: $e"); + setState(() => isLoading = false); + } + } + + int hitungUmurBulanPeriksa(String tglLahir, String tglPeriksa) { + try { + DateTime lahir = DateTime.parse(tglLahir); + DateTime periksa = DateTime.parse(tglPeriksa); + int months = + (periksa.year - lahir.year) * 12 + periksa.month - lahir.month; + return months < 0 ? 0 : months; + } catch (e) { + return 0; + } + } + + String formatUsiaLengkap(String tglLahir, String tglPeriksa) { + try { + DateTime birth = DateTime.parse(tglLahir); + DateTime now = DateTime.parse(tglPeriksa); + int years = now.year - birth.year; + int months = now.month - birth.month; + int days = now.day - birth.day; + + if (days < 0) { + DateTime lastMonth = DateTime(now.year, now.month, 0); + days += lastMonth.day; + months--; + } + if (months < 0) { + years--; + months += 12; + } + return "$years Thn $months Bln $days Hari"; + } catch (e) { + return "-"; + } + } + + @override + Widget build(BuildContext context) { + return PopScope( + canPop: false, + onPopInvokedWithResult: (didPop, result) async { + if (didPop) return; + + // ✅ FIX FINAL: selalu kembali ke Dashboard Ibu + Navigator.pushAndRemoveUntil( + context, + MaterialPageRoute( + builder: (_) => const DashboardIbuPage(), + ), + (route) => false, + ); + }, + child: MainLayout( + title: "", + drawer: const IbuDrawer(), + body: isLoading + ? const Center(child: CircularProgressIndicator()) + : Padding( + padding: const EdgeInsets.all(8.0), + child: anakList.isEmpty + ? _buildEmptyState("Tidak ada data pemeriksaan bb/u.") + : SingleChildScrollView( + child: Column( + children: [ + ListView.builder( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + itemCount: anakList.length, + itemBuilder: (context, index) { + var anak = anakList[index]; + + if (anak["pemeriksaan"].isEmpty) { + return _buildNoExaminationCard( + anak["nama"], anak["jenis_kelamin"]); + } + + List> detailSpots = []; + List spots = []; + double lastBB = 0; + int lastBulan = 0; + String lastTgl = ""; + + for (var p in anak["pemeriksaan"]) { + int bulan = hitungUmurBulanPeriksa( + anak["tanggal_lahir"], p["tgl_periksa"]); + double berat = p["bb"]; + String usiaFormat = formatUsiaLengkap( + anak["tanggal_lahir"], p["tgl_periksa"]); + + spots.add(FlSpot(bulan.toDouble(), berat)); + detailSpots.add({ + "x": bulan.toDouble(), + "y": berat, + "usia_lengkap": usiaFormat, + }); + + lastBB = berat; + lastBulan = bulan; + lastTgl = p["tgl_periksa"]; + } + + return GrafikCardKIA( + nama: anak["nama"], + jk: anak["jenis_kelamin"], + umurBulan: lastBulan, + bb: lastBB, + detailUsiaTerakhir: lastTgl.isNotEmpty + ? formatUsiaLengkap( + anak["tanggal_lahir"], lastTgl) + : "-", + historySpots: spots, + historyDetails: detailSpots, + ); + }, + ), + _buildGlobalLegendNoCard(), + ], + ), + ), + ), + ), + ); + } + + Widget _buildEmptyState(String pesan) { + return Center( + child: Text( + pesan, + textAlign: TextAlign.center, + style: GoogleFonts.poppins(fontSize: 14, color: Colors.black), + ), + ); + } + + Widget _buildNoExaminationCard(String nama, String jk) { + final bool isLaki = jk == "L"; + final Color headerColor = isLaki ? Colors.blue.shade700 : Colors.pink; + + return Card( + elevation: 2, + margin: const EdgeInsets.only(bottom: 20), + clipBehavior: Clip.antiAlias, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)), + child: Column( + children: [ + Container( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + color: headerColor, + child: Row( + children: [ + Text(nama.toUpperCase(), + style: GoogleFonts.poppins( + fontWeight: FontWeight.bold, + fontSize: 12, + color: Colors.white)), + const Spacer(), + Text(isLaki ? "Laki-laki" : "Perempuan", + style: + GoogleFonts.poppins(fontSize: 12, color: Colors.white)), + ], + ), + ), + Padding( + padding: const EdgeInsets.all(20.0), + child: Text( + "Belum ada riwayat pemeriksaan berat badan.", + textAlign: TextAlign.center, + style: GoogleFonts.poppins( + color: Colors.grey, + fontSize: 13, + fontStyle: FontStyle.italic), + ), + ), + ], + ), + ); + } + + Widget _buildGlobalLegendNoCard() { + return Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 20), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text("Keterangan Grafik BB/U:", + style: GoogleFonts.poppins( + fontWeight: FontWeight.bold, + fontSize: 13, + color: Colors.black87)), + const SizedBox(height: 15), + _legendRow(Colors.green, "Garis Hijau (Ideal)", + "Menunjukkan berat badan rata-rata anak sesuai usianya. Jika grafik berat badan anak berada di sekitar garis hijau, berarti pertumbuhan berat badan anak termasuk normal"), + _legendRow(Colors.red, "Garis Merah (Batas Normal)", + "Menunjukkan batas bawah dan batas atas kategori normal. Jika berat badan anak berada di antara dua garis merah, pertumbuhan berat badan masih termasuk kategori normal sesuai usia."), + _legendRow(Colors.black, "Garis Hitam (Batas Waspada)", + "Menunjukkan batas di luar kategori normal. Jika grafik berada di bawah garis hitam bawah, anak berisiko kekurangan gizi. Jika berada di atas garis hitam atas, berat badan anak berlebih."), + ], + ), + ); + } + + Widget _legendRow(Color color, String label, String desc) { + return Padding( + padding: const EdgeInsets.only(bottom: 15), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Container( + width: 18, + height: 4, + decoration: BoxDecoration( + color: color, borderRadius: BorderRadius.circular(2)), + ), + const SizedBox(width: 12), + Text(label, + style: GoogleFonts.poppins( + fontSize: 11, + fontWeight: FontWeight.bold, + color: Colors.black87)), + ], + ), + const SizedBox(height: 5), + Padding( + padding: const EdgeInsets.only(left: 30), + child: Text(desc, + textAlign: TextAlign.justify, + style: GoogleFonts.poppins( + fontSize: 11, color: Colors.black54, height: 1.4)), + ), + ], + ), + ); + } +} + +class GrafikCardKIA extends StatelessWidget { + final String nama; + final String jk; + final int umurBulan; + final double bb; + final String detailUsiaTerakhir; + final List historySpots; + final List> historyDetails; + + const GrafikCardKIA({ + super.key, + required this.nama, + required this.jk, + required this.umurBulan, + required this.bb, + required this.detailUsiaTerakhir, + required this.historySpots, + required this.historyDetails, + }); + + double getSDValueAtAge(List spots, int targetUmur) { + if (spots.isEmpty) return 0; + for (int i = 0; i < spots.length - 1; i++) { + if (targetUmur >= spots[i].x && targetUmur <= spots[i + 1].x) { + double ratio = + (targetUmur - spots[i].x) / (spots[i + 1].x - spots[i].x); + return spots[i].y + ratio * (spots[i + 1].y - spots[i].y); + } + } + return spots.last.y; + } + + Map analisisGizi(bool isLaki, int umur, double bb) { + double sd3 = getSDValueAtAge(_getSDData(isLaki, 3), umur); + double sd2 = getSDValueAtAge(_getSDData(isLaki, 2), umur); + double sdM2 = getSDValueAtAge(_getSDData(isLaki, -2), umur); + double sdM3 = getSDValueAtAge(_getSDData(isLaki, -3), umur); + + if (bb > sd3) + return {"status": "Sangat Berlebih (Obesitas)", "warna": Colors.purple}; + if (bb > sd2) + return {"status": "Berat Badan Lebih", "warna": Colors.orange}; + if (bb >= sdM2) + return {"status": "Berat Badan Normal", "warna": Colors.green}; + if (bb >= sdM3) + return {"status": "Berat Badan Kurang", "warna": Colors.red}; + return {"status": "Risiko Gizi Buruk", "warna": Colors.black}; + } + + @override + Widget build(BuildContext context) { + final bool isLaki = jk == "L"; + final Color headerColor = isLaki ? Colors.blue : Colors.pink; + final Color accentColor = + isLaki ? Colors.blue.shade700 : const Color(0xFFE91E63); + + final analisis = analisisGizi(isLaki, umurBulan, bb); + final Color statusColor = analisis["warna"]; + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Card( + elevation: 4, + clipBehavior: Clip.antiAlias, + shape: + RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)), + margin: const EdgeInsets.only(bottom: 10), + child: Column( + children: [ + Container( + padding: + const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + color: headerColor, + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text(nama.toUpperCase(), + style: GoogleFonts.poppins( + color: Colors.white, + fontWeight: FontWeight.bold, + fontSize: 12)), + Text(isLaki ? "Laki-laki" : "Perempuan", + style: GoogleFonts.poppins( + color: Colors.white, fontSize: 12)), + ], + ), + ), + Padding( + padding: const EdgeInsets.fromLTRB(10, 25, 25, 20), + child: SizedBox( + width: double.infinity, + height: 250, + child: LineChart( + LineChartData( + lineTouchData: LineTouchData( + touchTooltipData: LineTouchTooltipData( + getTooltipColor: (touchedSpot) => + Colors.blueGrey.withOpacity(0.9), + getTooltipItems: (List touchedSpots) { + return touchedSpots.map((spot) { + if (spot.barIndex != 5) return null; + var detail = historyDetails.firstWhere( + (element) => + element["x"] == spot.x && + element["y"] == spot.y, + orElse: () => + {"usia_lengkap": "${spot.x.toInt()} Bulan"}, + ); + return LineTooltipItem( + "Data Balita\n", + GoogleFonts.poppins( + color: Colors.white, + fontSize: 11, + fontWeight: FontWeight.bold), + children: [ + TextSpan( + text: + "Berat: ${spot.y} kg\nUsia: ${detail["usia_lengkap"]}", + style: GoogleFonts.poppins( + color: Colors.white, + fontSize: 10, + fontWeight: FontWeight.normal), + ), + ], + ); + }).toList(); + }, + ), + ), + minX: 0, + maxX: 60, + minY: 2, + maxY: 30, + titlesData: FlTitlesData( + rightTitles: AxisTitles( + sideTitles: SideTitles( + showTitles: true, + reservedSize: 30, + getTitlesWidget: (val, _) => Text( + val.toInt().toString(), + style: GoogleFonts.poppins( + fontSize: 10, color: Colors.black54)))), + leftTitles: AxisTitles( + axisNameWidget: Text("BB (kg)", + style: GoogleFonts.poppins( + fontSize: 10, fontWeight: FontWeight.bold)), + sideTitles: SideTitles( + showTitles: true, + reservedSize: 30, + getTitlesWidget: (val, _) => Text( + val.toInt().toString(), + style: GoogleFonts.poppins( + fontSize: 10, color: Colors.black54)))), + topTitles: const AxisTitles( + sideTitles: SideTitles(showTitles: false)), + bottomTitles: AxisTitles( + axisNameWidget: Text("Usia (Bulan/Tahun)", + style: GoogleFonts.poppins( + fontSize: 10, fontWeight: FontWeight.bold)), + sideTitles: SideTitles( + showTitles: true, + interval: 12, + getTitlesWidget: (val, _) => Text( + val == 0 + ? "Lahir" + : "${(val / 12).toInt()} Thn", + style: GoogleFonts.poppins(fontSize: 9)))), + ), + gridData: const FlGridData( + show: true, + drawVerticalLine: true, + horizontalInterval: 5, + verticalInterval: 12), + borderData: FlBorderData( + show: true, + border: Border.all(color: Colors.black12)), + lineBarsData: [ + _sdLine(_getSDData(isLaki, 3), Colors.black), + _sdLine(_getSDData(isLaki, 2), Colors.red), + _sdLine(_getSDData(isLaki, 0), Colors.green), + _sdLine(_getSDData(isLaki, -2), Colors.red), + _sdLine(_getSDData(isLaki, -3), Colors.black), + LineChartBarData( + spots: historySpots, + isCurved: true, + color: accentColor, + barWidth: 4, + dotData: FlDotData( + show: true, + getDotPainter: (spot, p, bar, i) => + FlDotCirclePainter( + radius: 6, + color: Colors.white, + strokeWidth: 3, + strokeColor: accentColor)), + ), + ], + ), + ), + ), + ), + ], + ), + ), + if (historySpots.isNotEmpty) + Align( + alignment: Alignment.centerLeft, + child: SizedBox( + width: MediaQuery.of(context).size.width * 0.75, + child: Card( + elevation: 4, + clipBehavior: Clip.antiAlias, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(15)), + margin: const EdgeInsets.only(bottom: 25), + color: statusColor, + child: Padding( + padding: const EdgeInsets.all(12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text("Keterangan Warna Status Gizi:", + style: GoogleFonts.poppins( + fontWeight: FontWeight.bold, + fontSize: 10, + color: Colors.white70)), + const SizedBox(height: 6), + Wrap( + spacing: 8, + runSpacing: 4, + children: [ + _statusLegend(Colors.green, "Normal"), + _statusLegend(Colors.red, "Kurang"), + _statusLegend(Colors.orange, "BB Lebih"), + _statusLegend(Colors.purple, "Obesitas"), + ], + ), + const Divider(color: Colors.white24, height: 20), + RichText( + text: TextSpan( + style: GoogleFonts.poppins( + fontSize: 12, color: Colors.white), + children: [ + const TextSpan( + text: "Status Berat Badan: ", + style: + TextStyle(fontWeight: FontWeight.normal)), + TextSpan( + text: "${analisis["status"]}", + style: const TextStyle( + fontWeight: FontWeight.bold)), + ], + ), + ), + const SizedBox(height: 4), + Text("BB Terakhir: $bb kg | Usia: $detailUsiaTerakhir", + style: GoogleFonts.poppins( + fontSize: 10, + fontWeight: FontWeight.w500, + color: Colors.white.withOpacity(0.9))), + ], + ), + ), + ), + ), + ), + ], + ); + } + + Widget _statusLegend(Color color, String text) { + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + width: 7, + height: 7, + decoration: BoxDecoration( + color: color, + shape: BoxShape.circle, + border: Border.all(color: Colors.white, width: 0.5))), + const SizedBox(width: 4), + Text(text, + style: GoogleFonts.poppins(fontSize: 8, color: Colors.white70)), + ], + ); + } + + LineChartBarData _sdLine(List spots, Color color) { + return LineChartBarData( + spots: spots, + color: color.withOpacity(0.35), + barWidth: 1.5, + dotData: const FlDotData(show: false), + isCurved: true); + } + + List _getSDData(bool isLaki, int type) { + if (isLaki) { + if (type == 3) + return const [ + FlSpot(0, 5.0), + FlSpot(6, 9.8), + FlSpot(12, 13.3), + FlSpot(24, 16.5), + FlSpot(36, 19.7), + FlSpot(48, 23.2), + FlSpot(60, 27.0) + ]; + if (type == 2) + return const [ + FlSpot(0, 4.4), + FlSpot(6, 9.0), + FlSpot(12, 12.0), + FlSpot(24, 15.0), + FlSpot(36, 17.8), + FlSpot(48, 21.0), + FlSpot(60, 24.2) + ]; + if (type == 0) + return const [ + FlSpot(0, 3.3), + FlSpot(6, 7.9), + FlSpot(12, 9.6), + FlSpot(24, 12.2), + FlSpot(36, 14.3), + FlSpot(48, 16.3), + FlSpot(60, 18.3) + ]; + if (type == -2) + return const [ + FlSpot(0, 2.5), + FlSpot(6, 6.4), + FlSpot(12, 7.7), + FlSpot(24, 9.7), + FlSpot(36, 11.3), + FlSpot(48, 12.7), + FlSpot(60, 14.1) + ]; + if (type == -3) + return const [ + FlSpot(0, 2.1), + FlSpot(6, 5.9), + FlSpot(12, 7.0), + FlSpot(24, 8.8), + FlSpot(36, 10.3), + FlSpot(48, 11.7), + FlSpot(60, 13.0) + ]; + } else { + if (type == 3) + return const [ + FlSpot(0, 4.8), + FlSpot(6, 9.3), + FlSpot(12, 12.9), + FlSpot(24, 16.5), + FlSpot(36, 20.2), + FlSpot(48, 24.4), + FlSpot(60, 29.0) + ]; + if (type == 2) + return const [ + FlSpot(0, 4.2), + FlSpot(6, 8.5), + FlSpot(12, 11.5), + FlSpot(24, 14.8), + FlSpot(36, 18.1), + FlSpot(48, 21.5), + FlSpot(60, 25.0) + ]; + if (type == 0) + return const [ + FlSpot(0, 3.2), + FlSpot(6, 7.3), + FlSpot(12, 8.9), + FlSpot(24, 11.5), + FlSpot(36, 13.9), + FlSpot(48, 16.1), + FlSpot(60, 18.2) + ]; + if (type == -2) + return const [ + FlSpot(0, 2.4), + FlSpot(6, 5.8), + FlSpot(12, 7.0), + FlSpot(24, 9.0), + FlSpot(36, 10.8), + FlSpot(48, 12.3), + FlSpot(60, 13.8) + ]; + if (type == -3) + return const [ + FlSpot(0, 2.0), + FlSpot(6, 5.3), + FlSpot(12, 6.3), + FlSpot(24, 8.1), + FlSpot(36, 9.8), + FlSpot(48, 11.2), + FlSpot(60, 12.5) + ]; + } + return []; + } +} diff --git a/lib/ibu/crud_grafik/grafik_anak_tb_usia.dart b/lib/ibu/crud_grafik/grafik_anak_tb_usia.dart new file mode 100644 index 0000000..e474822 --- /dev/null +++ b/lib/ibu/crud_grafik/grafik_anak_tb_usia.dart @@ -0,0 +1,709 @@ +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:fl_chart/fl_chart.dart'; +import 'package:http/http.dart' as http; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../../layout/main_layout.dart'; +import '../ibu_drawer.dart'; +// Import Dashboard Ibu agar navigasi PopScope berfungsi +import '../dashboard_ibu.dart'; + +class GrafikAnakTBUPage extends StatefulWidget { + const GrafikAnakTBUPage({super.key}); + + @override + State createState() => _GrafikAnakTBUPageState(); +} + +class _GrafikAnakTBUPageState extends State { + List anakList = []; + bool isLoading = true; + + @override + void initState() { + super.initState(); + getData(); + } + + Future getData() async { + SharedPreferences prefs = await SharedPreferences.getInstance(); + String userId = prefs.getString("id_user") ?? ""; + + if (userId.isEmpty) { + if (mounted) setState(() => isLoading = false); + return; + } + + try { + var response = await http.post( + Uri.parse( + "http://ta.myhost.id/E31230549/mposyandu_api/grafik_balita/get_grafik_tb_u.php"), + body: {"user_id": userId}, + ); + + var jsonData = json.decode(response.body); + + if (jsonData["success"] && jsonData["data"] != null) { + setState(() { + anakList = jsonData["data"]; + isLoading = false; + }); + } else { + setState(() => isLoading = false); + } + } catch (e) { + if (mounted) setState(() => isLoading = false); + } + } + + int hitungUmurBulan(String tglLahir, String tglPeriksa) { + try { + DateTime lahir = DateTime.parse(tglLahir); + DateTime periksa = DateTime.parse(tglPeriksa); + int months = + (periksa.year - lahir.year) * 12 + periksa.month - lahir.month; + return months < 0 ? 0 : months; + } catch (e) { + return 0; + } + } + + String formatUsiaDetail(String tglLahir, String tglPeriksa) { + try { + DateTime birth = DateTime.parse(tglLahir); + DateTime now = DateTime.parse(tglPeriksa); + int years = now.year - birth.year; + int months = now.month - birth.month; + int days = now.day - birth.day; + + if (days < 0) { + DateTime lastMonth = DateTime(now.year, now.month, 0); + days += lastMonth.day; + months--; + } + if (months < 0) { + years--; + months += 12; + } + return "$years Thn $months Bln $days Hari"; + } catch (e) { + return "-"; + } + } + + @override + Widget build(BuildContext context) { + return PopScope( + canPop: false, + onPopInvokedWithResult: (didPop, result) async { + if (didPop) return; + + // ✅ FIX FINAL: selalu kembali ke Dashboard Ibu + Navigator.pushAndRemoveUntil( + context, + MaterialPageRoute( + builder: (_) => const DashboardIbuPage(), + ), + (route) => false, + ); + }, + child: MainLayout( + title: "", + drawer: const IbuDrawer(), + body: isLoading + ? const Center(child: CircularProgressIndicator()) + : anakList.isEmpty + ? Center( + child: Text("Tidak ada data pemeriksaan tb/u.", + style: GoogleFonts.poppins(color: Colors.black))) + : SingleChildScrollView( + padding: const EdgeInsets.all(10), + child: Column( + children: [ + // List Card per Anak + ListView.builder( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + itemCount: anakList.length, + itemBuilder: (context, index) { + var anak = anakList[index]; + + // Kondisi Jika pemeriksaan kosong + if (anak["riwayat"] == null || + anak["riwayat"].isEmpty) { + return _buildNoExaminationCard( + anak["nama"], anak["jenis_kelamin"]); + } + + List spots = []; + List> riwayatDetails = []; + double lastTB = 0; + int lastBulan = 0; + String lastTgl = ""; + + for (var p in anak["riwayat"]) { + double tbVal = + double.tryParse(p["tb"].toString()) ?? 0.0; + if (tbVal > 0) { + int bulan = hitungUmurBulan( + anak["tanggal_lahir"], + p["tanggal_pemeriksaan"]); + String usiaFormat = formatUsiaDetail( + anak["tanggal_lahir"], + p["tanggal_pemeriksaan"]); + + spots.add(FlSpot(bulan.toDouble(), tbVal)); + riwayatDetails.add({ + "x": bulan.toDouble(), + "y": tbVal, + "usia_lengkap": usiaFormat + }); + lastTB = tbVal; + lastBulan = bulan; + lastTgl = p["tanggal_pemeriksaan"]; + } + } + + if (spots.isEmpty) { + return _buildNoExaminationCard( + anak["nama"], anak["jenis_kelamin"]); + } + + return GrafikCardKIA_TB( + nama: anak["nama"], + jk: anak["jenis_kelamin"], + umurBulan: lastBulan, + tb: lastTB, + detailUsiaTerakhir: lastTgl.isNotEmpty + ? formatUsiaDetail( + anak["tanggal_lahir"], lastTgl) + : "-", + historySpots: spots, + historyDetails: riwayatDetails, + ); + }, + ), + + // Keterangan Warna Grafik + _buildGlobalLegendNoCard(), + ], + ), + ), + ), + ); + } + + Widget _buildNoExaminationCard(String nama, String jk) { + final bool isLaki = jk == "L"; + final Color headerColor = isLaki ? Colors.blue.shade700 : Colors.pink; + + return Card( + elevation: 2, + margin: const EdgeInsets.only(bottom: 20), + clipBehavior: Clip.antiAlias, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)), + child: Column( + children: [ + Container( + padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 15), + color: headerColor, + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text(nama.toUpperCase(), + style: GoogleFonts.poppins( + fontWeight: FontWeight.bold, + fontSize: 12, + color: Colors.white)), + Text(isLaki ? "Laki-laki" : "Perempuan", + style: GoogleFonts.poppins( + fontSize: 12, + color: Colors.white, + fontWeight: FontWeight.w500)), + ], + ), + ), + Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(vertical: 40), + color: const Color(0xFFF8F4F9), + child: Text( + "Belum ada riwayat pemeriksaan tinggi badan.", + textAlign: TextAlign.center, + style: GoogleFonts.poppins( + color: Colors.black45, + fontSize: 13, + fontStyle: FontStyle.italic), + ), + ), + ], + ), + ); + } + + Widget _buildGlobalLegendNoCard() { + return Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 20), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text("Panduan Membaca Grafik TB/U:", + style: GoogleFonts.poppins( + fontWeight: FontWeight.bold, + fontSize: 13, + color: Colors.black87)), + const SizedBox(height: 15), + _legendRow(Colors.green, "Garis Hijau (Median)", + "Menunjukkan tinggi badan rata-rata anak sesuai usianya. Jika posisi garis pertumbuhan anak berada di sekitar garis ini, pertumbuhan tinggi badan anak termasuk normal."), + _legendRow(Colors.red, "Garis Merah (Batas Normal)", + "Merupakan batas bawah dan batas atas kategori normal. Jika tinggi badan anak berada di antara dua garis merah, tinggi badan anak masih termasuk kategori normal sesuai usia."), + _legendRow(Colors.black, "Garis Hitam (Batas Kritis)", + "Menunjukkan batas di luar kategori normal. Jika tinggi badan berada di bawah garis hitam bawah, anak termasuk sangat pendek. Jika berada di atas garis hitam atas, anak termasuk lebih tinggi dari rata-rata."), + ], + ), + ); + } + + Widget _legendRow(Color color, String label, String desc) { + return Padding( + padding: const EdgeInsets.only(bottom: 15), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Container( + width: 18, + height: 4, + decoration: BoxDecoration( + color: color, borderRadius: BorderRadius.circular(2)), + ), + const SizedBox(width: 12), + Text(label, + style: GoogleFonts.poppins( + fontSize: 11, + fontWeight: FontWeight.bold, + color: Colors.black87)), + ], + ), + const SizedBox(height: 5), + Padding( + padding: const EdgeInsets.only(left: 30), + child: Text(desc, + textAlign: TextAlign.justify, + style: GoogleFonts.poppins( + fontSize: 11, color: Colors.black54, height: 1.4)), + ), + ], + ), + ); + } +} + +class GrafikCardKIA_TB extends StatelessWidget { + final String nama; + final String jk; + final int umurBulan; + final double tb; + final String detailUsiaTerakhir; + final List historySpots; + final List> historyDetails; + + const GrafikCardKIA_TB({ + super.key, + required this.nama, + required this.jk, + required this.umurBulan, + required this.tb, + required this.detailUsiaTerakhir, + required this.historySpots, + required this.historyDetails, + }); + + double getSDValueAtAge(List spots, int targetUmur) { + if (spots.isEmpty) return 0; + for (int i = 0; i < spots.length - 1; i++) { + if (targetUmur >= spots[i].x && targetUmur <= spots[i + 1].x) { + double ratio = + (targetUmur - spots[i].x) / (spots[i + 1].x - spots[i].x); + return spots[i].y + ratio * (spots[i + 1].y - spots[i].y); + } + } + return spots.last.y; + } + + Map analisisStatusTB(bool isLaki, int umur, double tinggi) { + double sd3 = getSDValueAtAge(_getSDRefTBU(isLaki, 3), umur); + double sdM2 = getSDValueAtAge(_getSDRefTBU(isLaki, -2), umur); + double sdM3 = getSDValueAtAge(_getSDRefTBU(isLaki, -3), umur); + + if (tinggi < sdM3) + return { + "status": "Sangat Pendek (Severely Stunted)", + "warna": Colors.black + }; + if (tinggi < sdM2) + return {"status": "Pendek (Stunted)", "warna": Colors.red}; + if (tinggi > sd3) return {"status": "Tinggi", "warna": Colors.purple}; + return {"status": "Normal", "warna": Colors.green}; + } + + @override + Widget build(BuildContext context) { + final bool isLaki = jk == "L"; + final Color headerColor = isLaki ? Colors.blue.shade700 : Colors.pink; + final Color accentColor = + isLaki ? Colors.blue.shade700 : const Color(0xFFE91E63); + final analisis = analisisStatusTB(isLaki, umurBulan, tb); + final Color statusColor = analisis["warna"]; + final filteredSpots = historySpots.where((spot) => spot.x <= 60).toList(); + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Card( + elevation: 2, + shape: + RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)), + margin: const EdgeInsets.only(bottom: 10), + clipBehavior: Clip.antiAlias, + child: Column( + children: [ + Container( + padding: + const EdgeInsets.symmetric(horizontal: 20, vertical: 15), + color: headerColor, + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text(nama.toUpperCase(), + style: GoogleFonts.poppins( + color: Colors.white, + fontWeight: FontWeight.bold, + fontSize: 12)), + Text(isLaki ? "Laki-laki" : "Perempuan", + style: GoogleFonts.poppins( + color: Colors.white, + fontWeight: FontWeight.w500, + fontSize: 12)), + ], + ), + ), + Padding( + padding: const EdgeInsets.fromLTRB(10, 25, 25, 20), + child: SizedBox( + width: double.infinity, + height: 250, + child: LineChart( + LineChartData( + lineTouchData: LineTouchData( + touchTooltipData: LineTouchTooltipData( + getTooltipColor: (touchedSpot) => + Colors.blueGrey.withOpacity(0.9), + getTooltipItems: (List touchedSpots) { + return touchedSpots.map((spot) { + if (spot.barIndex != 5) return null; + var detail = historyDetails.firstWhere( + (element) => + element["x"] == spot.x && + element["y"] == spot.y, + orElse: () => {"usia_lengkap": "?"}); + return LineTooltipItem( + "Data Balita\n", + GoogleFonts.poppins( + color: Colors.white, + fontSize: 11, + fontWeight: FontWeight.bold), + children: [ + TextSpan( + text: + "Tinggi: ${spot.y} cm\nUsia: ${detail["usia_lengkap"]}", + style: GoogleFonts.poppins( + color: Colors.white, + fontSize: 10, + fontWeight: FontWeight.normal)) + ], + ); + }).toList(); + }, + ), + ), + minX: 0, + maxX: 60, + minY: 45, + maxY: 125, + titlesData: FlTitlesData( + rightTitles: AxisTitles( + sideTitles: SideTitles( + showTitles: true, + reservedSize: 30, + getTitlesWidget: (val, _) => Text( + val.toInt().toString(), + style: GoogleFonts.poppins( + fontSize: 10, color: Colors.black54)))), + leftTitles: AxisTitles( + axisNameWidget: Text("TB (cm)", + style: GoogleFonts.poppins( + fontSize: 10, fontWeight: FontWeight.bold)), + sideTitles: SideTitles( + showTitles: true, + reservedSize: 30, + getTitlesWidget: (val, _) => Text( + val.toInt().toString(), + style: GoogleFonts.poppins( + fontSize: 10, color: Colors.black54)))), + topTitles: const AxisTitles( + sideTitles: SideTitles(showTitles: false)), + bottomTitles: AxisTitles( + axisNameWidget: Text("Usia (Bulan/Tahun)", + style: GoogleFonts.poppins( + fontSize: 10, fontWeight: FontWeight.bold)), + sideTitles: SideTitles( + showTitles: true, + interval: 12, + getTitlesWidget: (val, _) => Text( + val == 0 + ? "Lahir" + : "${(val / 12).toInt()} Thn", + style: GoogleFonts.poppins(fontSize: 9)))), + ), + gridData: const FlGridData( + show: true, + drawVerticalLine: true, + horizontalInterval: 10, + verticalInterval: 12), + borderData: FlBorderData( + show: true, + border: Border.all(color: Colors.black12)), + lineBarsData: [ + _sdLine(_getSDRefTBU(isLaki, 3), Colors.black), + _sdLine(_getSDRefTBU(isLaki, 2), Colors.red), + _sdLine(_getSDRefTBU(isLaki, 0), Colors.green), + _sdLine(_getSDRefTBU(isLaki, -2), Colors.red), + _sdLine(_getSDRefTBU(isLaki, -3), Colors.black), + LineChartBarData( + spots: filteredSpots, + isCurved: true, + color: accentColor, + barWidth: 4, + dotData: FlDotData( + show: true, + getDotPainter: (spot, p, bar, i) => + FlDotCirclePainter( + radius: 6, + color: Colors.white, + strokeWidth: 3, + strokeColor: accentColor))), + ], + ), + ), + ), + ), + ], + ), + ), + Align( + alignment: Alignment.centerLeft, + child: SizedBox( + width: MediaQuery.of(context).size.width * 0.75, + child: Card( + elevation: 4, + clipBehavior: Clip.antiAlias, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(15)), + margin: const EdgeInsets.only(bottom: 25), + color: statusColor, + child: Padding( + padding: const EdgeInsets.all(12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text("Keterangan Warna Status Gizi:", + style: GoogleFonts.poppins( + fontWeight: FontWeight.bold, + fontSize: 10, + color: Colors.white70)), + const SizedBox(height: 6), + Wrap( + spacing: 8, + runSpacing: 4, + children: [ + _statusLegend(Colors.green, "Normal"), + _statusLegend(Colors.red, "Pendek"), + _statusLegend(Colors.black, "S. Pendek"), + _statusLegend(Colors.purple, "Tinggi"), + ], + ), + const Divider(color: Colors.white24, height: 20), + RichText( + text: TextSpan( + style: GoogleFonts.poppins( + fontSize: 12, color: Colors.white), + children: [ + const TextSpan( + text: "Status Pertumbuhan: ", + style: TextStyle(fontWeight: FontWeight.normal)), + TextSpan( + text: "${analisis["status"]}", + style: + const TextStyle(fontWeight: FontWeight.bold)), + ], + ), + ), + const SizedBox(height: 4), + Text("Tinggi: $tb cm | Usia: $detailUsiaTerakhir", + style: GoogleFonts.poppins( + fontSize: 10, + fontWeight: FontWeight.w500, + color: Colors.white.withOpacity(0.9))), + ], + ), + ), + ), + ), + ), + ], + ); + } + + Widget _statusLegend(Color color, String text) { + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + width: 7, + height: 7, + decoration: BoxDecoration( + color: color, + shape: BoxShape.circle, + border: Border.all(color: Colors.white, width: 0.5))), + const SizedBox(width: 4), + Text(text, + style: GoogleFonts.poppins(fontSize: 8, color: Colors.white70)), + ], + ); + } + + LineChartBarData _sdLine(List spots, Color color) { + return LineChartBarData( + spots: spots, + color: color.withOpacity(0.35), + barWidth: 1.5, + dotData: const FlDotData(show: false), + isCurved: true); + } + + List _getSDRefTBU(bool isLaki, int type) { + if (isLaki) { + switch (type) { + case 3: + return const [ + FlSpot(0, 53.7), + FlSpot(6, 71.9), + FlSpot(12, 80.5), + FlSpot(24, 93.9), + FlSpot(36, 104.8), + FlSpot(48, 113.9), + FlSpot(60, 122.2) + ]; + case 2: + return const [ + FlSpot(0, 52.1), + FlSpot(6, 70.1), + FlSpot(12, 78.3), + FlSpot(24, 91.3), + FlSpot(36, 101.7), + FlSpot(48, 110.5), + FlSpot(60, 118.5) + ]; + case 0: + return const [ + FlSpot(0, 49.9), + FlSpot(6, 67.6), + FlSpot(12, 75.7), + FlSpot(24, 87.8), + FlSpot(36, 96.1), + FlSpot(48, 103.3), + FlSpot(60, 110.0) + ]; + case -2: + return const [ + FlSpot(0, 46.1), + FlSpot(6, 61.2), + FlSpot(12, 68.6), + FlSpot(24, 79.1), + FlSpot(36, 88.0), + FlSpot(48, 94.9), + FlSpot(60, 100.7) + ]; + case -3: + return const [ + FlSpot(0, 44.2), + FlSpot(6, 58.0), + FlSpot(12, 65.0), + FlSpot(24, 74.9), + FlSpot(36, 82.4), + FlSpot(48, 88.9), + FlSpot(60, 94.2) + ]; + } + } else { + switch (type) { + case 3: + return const [ + FlSpot(0, 52.9), + FlSpot(6, 70.3), + FlSpot(12, 79.2), + FlSpot(24, 92.9), + FlSpot(36, 103.9), + FlSpot(48, 113.3), + FlSpot(60, 122.0) + ]; + case 2: + return const [ + FlSpot(0, 51.3), + FlSpot(6, 68.5), + FlSpot(12, 77.0), + FlSpot(24, 90.1), + FlSpot(36, 100.8), + FlSpot(48, 109.8), + FlSpot(60, 118.1) + ]; + case 0: + return const [ + FlSpot(0, 49.1), + FlSpot(6, 65.7), + FlSpot(12, 74.0), + FlSpot(24, 86.4), + FlSpot(36, 95.1), + FlSpot(48, 102.7), + FlSpot(60, 109.4) + ]; + case -2: + return const [ + FlSpot(0, 45.4), + FlSpot(6, 60.1), + FlSpot(12, 67.9), + FlSpot(24, 79.0), + FlSpot(36, 88.1), + FlSpot(48, 95.2), + FlSpot(60, 100.7) + ]; + case -3: + return const [ + FlSpot(0, 43.6), + FlSpot(6, 57.3), + FlSpot(12, 64.9), + FlSpot(24, 75.2), + FlSpot(36, 83.8), + FlSpot(48, 90.3), + FlSpot(60, 95.6) + ]; + } + } + return []; + } +} diff --git a/lib/ibu/crud_grafik/grafik_balita_imt.dart b/lib/ibu/crud_grafik/grafik_balita_imt.dart new file mode 100644 index 0000000..92318b6 --- /dev/null +++ b/lib/ibu/crud_grafik/grafik_balita_imt.dart @@ -0,0 +1,516 @@ +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:fl_chart/fl_chart.dart'; +import 'package:http/http.dart' as http; +import 'package:shared_preferences/shared_preferences.dart'; + +// Sesuaikan path import ini dengan project Anda +import '../../layout/main_layout.dart'; +import '../ibu_drawer.dart'; +// Import Dashboard Ibu agar navigasi PopScope berfungsi +import '../dashboard_ibu.dart'; + +class GrafikAnakIMTPage extends StatefulWidget { + const GrafikAnakIMTPage({super.key}); + + @override + State createState() => _GrafikAnakIMTPageState(); +} + +class _GrafikAnakIMTPageState extends State { + List anakList = []; + bool isLoading = true; + + @override + void initState() { + super.initState(); + getData(); + } + + Future getData() async { + SharedPreferences prefs = await SharedPreferences.getInstance(); + String userId = prefs.getString("id_user") ?? ""; + + try { + var response = await http.post( + Uri.parse( + "http://ta.myhost.id/E31230549/mposyandu_api/grafik_balita/get_grafik_imt.php"), + body: {"user_id": userId}, + ); + + var jsonData = json.decode(response.body); + + if (jsonData["success"]) { + setState(() { + anakList = jsonData["data"]; + isLoading = false; + }); + } + } catch (e) { + if (mounted) setState(() => isLoading = false); + debugPrint("Error: $e"); + } + } + + int hitungUmurBulan(String tglLahir, String tglPeriksa) { + DateTime lahir = DateTime.parse(tglLahir); + DateTime periksa = DateTime.parse(tglPeriksa); + int months = (periksa.year - lahir.year) * 12 + periksa.month - lahir.month; + return months < 0 ? 0 : months; + } + + String formatUsiaDetail(String tglLahir, String tglPeriksa) { + DateTime birth = DateTime.parse(tglLahir); + DateTime now = DateTime.parse(tglPeriksa); + int years = now.year - birth.year; + int months = now.month - birth.month; + int days = now.day - birth.day; + if (days < 0) { + days += DateTime(now.year, now.month, 0).day; + months--; + } + if (months < 0) { + years--; + months += 12; + } + return "$years Thn $months Bln $days Hari"; + } + + @override + Widget build(BuildContext context) { + return PopScope( + canPop: false, + onPopInvokedWithResult: (didPop, result) async { + if (didPop) return; + + // ✅ FIX FINAL: selalu kembali ke Dashboard Ibu + Navigator.pushAndRemoveUntil( + context, + MaterialPageRoute( + builder: (_) => const DashboardIbuPage(), + ), + (route) => false, + ); + }, + child: MainLayout( + title: "", + drawer: const IbuDrawer(), + body: Padding( + padding: const EdgeInsets.all(10), + child: isLoading + ? const Center(child: CircularProgressIndicator()) + : anakList.isEmpty + ? const Center(child: Text("Tidak ada data IMT.")) + : ListView.builder( + itemCount: anakList.length, + itemBuilder: (context, index) { + var anak = anakList[index]; + List spots = []; + List> riwayatDetails = []; + + double lastIMT = 0; + double lastBB = 0; + double lastTB = 0; + int lastBulan = 0; + String lastTgl = ""; + + for (var p in anak["riwayat_imt"]) { + double imtVal = + double.tryParse(p["imt"].toString()) ?? 0.0; + if (imtVal > 0) { + int bulan = hitungUmurBulan(anak["tanggal_lahir"], + p["tanggal_pemeriksaan"]); + String usiaStr = formatUsiaDetail( + anak["tanggal_lahir"], + p["tanggal_pemeriksaan"]); + + spots.add(FlSpot(bulan.toDouble(), imtVal)); + riwayatDetails.add({ + "x": bulan.toDouble(), + "y": imtVal, + "bb": p["bb"], + "tb": p["tb"], + "usia_lengkap": usiaStr, + }); + lastIMT = imtVal; + lastBB = p["bb"]; + lastTB = p["tb"]; + lastBulan = bulan; + lastTgl = p["tanggal_pemeriksaan"]; + } + } + + return GrafikCardKIA_IMT( + nama: anak["nama"], + jk: anak["jenis_kelamin"], + umurBulan: lastBulan, + imt: lastIMT, + bb: lastBB, + tb: lastTB, + detailUsiaTerakhir: lastTgl.isNotEmpty + ? formatUsiaDetail(anak["tanggal_lahir"], lastTgl) + : "-", + historySpots: spots, + historyDetails: riwayatDetails, + ); + }, + ), + ), + ), + ); + } +} + +class GrafikCardKIA_IMT extends StatelessWidget { + final String nama, jk, detailUsiaTerakhir; + final int umurBulan; + final double imt, bb, tb; + final List historySpots; + final List> historyDetails; + + const GrafikCardKIA_IMT({ + super.key, + required this.nama, + required this.jk, + required this.umurBulan, + required this.imt, + required this.bb, + required this.tb, + required this.detailUsiaTerakhir, + required this.historySpots, + required this.historyDetails, + }); + + double getSDValueAtAge(List spots, int targetUmur) { + if (spots.isEmpty) return 0; + for (int i = 0; i < spots.length - 1; i++) { + if (targetUmur >= spots[i].x && targetUmur <= spots[i + 1].x) { + double ratio = + (targetUmur - spots[i].x) / (spots[i + 1].x - spots[i].x); + return spots[i].y + ratio * (spots[i + 1].y - spots[i].y); + } + } + return spots.last.y; + } + + Map analisisStatusIMT( + bool isLaki, int umur, double nilaiIMT) { + if (umur > 60 || nilaiIMT <= 0) + return {"status": "Data tidak valid", "warna": Colors.grey}; + + double sd3 = getSDValueAtAge(_getSDRefIMT_Gabungan(isLaki, 3), umur); + double sd2 = getSDValueAtAge(_getSDRefIMT_Gabungan(isLaki, 2), umur); + double sd1 = getSDValueAtAge(_getSDRefIMT_Gabungan(isLaki, 1), umur); + double sd0 = getSDValueAtAge(_getSDRefIMT_Gabungan(isLaki, 0), umur); + double sdM2 = getSDValueAtAge(_getSDRefIMT_Gabungan(isLaki, -2), umur); + double sdM3 = getSDValueAtAge(_getSDRefIMT_Gabungan(isLaki, -3), umur); + + if (nilaiIMT < sdM3) + return {"status": "Gizi Buruk (Sangat Kurus)", "warna": Colors.black}; + if (nilaiIMT < sdM2) + return {"status": "Gizi Kurang (Kurus)", "warna": Colors.red}; + if (nilaiIMT > sd3) return {"status": "Obesitas", "warna": Colors.purple}; + if (nilaiIMT > sd2) + return {"status": "Berat Badan Lebih", "warna": Colors.orange.shade900}; + if (nilaiIMT > sd1) + return {"status": "Risiko Berat Badan Lebih", "warna": Colors.orange}; + if (nilaiIMT >= sd0) + return {"status": "Normal (Di atas Median)", "warna": Colors.green}; + return { + "status": "Normal (Di bawah Median)", + "warna": Colors.green.shade700 + }; + } + + @override + Widget build(BuildContext context) { + final bool isLaki = jk == "L"; + final Color accentColor = + isLaki ? Colors.blue.shade700 : const Color(0xFFE91E63); + final analisis = analisisStatusIMT(isLaki, umurBulan, imt); + + return Card( + elevation: 4, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)), + margin: const EdgeInsets.only(bottom: 25), + child: Column( + children: [ + Container( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + decoration: BoxDecoration( + color: accentColor, + borderRadius: + const BorderRadius.vertical(top: Radius.circular(15))), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text(nama, + style: GoogleFonts.poppins( + color: Colors.white, + fontWeight: FontWeight.bold, + fontSize: 15)), + Text(isLaki ? "Laki-laki" : "Perempuan", + style: + GoogleFonts.poppins(color: Colors.white, fontSize: 11)), + ], + ), + ), + Padding( + padding: const EdgeInsets.fromLTRB(10, 25, 25, 10), + child: SizedBox( + width: double.infinity, + height: 250, + child: LineChart( + LineChartData( + lineTouchData: LineTouchData( + touchTooltipData: LineTouchTooltipData( + getTooltipColor: (touchedSpot) => + Colors.blueGrey.withOpacity(0.9), + getTooltipItems: (List touchedSpots) { + return touchedSpots.map((spot) { + var detail = historyDetails.firstWhere( + (e) => e["x"] == spot.x && e["y"] == spot.y, + orElse: () => {}); + return LineTooltipItem( + "IMT: ${spot.y.toStringAsFixed(1)}\nBB: ${detail["bb"]}kg, TB: ${detail["tb"]}cm\n${detail["usia_lengkap"]}", + GoogleFonts.poppins( + color: Colors.white, + fontSize: 9, + fontWeight: FontWeight.bold), + ); + }).toList(); + }, + ), + ), + minX: 0, + maxX: 60, + minY: 10, + maxY: 22, + titlesData: FlTitlesData( + rightTitles: AxisTitles( + sideTitles: SideTitles( + showTitles: true, + reservedSize: 30, + getTitlesWidget: (val, _) => Text( + val.toInt().toString(), + style: GoogleFonts.poppins( + fontSize: 9, color: Colors.black54)))), + leftTitles: AxisTitles( + axisNameWidget: Text("IMT", + style: GoogleFonts.poppins( + fontSize: 10, fontWeight: FontWeight.bold)), + sideTitles: SideTitles( + showTitles: true, + reservedSize: 30, + getTitlesWidget: (val, _) => Text( + val.toInt().toString(), + style: GoogleFonts.poppins( + fontSize: 9, color: Colors.black54)))), + topTitles: const AxisTitles( + sideTitles: SideTitles(showTitles: false)), + bottomTitles: AxisTitles( + sideTitles: SideTitles( + showTitles: true, + interval: 12, + getTitlesWidget: (val, _) { + if (val == 0) + return Text("Lahir", + style: GoogleFonts.poppins(fontSize: 9)); + return Text("${(val / 12).toInt()} Thn", + style: GoogleFonts.poppins(fontSize: 9)); + }), + ), + ), + gridData: FlGridData( + show: true, horizontalInterval: 1, verticalInterval: 6), + borderData: FlBorderData( + show: true, border: Border.all(color: Colors.black12)), + lineBarsData: [ + _sdLine(_getSDRefIMT_Gabungan(isLaki, 3), Colors.black), + _sdLine(_getSDRefIMT_Gabungan(isLaki, 2), Colors.red), + _sdLine(_getSDRefIMT_Gabungan(isLaki, 1), Colors.orange), + _sdLine(_getSDRefIMT_Gabungan(isLaki, 0), Colors.green), + _sdLine(_getSDRefIMT_Gabungan(isLaki, -2), Colors.red), + _sdLine(_getSDRefIMT_Gabungan(isLaki, -3), Colors.black), + LineChartBarData( + spots: historySpots, + isCurved: true, + color: accentColor, + barWidth: 3, + dotData: FlDotData( + show: true, + getDotPainter: (spot, p, bar, i) => + FlDotCirclePainter( + radius: 4, + color: Colors.white, + strokeWidth: 2, + strokeColor: accentColor)), + ), + ], + ), + ), + ), + ), + Padding( + padding: const EdgeInsets.all(16), + child: Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: Colors.grey.shade50, + borderRadius: BorderRadius.circular(10), + border: Border.all(color: Colors.grey.shade200)), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text("Keterangan Grafik:", + style: GoogleFonts.poppins( + fontWeight: FontWeight.bold, fontSize: 12)), + const SizedBox(height: 8), + _legendItem(Colors.green, "Hijau", "Median (Ideal)"), + _legendItem( + Colors.orange, "Orange", "Ambang Normal Atas (+1 SD)"), + _legendItem(Colors.red, "Merah", "Batas Kurus / Gemuk"), + _legendItem(Colors.black, "Hitam", "Kritis"), + const Divider(height: 20), + Row( + children: [ + Container( + width: 12, + height: 12, + decoration: BoxDecoration( + color: analisis["warna"], + shape: BoxShape.circle)), + const SizedBox(width: 8), + Expanded( + child: Text("Status: ${analisis["status"]}", + style: GoogleFonts.poppins( + fontSize: 11, + fontWeight: FontWeight.bold, + color: analisis["warna"]))), + ], + ), + const SizedBox(height: 5), + Text( + "Terakhir: ${imt.toStringAsFixed(1)} kg/m² | Usia: $detailUsiaTerakhir", + style: GoogleFonts.poppins( + fontSize: 11, + fontWeight: FontWeight.w600, + color: accentColor)), + ], + ), + ), + ) + ], + ), + ); + } + + Widget _legendItem(Color color, String label, String desc) { + return Padding( + padding: const EdgeInsets.only(bottom: 4), + child: Row(children: [ + Container(width: 10, height: 1.5, color: color), + const SizedBox(width: 8), + Text("$label: $desc", style: GoogleFonts.poppins(fontSize: 10)) + ])); + } + + LineChartBarData _sdLine(List spots, Color color) => LineChartBarData( + spots: spots, + color: color.withOpacity(0.4), + barWidth: 1.2, + dotData: const FlDotData(show: false), + isCurved: true); + + List _getSDRefIMT_Gabungan(bool isLaki, int type) { + if (isLaki) { + if (type == 3) + return const [ + FlSpot(0, 16.1), + FlSpot(6, 19.3), + FlSpot(12, 19.9), + FlSpot(60, 19.6) + ]; + if (type == 2) + return const [ + FlSpot(0, 15.3), + FlSpot(6, 18.2), + FlSpot(12, 18.9), + FlSpot(60, 18.8) + ]; + if (type == 1) + return const [ + FlSpot(0, 14.4), + FlSpot(6, 17.2), + FlSpot(12, 18.0), + FlSpot(60, 18.0) + ]; + if (type == 0) + return const [ + FlSpot(0, 13.4), + FlSpot(6, 16.3), + FlSpot(12, 17.1), + FlSpot(60, 17.0) + ]; + if (type == -2) + return const [ + FlSpot(0, 11.5), + FlSpot(6, 14.3), + FlSpot(12, 15.1), + FlSpot(60, 15.1) + ]; + if (type == -3) + return const [ + FlSpot(0, 10.7), + FlSpot(6, 13.2), + FlSpot(12, 14.1), + FlSpot(60, 14.1) + ]; + } else { + if (type == 3) + return const [ + FlSpot(0, 16.0), + FlSpot(6, 19.1), + FlSpot(12, 19.7), + FlSpot(60, 21.0) + ]; + if (type == 2) + return const [ + FlSpot(0, 15.1), + FlSpot(6, 17.9), + FlSpot(12, 18.6), + FlSpot(60, 19.9) + ]; + if (type == 1) + return const [ + FlSpot(0, 14.2), + FlSpot(6, 16.9), + FlSpot(12, 17.6), + FlSpot(60, 18.9) + ]; + if (type == 0) + return const [ + FlSpot(0, 13.2), + FlSpot(6, 15.8), + FlSpot(12, 16.5), + FlSpot(60, 17.8) + ]; + if (type == -2) + return const [ + FlSpot(0, 11.2), + FlSpot(6, 13.8), + FlSpot(12, 14.4), + FlSpot(60, 15.6) + ]; + if (type == -3) + return const [ + FlSpot(0, 10.4), + FlSpot(6, 12.8), + FlSpot(12, 13.3), + FlSpot(60, 14.6) + ]; + } + return []; + } +} diff --git a/lib/ibu/crud_pemeriksaaan_balita/riwayat_pemeriksaan_balita.dart b/lib/ibu/crud_pemeriksaaan_balita/riwayat_pemeriksaan_balita.dart new file mode 100644 index 0000000..4b87fa5 --- /dev/null +++ b/lib/ibu/crud_pemeriksaaan_balita/riwayat_pemeriksaan_balita.dart @@ -0,0 +1,260 @@ +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:http/http.dart' as http; + +class RiwayatPemeriksaanBalitaPage extends StatefulWidget { + final String idBalita; + final String namaBalita; + + const RiwayatPemeriksaanBalitaPage({ + super.key, + required this.idBalita, + required this.namaBalita, + }); + + @override + State createState() => + _RiwayatPemeriksaanBalitaPageState(); +} + +class _RiwayatPemeriksaanBalitaPageState + extends State { + List dataRiwayat = []; + List dataFilter = []; + bool isLoading = true; + + final TextEditingController searchController = TextEditingController(); + final baseUrl = + "http://ta.myhost.id/E31230549/mposyandu_api/pemeriksaan_balita_ibu"; + + @override + void initState() { + super.initState(); + getRiwayat(); + } + + Future getRiwayat() async { + setState(() => isLoading = true); + try { + final response = await http.post( + Uri.parse("$baseUrl/get_riwayat_pemeriksaan_balita.php"), + body: { + "id_balita": widget.idBalita, + }, + ); + + final data = json.decode(response.body); + + if (data["success"]) { + setState(() { + dataRiwayat = data["data"]; + dataFilter = data["data"]; + isLoading = false; + }); + } else { + setState(() => isLoading = false); + } + } catch (e) { + debugPrint(e.toString()); + setState(() => isLoading = false); + } + } + + void _filterData(String keyword) { + final key = keyword.toLowerCase(); + setState(() { + dataFilter = dataRiwayat.where((item) { + return item['tanggal_pemeriksaan'] + .toString() + .toLowerCase() + .contains(key) || + item['status_bbu'].toString().toLowerCase().contains(key) || + item['status_tbu'].toString().toLowerCase().contains(key) || + item['status_bbtb'].toString().toLowerCase().contains(key) || + item['imunisasi'].toString().toLowerCase().contains(key); + }).toList(); + }); + } + + String formatTanggal(String? tanggal) { + if (tanggal == null || tanggal.isEmpty) return "-"; + try { + DateTime dt = DateTime.parse(tanggal); + const bulan = [ + "", + "Januari", + "Februari", + "Maret", + "April", + "Mei", + "Juni", + "Juli", + "Agustus", + "September", + "Oktober", + "November", + "Desember" + ]; + return "${dt.day} ${bulan[dt.month]} ${dt.year}"; + } catch (e) { + return "-"; + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: const Color(0xFFFDFDFD), + appBar: AppBar( + backgroundColor: Colors.blueAccent, + iconTheme: const IconThemeData(color: Colors.white), + elevation: 0, + title: Text( + "", + style: GoogleFonts.poppins(color: Colors.white, fontSize: 16), + ), + ), + body: isLoading + ? const Center(child: CircularProgressIndicator()) + : Column( + children: [ + Padding( + padding: const EdgeInsets.only(top: 20, bottom: 12), + child: Center( + child: Text( + "Riwayat Pemeriksaan", + style: GoogleFonts.poppins( + fontSize: 18, + fontWeight: FontWeight.w600, + ), + ), + ), + ), + Padding( + padding: + const EdgeInsets.symmetric(horizontal: 20, vertical: 10), + child: TextField( + controller: searchController, + onChanged: _filterData, + style: GoogleFonts.poppins(fontSize: 12), + decoration: InputDecoration( + hintText: "Cari tanggal atau status gizi...", + prefixIcon: const Icon(Icons.search, + size: 20, color: Colors.grey), + contentPadding: const EdgeInsets.symmetric(vertical: 10), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + ), + ), + ), + ), + const SizedBox(height: 10), + Expanded( + child: dataFilter.isEmpty + ? Center( + child: Text( + "Data tidak ditemukan", + style: GoogleFonts.poppins( + fontSize: 12, color: Colors.grey), + ), + ) + : ListView.builder( + itemCount: dataFilter.length, + itemBuilder: (context, index) { + final balita = dataFilter[index]; + return _cardBalita(balita); + }, + ), + ), + ], + ), + ); + } + + Widget _cardBalita(Map balita) { + return Container( + margin: const EdgeInsets.symmetric(horizontal: 20, vertical: 8), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12), + border: Border.all(color: Colors.grey.shade200), + boxShadow: const [ + BoxShadow(color: Colors.black12, blurRadius: 5, offset: Offset(0, 2)), + ], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), + decoration: const BoxDecoration( + color: Colors.blueAccent, + borderRadius: BorderRadius.vertical(top: Radius.circular(12)), + ), + child: Text( + widget.namaBalita, + style: GoogleFonts.poppins( + color: Colors.white, + fontSize: 13, + fontWeight: FontWeight.w600, + ), + ), + ), + Padding( + padding: const EdgeInsets.all(12), + child: Column( + children: [ + _row("Tanggal Posyandu", + formatTanggal(balita["tanggal_pemeriksaan"])), + _row("Berat Badan", "${balita["bb"] ?? "-"} kg"), + _row("Tinggi Badan", "${balita["tb"] ?? "-"} cm"), + _row("Lingkar Kepala", "${balita["lk"] ?? "-"} cm"), + + // --- PERUBAHAN STATUS GIZI --- + _row("Status (BB/U)", balita["status_bbu"] ?? "-"), + _row("Status (TB/U)", balita["status_tbu"] ?? "-"), + _row("Status (BB/TB)", balita["status_bbtb"] ?? "-"), + // ----------------------------- + + _row("Imunisasi", balita["imunisasi"] ?? "-"), + _row("Vitamin A", balita["vitamin_a"] ?? "-"), + _row("PMT", balita["pmt"] ?? "-"), + _row("Catatan", balita["catatan"] ?? "-"), + ], + ), + ), + ], + ), + ); + } + + Widget _row(String label, String value) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 2), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: 130, // Sedikit diperkecil agar pas + child: Text( + label, + style: GoogleFonts.poppins( + fontSize: 11, fontWeight: FontWeight.w600), + ), + ), + Text(" : ", + style: GoogleFonts.poppins( + fontSize: 11, fontWeight: FontWeight.bold)), + Expanded( + child: Text( + value, + style: GoogleFonts.poppins(fontSize: 11), + ), + ), + ], + ), + ); + } +} diff --git a/lib/ibu/crud_pemeriksaan_anc/riwayat_pemeriksaan_anc.dart b/lib/ibu/crud_pemeriksaan_anc/riwayat_pemeriksaan_anc.dart new file mode 100644 index 0000000..fa7efb5 --- /dev/null +++ b/lib/ibu/crud_pemeriksaan_anc/riwayat_pemeriksaan_anc.dart @@ -0,0 +1,358 @@ +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:http/http.dart' as http; + +class RiwayatPemeriksaanAncPage extends StatefulWidget { + final String ibuHamilId; + final String nama; + + const RiwayatPemeriksaanAncPage({ + super.key, + required this.ibuHamilId, + required this.nama, + }); + + @override + State createState() => + _RiwayatPemeriksaanAncPageState(); +} + +class _RiwayatPemeriksaanAncPageState extends State { + List> _data = []; + List> _dataFilter = []; + + bool _loading = true; + + final TextEditingController searchController = TextEditingController(); + + int _currentPage = 0; + final int _rowsPerPage = 5; + + @override + void initState() { + super.initState(); + fetchRiwayat(); + } + + String _formatTanggalIndo(String? tanggal) { + if (tanggal == null || tanggal.isEmpty) return "-"; + + try { + DateTime dt = DateTime.parse(tanggal); + + List bulanIndo = [ + "", + "Januari", + "Februari", + "Maret", + "April", + "Mei", + "Juni", + "Juli", + "Agustus", + "September", + "Oktober", + "November", + "Desember" + ]; + + return "${dt.day.toString().padLeft(2, '0')} " + "${bulanIndo[dt.month]} ${dt.year}"; + } catch (e) { + return tanggal; + } + } + + Future fetchRiwayat() async { + setState(() => _loading = true); + + debugPrint("IBU HAMIL ID = ${widget.ibuHamilId}"); + + final url = Uri.parse( + "http://ta.myhost.id/E31230549/mposyandu_api/pemeriksaan_anc/get_riwayat_pemeriksaan_anc.php?ibu_hamil_id=${widget.ibuHamilId}"); + + debugPrint("URL = $url"); + + try { + final response = await http.get(url); + + if (response.statusCode == 200) { + final jsonData = json.decode(response.body); + + if (jsonData["success"] == true) { + List> data = + List>.from(jsonData["data"]); + + data.sort((a, b) { + DateTime dateA = + DateTime.tryParse(a['tanggal_pemeriksaan'] ?? '') ?? + DateTime(1900); + + DateTime dateB = + DateTime.tryParse(b['tanggal_pemeriksaan'] ?? '') ?? + DateTime(1900); + + return dateB.compareTo(dateA); + }); + + setState(() { + _data = data; + _dataFilter = data; + }); + } + } + } catch (e) { + debugPrint(e.toString()); + } + + setState(() => _loading = false); + } + + void _filterData(String keyword) { + final key = keyword.toLowerCase(); + + setState(() { + _dataFilter = _data.where((item) { + return item['tanggal_pemeriksaan'] + .toString() + .toLowerCase() + .contains(key) || + item['keluhan'].toString().toLowerCase().contains(key) || + item['tindakan'].toString().toLowerCase().contains(key); + }).toList(); + + _currentPage = 0; + }); + } + + List> get _paginatedData { + if (_dataFilter.isEmpty) return []; + + final start = _currentPage * _rowsPerPage; + final end = start + _rowsPerPage; + + if (start >= _dataFilter.length) return []; + + return _dataFilter.sublist( + start, end > _dataFilter.length ? _dataFilter.length : end); + } + + @override + Widget build(BuildContext context) { + final totalPages = + _dataFilter.isEmpty ? 1 : (_dataFilter.length / _rowsPerPage).ceil(); + + return Scaffold( + backgroundColor: const Color(0xFFFDFDFD), + appBar: AppBar( + backgroundColor: Colors.blue, + elevation: 0, + leading: IconButton( + icon: const Icon(Icons.arrow_back, color: Colors.white), + onPressed: () => Navigator.pop(context), + ), + ), + body: _loading + ? const Center(child: CircularProgressIndicator()) + : Column( + children: [ + /// TITLE + Padding( + padding: const EdgeInsets.only(top: 20, bottom: 12), + child: Center( + child: Text( + "Riwayat Pemeriksaan ANC", + style: GoogleFonts.poppins( + fontSize: 18, + fontWeight: FontWeight.bold, + ), + ), + ), + ), + + /// SEARCH + Padding( + padding: const EdgeInsets.symmetric(horizontal: 20), + child: TextField( + controller: searchController, + onChanged: _filterData, + style: GoogleFonts.poppins(fontSize: 12), + decoration: InputDecoration( + hintText: "Cari berdasarkan tanggal, keluhan...", + prefixIcon: const Icon( + Icons.search, + size: 20, + color: Colors.grey, + ), + contentPadding: const EdgeInsets.symmetric( + vertical: 10, + ), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + ), + ), + ), + ), + + const SizedBox(height: 15), + + /// LIST DATA + Expanded( + child: _dataFilter.isEmpty + ? Center( + child: Text( + "Tidak ada riwayat pemeriksaan ANC", + style: GoogleFonts.poppins( + fontSize: 12, + color: Colors.grey, + ), + )) + : ListView.builder( + itemCount: _paginatedData.length, + itemBuilder: (context, index) { + final data = _paginatedData[index]; + + return _buildCard(data); + }, + ), + ), + + /// PAGINATION + Container( + padding: + const EdgeInsets.symmetric(horizontal: 20, vertical: 8), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + "Halaman ${_currentPage + 1} dari $totalPages", + style: GoogleFonts.poppins( + fontSize: 12, + ), + ), + Row( + children: [ + IconButton( + iconSize: 20, + icon: const Icon(Icons.chevron_left), + onPressed: _currentPage == 0 + ? null + : () { + setState(() { + _currentPage--; + }); + }, + ), + IconButton( + iconSize: 20, + icon: const Icon(Icons.chevron_right), + onPressed: _currentPage >= totalPages - 1 + ? null + : () { + setState(() { + _currentPage++; + }); + }, + ), + ], + ) + ], + ), + ) + ], + ), + ); + } + + Widget _buildCard(Map data) { + return Center( + child: Container( + margin: const EdgeInsets.symmetric(horizontal: 25, vertical: 8), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(14), + border: Border.all(color: Colors.grey.shade300), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.03), + blurRadius: 5, + offset: const Offset(0, 2), + ), + ], + ), + child: Column( + children: [ + /// HEADER CARD + Container( + width: double.infinity, + padding: const EdgeInsets.all(12), + decoration: const BoxDecoration( + color: Colors.blue, + borderRadius: BorderRadius.vertical( + top: Radius.circular(14), + ), + ), + child: Text( + widget.nama, + style: GoogleFonts.poppins( + color: Colors.white, + fontWeight: FontWeight.bold, + fontSize: 12, + ), + ), + ), + + /// BODY + Padding( + padding: const EdgeInsets.all(12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _row("Tanggal", + _formatTanggalIndo(data["tanggal_pemeriksaan"])), + _row("Berat Badan", "${data["berat_badan"]} kg"), + _row("Tekanan Darah", data["tekanan_darah"]), + _row("Tinggi Fundus", "${data["tinggi_fundus"]} cm"), + _row("DJJ", data["denyut_jantung_janin"]), + _row("HB", data["hb"]), + _row("Kaki Bengkak", data["kaki_bengkak"]), + _row("Keluhan", data["keluhan"]), + _row("Tindakan", data["tindakan"]), + ], + ), + ) + ], + ), + ), + ); + } + + Widget _row(String label, dynamic value) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 3), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: 100, + child: Text( + label, + style: GoogleFonts.poppins( + fontSize: 12, + fontWeight: FontWeight.w600, + ), + ), + ), + Text(" : ", style: GoogleFonts.poppins(fontSize: 12)), + Expanded( + child: Text( + "${value ?? '-'}", + style: GoogleFonts.poppins(fontSize: 12), + ), + ) + ], + ), + ); + } +} diff --git a/lib/ibu/dashboard_ibu.dart b/lib/ibu/dashboard_ibu.dart new file mode 100644 index 0000000..724a17d --- /dev/null +++ b/lib/ibu/dashboard_ibu.dart @@ -0,0 +1,808 @@ +import 'dart:convert'; +import 'dart:async'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:http/http.dart' as http; +import 'package:audioplayers/audioplayers.dart'; + +import '../layout/main_layout.dart'; +import 'ibu_drawer.dart'; + +class DashboardIbuPage extends StatefulWidget { + const DashboardIbuPage({super.key}); + + @override + State createState() => _DashboardIbuPageState(); +} + +class _DashboardIbuPageState extends State { + DateTime _selectedDate = DateTime.now(); + static const String baseUrl = "http://ta.myhost.id/E31230549/mposyandu_api"; + + Timer? _pollingTimer; + final AudioPlayer _audioPlayer = AudioPlayer(); + int _notificationCount = 0; + List _knownJadwalIds = []; + + Map? dataKehamilan; + List dataBalita = []; + List dataJadwal = []; + List dataJadwalAnc = []; + String namaUser = "Ibu"; + bool isLoading = true; + bool _isPasswordVisible = false; + + @override + void initState() { + super.initState(); + _audioPlayer.setReleaseMode(ReleaseMode.stop); + _initDashboard(); + _pollingTimer = Timer.periodic(const Duration(seconds: 15), (timer) { + getDashboardData(isPolling: true); + }); + } + + @override + void dispose() { + _pollingTimer?.cancel(); + _audioPlayer.dispose(); + super.dispose(); + } + + Future _initDashboard() async { + final prefs = await SharedPreferences.getInstance(); + String? idUser = prefs.getString("id_user"); + + setState(() { + namaUser = prefs.getString("nama") ?? "Ibu"; + _notificationCount = prefs.getInt('notif_count_$idUser') ?? 0; + _knownJadwalIds = prefs.getStringList('known_ids_$idUser') ?? []; + }); + + await _checkLoginStatus(); + _checkPasswordStatus(); + await getDashboardData(isPolling: false); + } + + // ================= LOGIKA CEK & UPDATE PASSWORD DEFAULT (NIK) ================= + + Future _checkPasswordStatus() async { + final prefs = await SharedPreferences.getInstance(); + String? id = prefs.getString("id_user"); + + if (id == null) return; + + bool isChanged = prefs.getBool("is_password_changed_$id") ?? false; + if (isChanged) return; + + try { + final res = await http.post( + Uri.parse("$baseUrl/cek_password_default_ibu.php"), + body: {"id": id}).timeout(const Duration(seconds: 10)); + + if (res.statusCode == 200) { + final data = json.decode(res.body); + if (data["success"] == true && data["password_default"] == true) { + WidgetsBinding.instance.addPostFrameCallback((_) { + _showChangePasswordDialog(); + }); + } else if (data["success"] == true) { + await prefs.setBool("is_password_changed_$id", true); + } + } + } catch (e) { + debugPrint("Gagal cek password default: $e"); + } + } + + void _showChangePasswordDialog() { + final TextEditingController passwordController = TextEditingController(); + String? localError; + + showDialog( + context: context, + barrierDismissible: false, + builder: (context) => StatefulBuilder( + builder: (context, setDialogState) { + return AlertDialog( + shape: + RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)), + title: Text("Keamanan Akun", + style: GoogleFonts.poppins(fontWeight: FontWeight.bold)), + content: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + "Akun Anda terdeteksi masih menggunakan password bawaan. Silakan ubah password (6 digit, berisi huruf & angka) demi keamanan data.", + style: GoogleFonts.poppins(fontSize: 13), + ), + const SizedBox(height: 20), + TextField( + controller: passwordController, + obscureText: !_isPasswordVisible, + maxLength: 6, + keyboardType: TextInputType.visiblePassword, + decoration: InputDecoration( + labelText: "Password Baru", + hintText: "Contoh: abc123", + errorText: localError, + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(12)), + suffixIcon: IconButton( + icon: Icon(_isPasswordVisible + ? Icons.visibility + : Icons.visibility_off), + onPressed: () => setDialogState( + () => _isPasswordVisible = !_isPasswordVisible), + ), + ), + ), + ], + ), + actions: [ + SizedBox( + width: double.infinity, + child: ElevatedButton( + style: ElevatedButton.styleFrom( + backgroundColor: Colors.blue, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10)), + ), + onPressed: () async { + String val = passwordController.text.trim(); + + bool hasLetter = val.contains(RegExp(r'[a-zA-Z]')); + bool hasNumber = val.contains(RegExp(r'[0-9]')); + + if (val.isEmpty) { + setDialogState(() => localError = "Wajib diisi"); + } else if (val.length != 6) { + setDialogState( + () => localError = "Harus tepat 6 karakter"); + } else if (!hasLetter || !hasNumber) { + setDialogState( + () => localError = "Harus kombinasi huruf & angka"); + } else { + setDialogState(() => localError = null); + await _updatePassword(val); + } + }, + child: Text("Simpan Password", + style: GoogleFonts.poppins( + color: Colors.white, fontWeight: FontWeight.bold)), + ), + ), + ], + ); + }, + ), + ); + } + + Future _updatePassword(String p) async { + final prefs = await SharedPreferences.getInstance(); + String? id = prefs.getString("id_user"); + if (id == null) return; + try { + final res = await http.post(Uri.parse("$baseUrl/update_password_ibu.php"), + body: {"id": id, "password": p}); + final data = json.decode(res.body); + + if (data["success"]) { + await prefs.setBool("is_password_changed_$id", true); + if (mounted) { + Navigator.pop(context); + ScaffoldMessenger.of(context).showSnackBar(const SnackBar( + content: Text("Password berhasil diperbarui"), + backgroundColor: Colors.green)); + } + } + } catch (e) { + debugPrint("Update error: $e"); + } + } + + // ================= LOGIKA DATA & NOTIFIKASI ================= + + Future getDashboardData({required bool isPolling}) async { + final prefs = await SharedPreferences.getInstance(); + String? idUser = prefs.getString("id_user"); + if (idUser == null) return; + + try { + final response = await http.post(Uri.parse("$baseUrl/dashboard_ibu.php"), + body: {"user_id": idUser}); + final data = json.decode(response.body); + + if (data["success"]) { + List currentPosyandu = data["jadwal"] ?? []; + List currentAnc = data["jadwal_anc"] ?? []; + List allIncoming = [...currentPosyandu, ...currentAnc]; + + bool hasNewJadwal = false; + int newItemsCount = 0; + + for (var item in allIncoming) { + String uniqueId = "${item['id']}_${item['tanggal']}"; + if (!_knownJadwalIds.contains(uniqueId)) { + _knownJadwalIds.add(uniqueId); + newItemsCount++; + hasNewJadwal = true; + } + } + + if (hasNewJadwal) { + await prefs.setStringList('known_ids_$idUser', _knownJadwalIds); + if (isPolling) { + _playNotifSound(); + setState(() { + _notificationCount += newItemsCount; + }); + await prefs.setInt('notif_count_$idUser', _notificationCount); + } + } + + if (mounted) { + setState(() { + dataKehamilan = data["kehamilan"]; + dataBalita = data["balita"] ?? []; + dataJadwal = currentPosyandu; + dataJadwalAnc = currentAnc; + isLoading = false; + }); + } + } + } catch (e) { + if (mounted) setState(() => isLoading = false); + } + } + + Future _playNotifSound() async { + try { + await _audioPlayer.stop(); + await _audioPlayer.play(AssetSource('sounds/notif.mp3')); + } catch (e) { + debugPrint("Audio Error: $e"); + } + } + + Map _getJadwalStatus(Map item, bool isAnc) { + try { + DateTime sekarang = DateTime.now(); + String tglStr = item["tanggal"] ?? ""; + String jamMulaiStr = item["jam_mulai"]?.toString() ?? "08:00:00"; + if (jamMulaiStr.length == 5) jamMulaiStr = "$jamMulaiStr:00"; + + DateTime mulai = DateTime.parse("${tglStr.trim()} ${jamMulaiStr.trim()}"); + DateTime selesai; + + if (isAnc) { + selesai = mulai.add(const Duration(hours: 4)); + } else { + String jamSelesaiStr = item["jam_selesai"]?.toString() ?? ""; + if (jamSelesaiStr == "-" || jamSelesaiStr.isEmpty) { + selesai = mulai.add(const Duration(hours: 4)); + } else { + if (jamSelesaiStr.length == 5) jamSelesaiStr = "$jamSelesaiStr:00"; + selesai = DateTime.parse("${tglStr.trim()} ${jamSelesaiStr.trim()}"); + } + } + + if (sekarang.isAfter(selesai)) { + return {"label": "Selesai", "color": Colors.white.withOpacity(0.4)}; + } else if (sekarang.isAfter(mulai) && sekarang.isBefore(selesai)) { + return {"label": "Berlangsung", "color": Colors.greenAccent}; + } else { + return {"label": "Mendatang", "color": Colors.white.withOpacity(0.2)}; + } + } catch (e) { + return {"label": "-", "color": Colors.transparent}; + } + } + + @override + Widget build(BuildContext context) { + final selectedKey = + "${_selectedDate.year}-${_selectedDate.month.toString().padLeft(2, '0')}-${_selectedDate.day.toString().padLeft(2, '0')}"; + final posyanduAtDate = + dataJadwal.where((j) => j["tanggal"] == selectedKey).toList(); + final ancAtDate = + dataJadwalAnc.where((j) => j["tanggal"] == selectedKey).toList(); + + if (isLoading) { + return const Scaffold(body: Center(child: CircularProgressIndicator())); + } + + return PopScope( + canPop: false, + onPopInvokedWithResult: (didPop, result) async { + if (didPop) return; + await SystemNavigator.pop(); + }, + child: Theme( + data: Theme.of(context).copyWith( + textTheme: + GoogleFonts.poppinsTextTheme(Theme.of(context).textTheme)), + child: Stack( + children: [ + MainLayout( + title: "", + drawer: const IbuDrawer(), + body: RefreshIndicator( + onRefresh: () => getDashboardData(isPolling: false), + child: SingleChildScrollView( + physics: const AlwaysScrollableScrollPhysics(), + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildHeader(), + const SizedBox(height: 20), + _buildHeroImage(), + const SizedBox(height: 30), + if (dataKehamilan != null) ...[ + _buildKehamilanCard(), + const SizedBox(height: 15) + ], + if (dataBalita.isNotEmpty) ...[ + _buildBalitaCard(), + const SizedBox(height: 30) + ], + _buildCalendarSection(posyanduAtDate, ancAtDate), + const SizedBox(height: 20), + ], + ), + ), + ), + ), + _buildNotificationIcon(), + ], + ), + ), + ); + } + + Widget _buildNotificationIcon() { + return Positioned( + top: MediaQuery.of(context).padding.top + 5, + right: 12, + child: Stack( + alignment: Alignment.center, + children: [ + IconButton( + icon: const Icon(Icons.notifications, + color: Colors.white, size: 28), + onPressed: _showNotifDialog), + if (_notificationCount > 0) + Positioned( + right: 8, + top: 8, + child: Container( + padding: const EdgeInsets.all(2), + decoration: BoxDecoration( + color: Colors.red, + shape: BoxShape.circle, + border: Border.all(color: Colors.white, width: 1.5)), + constraints: const BoxConstraints(minWidth: 18, minHeight: 18), + child: Center( + child: Text( + _notificationCount > 9 ? "9+" : "$_notificationCount", + style: const TextStyle( + color: Colors.white, + fontSize: 9, + fontWeight: FontWeight.bold))), + ), + ) + ], + ), + ); + } + + void _showNotifDialog() async { + final prefs = await SharedPreferences.getInstance(); + String? idUser = prefs.getString("id_user"); + setState(() { + _notificationCount = 0; + }); + await prefs.setInt('notif_count_$idUser', 0); + + showDialog( + context: context, + builder: (_) => AlertDialog( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)), + title: Text("Pemberitahuan Jadwal", + textAlign: TextAlign.center, + style: + GoogleFonts.poppins(fontWeight: FontWeight.bold, fontSize: 16)), + content: Container( + width: 300, + constraints: const BoxConstraints(maxHeight: 450), + child: dataJadwal.isEmpty && dataJadwalAnc.isEmpty + ? Text("Tidak ada riwayat jadwal.", + textAlign: TextAlign.center, + style: GoogleFonts.poppins(fontSize: 13)) + : SingleChildScrollView( + child: Column(mainAxisSize: MainAxisSize.min, children: [ + ...dataJadwal + .map((j) => _buildMiniSchedule(j, Colors.blue, false)), + ...dataJadwalAnc + .map((j) => _buildMiniSchedule(j, Colors.pink, true)), + ]), + ), + ), + actions: [ + Center( + child: TextButton( + onPressed: () => Navigator.pop(context), + child: const Text("Tutup"))) + ], + ), + ); + } + + Widget _buildMiniSchedule(Map item, Color color, bool isAnc) { + var status = _getJadwalStatus(item, isAnc); + return Container( + width: double.infinity, + margin: const EdgeInsets.only(bottom: 12), + padding: const EdgeInsets.all(14), + decoration: BoxDecoration( + color: color, + borderRadius: BorderRadius.circular(12), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.1), + blurRadius: 4, + offset: const Offset(0, 2)) + ]), + child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Row(children: [ + const Icon(Icons.event_available, size: 18, color: Colors.white), + const SizedBox(width: 8), + Expanded( + child: Text(item["keterangan"] ?? "Kegiatan", + style: GoogleFonts.poppins( + fontWeight: FontWeight.bold, + fontSize: 14, + color: Colors.white))), + Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2), + decoration: BoxDecoration( + color: status["color"], + borderRadius: BorderRadius.circular(6)), + child: Text(status["label"], + style: const TextStyle( + fontSize: 10, + color: Colors.white, + fontWeight: FontWeight.bold))) + ]), + Divider(height: 20, color: Colors.white.withOpacity(0.3), thickness: 1), + Row(children: [ + const Icon(Icons.calendar_month, size: 14, color: Colors.white), + const SizedBox(width: 8), + Text(_formatDateToIndo(item["tanggal"]), + style: const TextStyle( + fontSize: 12, + color: Colors.white, + fontWeight: FontWeight.w500)) + ]), + const SizedBox(height: 6), + Row(children: [ + const Icon(Icons.location_on, size: 14, color: Colors.white), + const SizedBox(width: 8), + Expanded( + child: Text(item["lokasi"] ?? "-", + style: const TextStyle(fontSize: 12, color: Colors.white))) + ]), + ]), + ); + } + + Widget _buildHeader() => RichText( + text: TextSpan(children: [ + TextSpan( + text: 'Selamat Datang Ibu $namaUser\n', + style: GoogleFonts.poppins( + fontSize: 18, fontWeight: FontWeight.bold, color: Colors.blue)), + TextSpan( + text: 'Pantau kesehatan ibu dan buah hati tercinta ', + style: GoogleFonts.poppins(fontSize: 13, color: Colors.black87)), + const WidgetSpan( + child: Icon(Icons.favorite, color: Colors.blue, size: 18)), + ])); + + Widget _buildHeroImage() => Center( + child: Image.asset('assets/images/logoo.webp', + width: 300, + height: 180, + errorBuilder: (_, __, ___) => + const Icon(Icons.image, size: 100, color: Colors.grey))); + + // ================= UPDATE CARD INFORMASI KEHAMILAN ================= + Widget _buildKehamilanCard() => + _infoBox(color: Colors.lightGreen, title: "Informasi Kehamilan", items: [ + _infoItem(Icons.info_outline, "Status Kehamilan", + _capitalize(dataKehamilan?["status"])), + _infoItem(Icons.calendar_today, "HPHT", + _formatDateToIndo(dataKehamilan?["hpht"])), + _infoItem(Icons.pregnant_woman, "Usia Kandungan", + "${dataKehamilan!["hpht"] != "0000-00-00" && dataKehamilan?["status"] == "aktif" ? (DateTime.now().difference(DateTime.parse(dataKehamilan!["hpht"])).inDays ~/ 7) : 0} Minggu"), + _infoItem(Icons.event, "HPL", _formatDateToIndo(dataKehamilan?["hpl"])), + _infoItem(Icons.history, "Tgl Persalinan Sblm", + _formatDateToIndo(dataKehamilan?["tanggal_persalinan_sebelumnya"])), + _infoItem(Icons.looks_one, "Gravida", + dataKehamilan?["gravida"].toString() ?? "-"), + _infoItem( + Icons.looks_two, "Para", dataKehamilan?["para"].toString() ?? "-"), + _infoItem(Icons.looks_3, "Abortus", + dataKehamilan?["abortus"].toString() ?? "-"), + _infoItem(Icons.favorite_border, "Hidup", + dataKehamilan?["hidup"].toString() ?? "-"), + _infoItem( + Icons.payment, "Pembiayaan", dataKehamilan?["pembiayaan"] ?? "-"), + ]); + + // ================= UPDATE CARD INFORMASI ANAK ================= + Widget _buildBalitaCard() { + bool isFirstChildFemale = dataBalita.isNotEmpty && + dataBalita[0]["jenis_kelamin"]?.toString().toUpperCase() == "P"; + + return Container( + width: double.infinity, + decoration: BoxDecoration( + color: isFirstChildFemale ? Colors.pink : Colors.blue, + borderRadius: BorderRadius.circular(16), + boxShadow: const [ + BoxShadow( + blurRadius: 8, color: Colors.black12, offset: Offset(0, 4)) + ]), + child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Padding( + padding: const EdgeInsets.all(16), + child: Text("Informasi Anak", + style: GoogleFonts.poppins( + color: Colors.white, + fontWeight: FontWeight.bold, + fontSize: 16))), + ...dataBalita.asMap().entries.map((entry) { + var anak = entry.value; + bool isP = anak["jenis_kelamin"]?.toString().toUpperCase() == "P"; + + String tempatLahir = anak["tempat_lahir"] ?? "-"; + String tanggalLahirIndo = _formatDateToIndo(anak["tanggal_lahir"]); + String tempatTanggalLahir = "$tempatLahir, $tanggalLahirIndo"; + + return Container( + width: double.infinity, + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: isP ? Colors.pink : Colors.blue, + borderRadius: entry.key == dataBalita.length - 1 + ? const BorderRadius.vertical( + bottom: Radius.circular(16)) + : null), + child: Column(children: [ + _infoItemCustom(Icons.info_outline, "Status Balita", + _capitalize(anak["status"]), Colors.white), + _infoItemCustom(Icons.child_care, "Nama Balita", + anak["nama"] ?? "-", Colors.white), + _infoItemCustom(Icons.person, "Jenis Kelamin", + formatJenisKelamin(anak["jenis_kelamin"]), Colors.white), + _infoItemCustom(Icons.location_city, "Tempat Tanggal Lahir", + tempatTanggalLahir, Colors.white), + _infoItemCustom(Icons.cake, "Usia", + hitungUsiaBalita(anak["tanggal_lahir"]), Colors.white), + _infoItemCustom(Icons.format_list_numbered, "Anak Ke", + anak["anak_ke"]?.toString() ?? "-", Colors.white), + if (entry.key < dataBalita.length - 1) + const Divider(color: Colors.white30, height: 20) + ])); + }).toList(), + ])); + } + + Widget _buildCalendarSection(List s, List a) => Column(children: [ + Center( + child: Text("Jadwal Kegiatan", + style: GoogleFonts.poppins( + fontWeight: FontWeight.bold, fontSize: 16))), + const SizedBox(height: 20), + if (s.isEmpty && a.isEmpty) + _emptySchedule() + else + Column(children: [ + ...s.map((i) => _scheduleDetail(i, Colors.blue)), + ...a.map((i) => _scheduleDetail(i, Colors.pink)) + ]), + const SizedBox(height: 20), + _buildCalendarPicker(), + ]); + + Widget _buildCalendarPicker() => Center( + child: Container( + padding: const EdgeInsets.all(8), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + boxShadow: [ + BoxShadow(color: Colors.black.withOpacity(0.05), blurRadius: 10) + ]), + child: SizedBox( + width: 300, + height: 280, + child: CalendarDatePicker( + initialDate: _selectedDate, + firstDate: DateTime(2020), + lastDate: DateTime(2030), + onDateChanged: (d) => setState(() => _selectedDate = d))))); + + Widget _scheduleDetail(Map item, Color color) { + String jamSelesai = item["jam_selesai"]?.toString() ?? "-"; + String displayJam = (jamSelesai == "-" || jamSelesai.isEmpty) + ? "${item["jam_mulai"] ?? "00:00"} - Selesai" + : "${item["jam_mulai"] ?? "00:00"} - $jamSelesai"; + return Padding( + padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 8), + child: Column(children: [ + Row(mainAxisAlignment: MainAxisAlignment.center, children: [ + Icon(Icons.stars, color: color, size: 20), + const SizedBox(width: 8), + Flexible( + child: Text(item["keterangan"] ?? "Kegiatan", + textAlign: TextAlign.center, + style: GoogleFonts.poppins( + fontSize: 14, + fontWeight: FontWeight.bold, + color: color))) + ]), + const SizedBox(height: 8), + Row(mainAxisAlignment: MainAxisAlignment.center, children: [ + const Icon(Icons.access_time, size: 14, color: Colors.grey), + const SizedBox(width: 6), + Text(displayJam, style: GoogleFonts.poppins(fontSize: 12)) + ]), + const SizedBox(height: 4), + Row(mainAxisAlignment: MainAxisAlignment.center, children: [ + const Icon(Icons.location_on_outlined, + size: 14, color: Colors.grey), + const SizedBox(width: 6), + Flexible( + child: Text("Lokasi: ${item["lokasi"] ?? "-"}", + textAlign: TextAlign.center, + style: GoogleFonts.poppins(fontSize: 12))) + ]), + Divider(thickness: 1, color: color.withOpacity(0.2)), + ])); + } + + String _formatDateToIndo(String? dateString) { + if (dateString == null || dateString.isEmpty || dateString == "0000-00-00") + return "-"; + try { + DateTime date = DateTime.parse(dateString); + const bulan = [ + "", + "Januari", + "Februari", + "Maret", + "April", + "Mei", + "Juni", + "Juli", + "Agustus", + "September", + "Oktober", + "November", + "Desember" + ]; + return "${date.day} ${bulan[date.month]} ${date.year}"; + } catch (e) { + return "-"; + } + } + + String hitungUsiaBalita(String? tanggalLahir) { + if (tanggalLahir == null || tanggalLahir.isEmpty) return "-"; + try { + DateTime lahir = DateTime.parse(tanggalLahir); + DateTime sekarang = DateTime.now(); + + int tahun = sekarang.year - lahir.year; + int selisihBulan = ClinicalMonthDiff(sekarang, lahir); + + if (sekarang.day < lahir.day) selisihBulan--; + + if (selisihBulan < 0) { + tahun--; + selisihBulan += 12; + } + return "$tahun Thn $selisihBulan Bln"; + } catch (e) { + return "-"; + } + } + + int ClinicalMonthDiff(DateTime a, DateTime b) { + return a.month - b.month; + } + + String formatJenisKelamin(String? jk) { + if (jk == null) return "-"; + return (jk.toUpperCase() == "L") + ? "Laki-laki" + : (jk.toUpperCase() == "P" ? "Perempuan" : jk); + } + + String _capitalize(String? text) { + if (text == null || text.isEmpty) return "-"; + return text[0].toUpperCase() + text.substring(1).toLowerCase(); + } + + Widget _infoBox( + {required Color color, + required String title, + required List items}) => + Container( + width: double.infinity, + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: color, + borderRadius: BorderRadius.circular(16), + boxShadow: const [ + BoxShadow( + blurRadius: 8, color: Colors.black12, offset: Offset(0, 4)) + ]), + child: + Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text(title, + style: GoogleFonts.poppins( + color: Colors.white, + fontWeight: FontWeight.bold, + fontSize: 16)), + const SizedBox(height: 12), + ...items + ])); + + Widget _infoItem(IconData i, String t, String v) => Padding( + padding: const EdgeInsets.only(bottom: 6), + child: Row(children: [ + Icon(i, color: Colors.white, size: 18), + const SizedBox(width: 10), + SizedBox( + width: 150, + child: Text(t, + style: GoogleFonts.poppins(color: Colors.white, fontSize: 13))), + const Text(": ", style: TextStyle(color: Colors.white)), + Expanded( + child: Text(v, + style: GoogleFonts.poppins(color: Colors.white, fontSize: 13))) + ])); + + Widget _infoItemCustom(IconData i, String t, String v, Color c) => Padding( + padding: const EdgeInsets.only(bottom: 6), + child: Row(children: [ + Icon(i, color: c, size: 18), + const SizedBox(width: 10), + SizedBox( + width: 150, + child: Text(t, style: GoogleFonts.poppins(color: c, fontSize: 13))), + Text(": ", style: TextStyle(color: c)), + Expanded( + child: Text(v, style: GoogleFonts.poppins(color: c, fontSize: 13))) + ])); + + Widget _emptySchedule() => Column(children: [ + const Icon(Icons.event_busy, size: 30, color: Colors.grey), + Text("Tidak ada kegiatan", + style: GoogleFonts.poppins(color: Colors.grey, fontSize: 12)) + ]); + + Future _checkLoginStatus() async { + final prefs = await SharedPreferences.getInstance(); + if (!(prefs.getBool("isLogin") ?? false) && mounted) { + Navigator.pushReplacementNamed(context, "/login"); + } + } +} diff --git a/lib/ibu/ibu_drawer.dart b/lib/ibu/ibu_drawer.dart new file mode 100644 index 0000000..a16b2ad --- /dev/null +++ b/lib/ibu/ibu_drawer.dart @@ -0,0 +1,255 @@ +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import '../layout/main_layout.dart'; + +class IbuDrawer extends StatefulWidget { + const IbuDrawer({super.key}); + + @override + State createState() => _IbuDrawerState(); +} + +class _IbuDrawerState extends State { + String? fotoUser; + String namaUser = "Ibu Posyandu"; + + @override + void initState() { + super.initState(); + _loadUserData(); + } + + // Fungsi untuk mengambil data foto dan nama dari SharedPreferences + Future _loadUserData() async { + final prefs = await SharedPreferences.getInstance(); + setState(() { + fotoUser = prefs.getString('foto'); + namaUser = prefs.getString('nama') ?? "Ibu Posyandu"; + }); + } + + @override + Widget build(BuildContext context) { + return Drawer( + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.only( + topRight: Radius.circular(20), + bottomRight: Radius.circular(20), + ), + ), + child: Column( + children: [ + // ================= HEADER DENGAN LINK PROFIL ================= + Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(vertical: 40), + decoration: const BoxDecoration( + color: MainLayout.mainColor, + borderRadius: BorderRadius.only( + topRight: Radius.circular(20), + ), + ), + child: InkWell( + onTap: () { + // Berpindah ke halaman profil ibu + Navigator.pushReplacementNamed(context, '/profile-ibu'); + }, + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + CircleAvatar( + radius: 40, + backgroundColor: Colors.white, + child: CircleAvatar( + radius: 37, + backgroundColor: Colors.blue.shade100, + backgroundImage: (fotoUser != null && + fotoUser!.isNotEmpty) + ? NetworkImage( + "http://ta.myhost.id/E31230549/mposyandu_api/uploads/$fotoUser") + : null, + child: (fotoUser == null || fotoUser!.isEmpty) + ? const Icon( + Icons.person, + size: 40, + color: MainLayout.mainColor, + ) + : null, + ), + ), + const SizedBox(height: 12), + Text( + namaUser, + style: GoogleFonts.poppins( + color: Colors.white, + fontSize: 16, + fontWeight: FontWeight.bold, + ), + ), + Text( + "Lihat Profil", + style: GoogleFonts.poppins( + color: Colors.white70, + fontSize: 12, + ), + ), + ], + ), + ), + ), + + // ================= MENU UTAMA ================= + Expanded( + child: ListView( + padding: EdgeInsets.zero, + children: [ + _item(context, Icons.home, "Home", '/dashboard-ibu'), + _item(context, Icons.pregnant_woman, "Pemeriksaan ANC", + '/pemeriksaan-anc'), + _item(context, Icons.child_care, "Pemeriksaan Balita", + '/pemeriksaan-balita'), + + // ================= MENU DROPDOWN GRAFIK ================= + Theme( + data: Theme.of(context) + .copyWith(dividerColor: Colors.transparent), + child: ExpansionTile( + leading: const Icon(Icons.bar_chart, + color: MainLayout.mainColor), + title: Text( + "Grafik Anak", + style: GoogleFonts.poppins( + fontWeight: FontWeight.w500, fontSize: 14), + ), + iconColor: MainLayout.mainColor, + textColor: MainLayout.mainColor, + collapsedIconColor: MainLayout.mainColor, + childrenPadding: + const EdgeInsets.only(left: 15, bottom: 10), + children: [ + _subItem(context, Icons.height, "Tinggi Badan / Usia", + '/grafik-tb-u'), + _subItem(context, Icons.monitor_weight, + "Berat Badan / Usia", '/grafik-bb-u'), + _subItem(context, Icons.compare_arrows, + "Berat Badan / Tinggi Badan", '/grafik-bb-tb'), + ], + ), + ), + + // ================= MENU DROPDOWN EDUKASI ================= + Theme( + data: Theme.of(context) + .copyWith(dividerColor: Colors.transparent), + child: ExpansionTile( + leading: + const Icon(Icons.school, color: MainLayout.mainColor), + title: Text( + "Edukasi", + style: GoogleFonts.poppins( + fontWeight: FontWeight.w500, fontSize: 14), + ), + iconColor: MainLayout.mainColor, + textColor: MainLayout.mainColor, + collapsedIconColor: MainLayout.mainColor, + childrenPadding: + const EdgeInsets.only(left: 15, bottom: 10), + children: [ + _subItem(context, Icons.pregnant_woman, + "Edukasi Ibu Hamil", '/edukasi-hamil'), + _subItem(context, Icons.child_friendly, "Edukasi Balita", + '/edukasi-balita'), + ], + ), + ), + ], + ), + ), + + const Divider(height: 1), + _logoutItem(context), + const SizedBox(height: 10), + ], + ), + ); + } + + /// Widget untuk item menu utama + Widget _item(BuildContext context, IconData icon, String text, String route) { + return ListTile( + leading: Icon(icon, color: MainLayout.mainColor), + title: Text( + text, + style: GoogleFonts.poppins( + fontWeight: FontWeight.w500, + fontSize: 14, + ), + ), + onTap: () { + Navigator.pushReplacementNamed(context, route); + }, + ); + } + + /// Widget untuk isi dropdown (Sub-menu) + Widget _subItem( + BuildContext context, IconData icon, String text, String route) { + return ListTile( + dense: true, + visualDensity: const VisualDensity(vertical: -2), + leading: + Icon(icon, color: MainLayout.mainColor.withOpacity(0.7), size: 20), + title: Text( + text, + style: GoogleFonts.poppins( + fontSize: 13, + color: Colors.black87, + ), + ), + onTap: () { + Navigator.pushNamed(context, route); + }, + ); + } + + /// Widget Logout + Widget _logoutItem(BuildContext context) { + return ListTile( + leading: const Icon(Icons.logout, color: MainLayout.mainColor), + title: Text( + "Logout", + style: GoogleFonts.poppins( + fontWeight: FontWeight.w500, + fontSize: 14, + ), + ), + onTap: () => _logout(context), + ); + } + + /// Fungsi Logout + Future _logout(BuildContext context) async { + final prefs = await SharedPreferences.getInstance(); + + // Menghapus data session satu per satu sesuai permintaan + await prefs.remove('isLogin'); + await prefs.remove('id_user'); + await prefs.remove('role'); + await prefs.remove('nama'); + await prefs.remove('email'); + await prefs.remove('no_hp'); + await prefs.remove('password'); + await prefs.remove('foto'); + await prefs.remove('desa_id'); + await prefs.remove('dusun_id'); + + if (context.mounted) { + Navigator.pushNamedAndRemoveUntil( + context, + "/login", + (route) => false, + ); + } + } +} diff --git a/lib/ibu/pemeriksaan_anc.dart b/lib/ibu/pemeriksaan_anc.dart new file mode 100644 index 0000000..6458733 --- /dev/null +++ b/lib/ibu/pemeriksaan_anc.dart @@ -0,0 +1,310 @@ +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:http/http.dart' as http; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../layout/main_layout.dart'; +import 'ibu_drawer.dart'; +import '../ibu/crud_pemeriksaan_anc/riwayat_pemeriksaan_anc.dart'; +// Import Dashboard Ibu agar navigasi PopScope berfungsi +import '../ibu/dashboard_ibu.dart'; + +class PemeriksaanANCPage extends StatefulWidget { + const PemeriksaanANCPage({super.key}); + + @override + State createState() => _PemeriksaanANCPageState(); +} + +class _PemeriksaanANCPageState extends State { + final String baseUrl = + "http://ta.myhost.id/E31230549/mposyandu_api/pemeriksaan_anc"; + + Map? dataPemeriksaan; + + String namaIbu = "-"; + String ibuHamilId = ""; + + bool isLoading = true; + + @override + void initState() { + super.initState(); + getDataANC(); + } + + Future getDataANC() async { + final prefs = await SharedPreferences.getInstance(); + + String? idUser = prefs.getString("id_user"); + + if (idUser == null) return; + + try { + final response = await http.post( + Uri.parse("$baseUrl/get_pemeriksaan_anc_ibu.php"), + body: {"user_id": idUser}, + ); + + final data = json.decode(response.body); + + if (data["success"]) { + setState(() { + namaIbu = data["nama"]; + + ibuHamilId = data["ibu_hamil_id"].toString(); + + dataPemeriksaan = data["pemeriksaan"]; + + isLoading = false; + }); + } + } catch (e) { + debugPrint("ERROR ANC: $e"); + + setState(() { + isLoading = false; + }); + } + } + + String formatTanggal(String? tanggal) { + if (tanggal == null || tanggal.isEmpty || tanggal == "0000-00-00") + return "-"; + + try { + DateTime dt = DateTime.parse(tanggal); + + const bulan = [ + "", + "Januari", + "Februari", + "Maret", + "April", + "Mei", + "Juni", + "Juli", + "Agustus", + "September", + "Oktober", + "November", + "Desember" + ]; + + return "${dt.day} ${bulan[dt.month]} ${dt.year}"; + } catch (e) { + return "-"; + } + } + + @override + Widget build(BuildContext context) { + return PopScope( + canPop: false, + onPopInvokedWithResult: (didPop, result) async { + if (didPop) return; + + // ✅ FIX FINAL: selalu kembali ke Dashboard Ibu + Navigator.pushAndRemoveUntil( + context, + MaterialPageRoute( + builder: (_) => const DashboardIbuPage(), + ), + (route) => false, + ); + }, + child: MainLayout( + title: "", + drawer: const IbuDrawer(), + body: isLoading + ? const Center(child: CircularProgressIndicator()) + : Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Center( + child: Text( + "Hasil Pemeriksaan", + textAlign: TextAlign.center, + style: GoogleFonts.poppins( + fontSize: 18, + fontWeight: FontWeight.w600, + ), + ), + ), + const SizedBox(height: 20), + Container( + width: double.infinity, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.08), + blurRadius: 10, + offset: const Offset(0, 4), + ), + ], + ), + child: Column( + children: [ + /// HEADER + Container( + width: double.infinity, + padding: const EdgeInsets.symmetric( + vertical: 10, horizontal: 12), + decoration: const BoxDecoration( + color: Colors.blue, + borderRadius: BorderRadius.vertical( + top: Radius.circular(12)), + ), + child: Text( + namaIbu, + style: GoogleFonts.poppins( + color: Colors.white, + fontSize: 13, + fontWeight: FontWeight.w600, + ), + ), + ), + + /// BODY CARD + Padding( + padding: const EdgeInsets.all(12), + child: dataPemeriksaan == null + ? Text( + "Belum ada pemeriksaan", + style: GoogleFonts.poppins( + fontSize: 12, color: Colors.grey), + ) + : Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + Text( + "Pemeriksaan Terakhir", + style: GoogleFonts.poppins( + fontSize: 12, + fontWeight: FontWeight.w700), + ), + + const SizedBox(height: 8), + + _row( + "Tanggal", + formatTanggal(dataPemeriksaan?[ + "tanggal_pemeriksaan"])), + + _row("Berat Badan", + "${dataPemeriksaan?["berat_badan"] ?? "-"} kg"), + + _row( + "Tekanan Darah", + dataPemeriksaan?["tekanan_darah"] ?? + "-"), + + _row("Tinggi Fundus", + "${dataPemeriksaan?["tinggi_fundus"] ?? "-"} cm"), + + _row( + "DJJ", + dataPemeriksaan?[ + "denyut_jantung_janin"] ?? + "-"), + + _row("HB", dataPemeriksaan?["hb"] ?? "-"), + + _row( + "Kaki Bengkak", + dataPemeriksaan?["kaki_bengkak"] ?? + "-"), + + _row("Keluhan", + dataPemeriksaan?["keluhan"] ?? "-"), + + _row("Tindak Lanjut", + dataPemeriksaan?["tindakan"] ?? "-"), + + const SizedBox(height: 20), + + /// BUTTON RIWAYAT + Center( + child: OutlinedButton.icon( + onPressed: ibuHamilId.isEmpty + ? null + : () { + Navigator.push( + context, + MaterialPageRoute( + builder: (_) => + RiwayatPemeriksaanAncPage( + ibuHamilId: ibuHamilId, + nama: namaIbu, + ), + ), + ); + }, + icon: const Icon(Icons.history, + size: 14, color: Colors.blue), + label: Text( + "Riwayat", + style: GoogleFonts.poppins( + fontSize: 12, + fontWeight: FontWeight.w600, + color: Colors.blue, + ), + ), + style: OutlinedButton.styleFrom( + side: const BorderSide( + color: Colors.blue, width: 1.5), + padding: const EdgeInsets.symmetric( + horizontal: 20, vertical: 8), + shape: RoundedRectangleBorder( + borderRadius: + BorderRadius.circular(25), + ), + ), + ), + ), + ], + ), + ), + ], + ), + ), + ], + ), + ), + ), + ); + } + + Widget _row(String label, String value) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 3), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: 130, + child: Text( + label, + style: GoogleFonts.poppins( + fontSize: 12, + fontWeight: FontWeight.w600, + color: Colors.black54), + ), + ), + Expanded( + child: Text( + ": $value", + style: GoogleFonts.poppins(fontSize: 12, color: Colors.black87), + ), + ), + ], + ), + ); + } +} diff --git a/lib/ibu/pemeriksaan_balita.dart b/lib/ibu/pemeriksaan_balita.dart new file mode 100644 index 0000000..cbaf4f4 --- /dev/null +++ b/lib/ibu/pemeriksaan_balita.dart @@ -0,0 +1,316 @@ +import 'dart:convert'; + +import 'package:flutter/material.dart'; + +import 'package:google_fonts/google_fonts.dart'; + +import 'package:http/http.dart' as http; + +import 'package:shared_preferences/shared_preferences.dart'; + +import '../layout/main_layout.dart'; + +import 'ibu_drawer.dart'; + +import '../ibu/crud_pemeriksaaan_balita/riwayat_pemeriksaan_balita.dart'; + +// Import Dashboard Ibu agar navigasi PopScope berfungsi + +import '../ibu/dashboard_ibu.dart'; + +class PemeriksaanBalitaIbuPage extends StatefulWidget { + const PemeriksaanBalitaIbuPage({super.key}); + + @override + State createState() => + _PemeriksaanBalitaIbuPageState(); +} + +class _PemeriksaanBalitaIbuPageState extends State { + List dataBalita = []; + + bool isLoading = true; + + final baseUrl = + "http://ta.myhost.id/E31230549/mposyandu_api/pemeriksaan_balita_ibu"; + + @override + void initState() { + super.initState(); + + getDataBalita(); + } + + Future getDataBalita() async { + final prefs = await SharedPreferences.getInstance(); + + // SESUAI KODE LOGIN: Mengambil key "id_user" (bukan "idUser" atau "user_id") + String? idUser = prefs.getString("id_user"); + + if (idUser == null) { + setState(() { + isLoading = false; + }); + return; + } + + try { + final response = await http.post( + Uri.parse("$baseUrl/get_pemeriksaan_balita_ibu.php"), + body: { + "id_user": idUser, // Mengirim string ID ke server PHP + }, + ); + + if (response.statusCode == 200) { + final data = json.decode(response.body); + + if (data["success"] == true) { + setState(() { + dataBalita = data["data"]; + isLoading = false; + }); + } else { + setState(() { + isLoading = false; + }); + } + } else { + setState(() { + isLoading = false; + }); + } + } catch (e) { + setState(() { + isLoading = false; + }); + debugPrint("Koneksi gagal atau eror data: $e"); + } + } + + String formatTanggal(String? tanggal) { + if (tanggal == null) return "-"; + + try { + DateTime dt = DateTime.parse(tanggal); + + const bulan = [ + "", + "Januari", + "Februari", + "Maret", + "April", + "Mei", + "Juni", + "Juli", + "Agustus", + "September", + "Oktober", + "November", + "Desember" + ]; + + return "${dt.day} ${bulan[dt.month]} ${dt.year}"; + } catch (e) { + return "-"; + } + } + + @override + Widget build(BuildContext context) { + return PopScope( + canPop: false, + onPopInvokedWithResult: (didPop, result) async { + if (didPop) return; + + // ✅ FIX FINAL: selalu kembali ke Dashboard Ibu + + Navigator.pushAndRemoveUntil( + context, + MaterialPageRoute( + builder: (_) => const DashboardIbuPage(), + ), + (route) => false, + ); + }, + child: MainLayout( + title: "", + drawer: const IbuDrawer(), + body: isLoading + ? const Center(child: CircularProgressIndicator()) + : Padding( + padding: const EdgeInsets.all(16), + child: Column( + children: [ + Center( + child: Text( + "Hasil Pemeriksaan", + style: GoogleFonts.poppins( + fontSize: 18, + fontWeight: FontWeight.w600, + ), + ), + ), + const SizedBox(height: 20), + Expanded( + child: dataBalita.isEmpty + ? Center( + child: Text( + "Belum ada data pemeriksaan", + style: GoogleFonts.poppins(fontSize: 12), + ), + ) + : ListView.builder( + itemCount: dataBalita.length, + itemBuilder: (context, index) { + final balita = dataBalita[index]; + + return _cardBalita(balita); + }, + ), + ), + ], + ), + ), + ), + ); + } + + Widget _cardBalita(Map balita) { + return Container( + margin: const EdgeInsets.only(bottom: 16), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12), + boxShadow: const [ + BoxShadow( + color: Colors.black12, + blurRadius: 8, + offset: Offset(0, 4), + ), + ], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), + decoration: const BoxDecoration( + color: Colors.blueAccent, + borderRadius: BorderRadius.vertical(top: Radius.circular(12)), + ), + child: Text( + balita["nama_balita"] ?? "-", + style: GoogleFonts.poppins( + color: Colors.white, + fontSize: 12, + fontWeight: FontWeight.w600, + ), + ), + ), + Padding( + padding: const EdgeInsets.all(12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + "Pemeriksaan Terakhir", + style: GoogleFonts.poppins( + fontSize: 12, + fontWeight: FontWeight.w600, + ), + ), + const SizedBox(height: 8), + _row("Tanggal Posyandu", + formatTanggal(balita["tanggal_pemeriksaan"])), + _row("Berat Badan", "${balita["bb"] ?? "-"} kg"), + _row("Tinggi Badan", "${balita["tb"] ?? "-"} cm"), + _row("Lingkar Kepala", "${balita["lk"] ?? "-"} cm"), + _row("Status Gizi (BB/U)", balita["status_bbu"] ?? "-"), + _row("Status Gizi (TB/U)", balita["status_tbu"] ?? "-"), + _row("Status Gizi (BB/TB)", balita["status_bbtb"] ?? "-"), + _row("Pemberian Imunisasi", balita["imunisasi"] ?? "-"), + _row("Pemberian Vitamin A", balita["vitamin_a"] ?? "-"), + _row("Pemberian PMT", balita["pmt"] ?? "-"), + _row("Catatan Kader", balita["catatan"] ?? "-"), + const SizedBox(height: 16), + Center( + child: OutlinedButton.icon( + onPressed: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => RiwayatPemeriksaanBalitaPage( + idBalita: balita["id_balita"].toString(), + namaBalita: balita["nama_balita"] ?? "-", + ), + ), + ); + }, + icon: const Icon(Icons.history, + size: 14, color: Colors.blueAccent), + label: Text( + "Riwayat", + style: GoogleFonts.poppins( + fontSize: 12, + color: Colors.blueAccent, + fontWeight: FontWeight.w500, + ), + ), + style: OutlinedButton.styleFrom( + side: const BorderSide(color: Colors.blueAccent), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(20), + ), + padding: const EdgeInsets.symmetric( + horizontal: 20, vertical: 4), + minimumSize: const Size(0, 34), + ), + ), + ), + ], + ), + ), + ], + ), + ); + } + + Widget _row(String label, String value) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 2), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: 150, + child: Text( + label, + style: GoogleFonts.poppins( + fontSize: 12, + fontWeight: FontWeight.w600, + ), + ), + ), + SizedBox( + width: 10, + child: Text( + ":", + style: GoogleFonts.poppins( + fontSize: 12, + fontWeight: FontWeight.w600, + ), + ), + ), + Expanded( + child: Text( + value, + style: GoogleFonts.poppins(fontSize: 12), + ), + ), + ], + ), + ); + } +} diff --git a/lib/ibu/profile_ibu.dart b/lib/ibu/profile_ibu.dart new file mode 100644 index 0000000..7087b8c --- /dev/null +++ b/lib/ibu/profile_ibu.dart @@ -0,0 +1,588 @@ +import 'dart:io'; +import 'dart:convert'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:image_picker/image_picker.dart'; +import 'package:http/http.dart' as http; +import '../pages/login_page.dart'; +import '../ibu/dashboard_ibu.dart'; + +class ProfileIbuPage extends StatefulWidget { + const ProfileIbuPage({super.key}); + + @override + State createState() => _ProfileIbuPageState(); +} + +class _ProfileIbuPageState extends State { + // --- CONTROLLER TABEL USERS --- + final TextEditingController namaC = TextEditingController(); + final TextEditingController emailC = TextEditingController(); + final TextEditingController passwordC = TextEditingController(); + final TextEditingController noHpC = TextEditingController(); + final TextEditingController roleC = TextEditingController(); + final TextEditingController statusC = TextEditingController(); + + // --- CONTROLLER TABEL IBU --- + final TextEditingController nikC = TextEditingController(); + final TextEditingController noKkC = TextEditingController(); + final TextEditingController namaSuamiC = TextEditingController(); + final TextEditingController tempatLahirC = TextEditingController(); + final TextEditingController tanggalLahirC = TextEditingController(); + final TextEditingController pendidikanC = TextEditingController(); + final TextEditingController pekerjaanC = TextEditingController(); + final TextEditingController alamatDetailC = TextEditingController(); + final TextEditingController desaC = TextEditingController(); + final TextEditingController dusunC = TextEditingController(); + + // Variabel State + String? idUser; + String? fotoUser; + String? namaKader; + XFile? _pickedFile; + bool _obscurePassword = true; + bool isEditMode = false; + + // Variabel Dropdown + String? selectedAgama; + String? selectedGoldar; + + final List listAgama = [ + 'Islam', + 'Kristen', + 'Katolik', + 'Hindu', + 'Budha', + 'Khonghucu' + ]; + final List listGoldar = ['A', 'B', 'AB', 'O', '-']; + + @override + void initState() { + super.initState(); + _loadUserData(); + } + + @override + void dispose() { + namaC.dispose(); + emailC.dispose(); + passwordC.dispose(); + noHpC.dispose(); + roleC.dispose(); + statusC.dispose(); + nikC.dispose(); + noKkC.dispose(); + namaSuamiC.dispose(); + tempatLahirC.dispose(); + tanggalLahirC.dispose(); + pendidikanC.dispose(); + pekerjaanC.dispose(); + alamatDetailC.dispose(); + desaC.dispose(); + dusunC.dispose(); + super.dispose(); + } + + Future _loadUserData() async { + final prefs = await SharedPreferences.getInstance(); + final isLogin = prefs.getBool('isLogin') ?? false; + + if (!isLogin) { + if (!mounted) return; + Navigator.pushAndRemoveUntil( + context, + MaterialPageRoute(builder: (_) => const LoginPage(fromGuard: true)), + (route) => false, + ); + return; + } + + setState(() { + idUser = prefs.getString('id_user') ?? ""; + fotoUser = prefs.getString('foto'); + namaKader = prefs.getString('nama_kader') ?? "Kader"; + + namaC.text = prefs.getString('nama') ?? ""; + emailC.text = prefs.getString('email') ?? ""; + passwordC.text = prefs.getString('password') ?? ""; + noHpC.text = prefs.getString('no_hp') ?? ""; + roleC.text = "Ibu"; + statusC.text = prefs.getString('status_aktif') ?? "Aktif"; + + nikC.text = prefs.getString('nik') ?? "-"; + noKkC.text = prefs.getString('no_kk') ?? "-"; + namaSuamiC.text = prefs.getString('nama_suami') ?? ""; + tempatLahirC.text = prefs.getString('tempat_lahir') ?? "-"; + tanggalLahirC.text = prefs.getString('tanggal_lahir') ?? "-"; + pendidikanC.text = prefs.getString('pendidikan') ?? ""; + pekerjaanC.text = prefs.getString('pekerjaan') ?? ""; + alamatDetailC.text = prefs.getString('alamat_detail') ?? ""; + desaC.text = prefs.getString('nama_desa') ?? "-"; + dusunC.text = prefs.getString('nama_dusun') ?? "-"; + + String? dbAgama = prefs.getString('agama'); + if (listAgama.contains(dbAgama)) selectedAgama = dbAgama; + + String? dbGoldar = prefs.getString('golongan_darah'); + if (listGoldar.contains(dbGoldar)) selectedGoldar = dbGoldar; + }); + } + + void _showError(String msg) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(msg), backgroundColor: Colors.red), + ); + } + + // Fungsi untuk menangani klik foto/hapus saat belum edit + void _warnEditFirst() { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text( + "Klik tombol edit di bawah untuk mengubah atau menghapus foto"), + backgroundColor: Colors.red, + ), + ); + } + + Future _pickImage() async { + if (!isEditMode) { + _warnEditFirst(); + return; + } + final ImagePicker picker = ImagePicker(); + final XFile? image = await picker.pickImage(source: ImageSource.gallery); + if (image != null) setState(() => _pickedFile = image); + } + + void _removeImage() { + if (!isEditMode) { + _warnEditFirst(); + return; + } + setState(() { + _pickedFile = null; + fotoUser = ""; + }); + } + + void _saveProfile() async { + if (!isEditMode) return; + if (namaC.text.isEmpty || emailC.text.isEmpty) { + _showError("Nama dan Email tidak boleh kosong"); + return; + } + + try { + var request = http.MultipartRequest( + 'POST', + Uri.parse( + "http://ta.myhost.id/E31230549/mposyandu_api/users/update_profile_ibu.php"), + ); + + request.fields['id_user'] = idUser ?? ""; + request.fields['nama'] = namaC.text; + request.fields['email'] = emailC.text; + request.fields['password'] = passwordC.text; + request.fields['no_hp'] = noHpC.text; + request.fields['foto_lama'] = fotoUser ?? ""; + request.fields['nama_suami'] = namaSuamiC.text; + request.fields['golongan_darah'] = selectedGoldar ?? ""; + request.fields['pendidikan'] = pendidikanC.text; + request.fields['pekerjaan'] = pekerjaanC.text; + request.fields['agama'] = selectedAgama ?? ""; + request.fields['alamat_detail'] = alamatDetailC.text; + + if (_pickedFile != null) { + Uint8List data = await _pickedFile!.readAsBytes(); + request.files.add(http.MultipartFile.fromBytes('foto', data, + filename: _pickedFile!.name)); + } + + var response = await request.send(); + var responseData = await response.stream.bytesToString(); + var result = json.decode(responseData); + + if (result['status'] == 'success') { + final prefs = await SharedPreferences.getInstance(); + await prefs.setString('nama', namaC.text); + await prefs.setString('email', emailC.text); + await prefs.setString('no_hp', noHpC.text); + await prefs.setString('nama_suami', namaSuamiC.text); + await prefs.setString('golongan_darah', selectedGoldar ?? ""); + await prefs.setString('agama', selectedAgama ?? ""); + + if (result['foto'] != null) + await prefs.setString('foto', result['foto']); + + setState(() { + isEditMode = false; + _pickedFile = null; + if (result['foto'] != null) fotoUser = result['foto']; + }); + + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text("Profil berhasil diperbarui")), + ); + } + } catch (e) { + _showError("Gagal menyimpan: $e"); + } + } + + @override + Widget build(BuildContext context) { + bool hasPhoto = + _pickedFile != null || (fotoUser != null && fotoUser!.isNotEmpty); + + return PopScope( + canPop: false, + onPopInvokedWithResult: (didPop, result) async { + if (didPop) return; + Navigator.pushAndRemoveUntil( + context, + MaterialPageRoute( + builder: (_) => const DashboardIbuPage(), + ), + (route) => false, + ); + }, + child: Scaffold( + backgroundColor: const Color(0xfff4f6fb), + appBar: AppBar( + backgroundColor: Colors.blue, + elevation: 0, + leading: IconButton( + icon: const Icon(Icons.arrow_back, color: Colors.white), + onPressed: () { + Navigator.pushAndRemoveUntil( + context, + MaterialPageRoute( + builder: (context) => const DashboardIbuPage()), + (route) => false, + ); + }, + ), + title: Text("", + style: GoogleFonts.poppins(color: Colors.white, fontSize: 18)), + ), + body: SingleChildScrollView( + child: Column( + children: [ + Container( + width: double.infinity, + decoration: const BoxDecoration( + color: Colors.blue, + borderRadius: + BorderRadius.vertical(bottom: Radius.circular(30)), + ), + padding: const EdgeInsets.only(bottom: 30), + child: Column( + children: [ + Stack( + children: [ + CircleAvatar( + radius: 65, + backgroundColor: Colors.white, + child: CircleAvatar( + radius: 60, + backgroundColor: Colors.blue.shade100, + backgroundImage: _pickedFile != null + ? (kIsWeb + ? NetworkImage(_pickedFile!.path) + : FileImage(File(_pickedFile!.path)) + as ImageProvider) + : (fotoUser != null && fotoUser!.isNotEmpty) + ? NetworkImage( + "http://ta.myhost.id/E31230549/mposyandu_api/uploads/$fotoUser") + : null, + child: !hasPhoto + ? const Icon(Icons.person, + size: 60, color: Colors.blue) + : null, + ), + ), + // Tombol Kamera + Positioned( + bottom: 0, + right: hasPhoto ? 40 : 0, + child: GestureDetector( + onTap: _pickImage, + child: CircleAvatar( + radius: 18, + backgroundColor: + isEditMode ? Colors.black : Colors.grey, + child: const Icon(Icons.camera_alt, + color: Colors.white, size: 18), + ), + ), + ), + // Tombol Hapus + if (hasPhoto) + Positioned( + bottom: 0, + right: 0, + child: GestureDetector( + onTap: _removeImage, + child: CircleAvatar( + radius: 18, + backgroundColor: + isEditMode ? Colors.red : Colors.grey, + child: const Icon(Icons.delete, + color: Colors.white, size: 18), + ), + ), + ), + ], + ), + const SizedBox(height: 12), + Text( + namaC.text, + style: GoogleFonts.poppins( + fontSize: 18, + fontWeight: FontWeight.bold, + color: Colors.white), + ), + ], + ), + ), + Padding( + padding: const EdgeInsets.all(20), + child: Column( + children: [ + Card( + color: Colors.white, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(15)), + child: Padding( + padding: const EdgeInsets.all(20), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildSectionTitle("Informasi Akun & Kontak"), + _buildField("Nama Lengkap", namaC), + _buildField("Email", emailC), + _buildPasswordField("Password", passwordC), + _buildField("No. HP", noHpC, isNumber: true), + const Divider(height: 30), + _buildSectionTitle("Informasi Resmi"), + Container( + padding: const EdgeInsets.all(12), + margin: const EdgeInsets.only(bottom: 15), + decoration: BoxDecoration( + color: Colors.amber.shade50, + borderRadius: BorderRadius.circular(8), + border: + Border.all(color: Colors.amber.shade200), + ), + child: Row( + children: [ + const Icon(Icons.info_outline, + color: Colors.amber, size: 20), + const SizedBox(width: 10), + Expanded( + child: Text( + "Jika ada kesalahan data pada kolom di bawah ini, silahkan hubungi kader: $namaKader", + style: GoogleFonts.poppins( + fontSize: 11, + color: Colors.brown.shade700, + fontStyle: FontStyle.italic), + ), + ), + ], + ), + ), + _buildField("NIK", nikC, isReadOnly: true), + _buildField("No. KK", noKkC, isReadOnly: true), + _buildField("Tempat Lahir", tempatLahirC, + isReadOnly: true), + _buildField("Tanggal Lahir", tanggalLahirC, + isReadOnly: true), + _buildField("Desa", desaC, isReadOnly: true), + _buildField("Dusun", dusunC, isReadOnly: true), + const Divider(height: 30), + _buildSectionTitle("Data Tambahan"), + _buildField("Nama Suami", namaSuamiC), + _buildDropdown( + "Golongan Darah", + selectedGoldar, + listGoldar, + (val) => setState(() => selectedGoldar = val)), + _buildField("Pendidikan", pendidikanC), + _buildField("Pekerjaan", pekerjaanC), + _buildDropdown("Agama", selectedAgama, listAgama, + (val) => setState(() => selectedAgama = val)), + _buildField("Alamat Detail", alamatDetailC), + ], + ), + ), + ), + const SizedBox(height: 25), + Row( + children: [ + Expanded( + child: _buildActionButton( + label: "Edit Profil", + color: Colors.orange, + onTap: () => + setState(() => isEditMode = true))), + const SizedBox(width: 15), + Expanded( + child: _buildActionButton( + label: "Simpan", + color: Colors.blue, + onTap: _saveProfile)), + ], + ), + const SizedBox(height: 40), + ], + ), + ), + ], + ), + ), + ), + ); + } + + Widget _buildSectionTitle(String title) { + return Padding( + padding: const EdgeInsets.only(bottom: 10), + child: Text(title, + style: GoogleFonts.poppins( + fontSize: 14, + fontWeight: FontWeight.bold, + color: Colors.blueGrey)), + ); + } + + Widget _buildDropdown(String label, String? value, List items, + Function(String?) onChanged) { + return Padding( + padding: const EdgeInsets.only(bottom: 15), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(label, + style: GoogleFonts.poppins( + fontSize: 12, + fontWeight: FontWeight.w600, + color: Colors.grey[600])), + const SizedBox(height: 5), + Container( + padding: const EdgeInsets.symmetric(horizontal: 12), + decoration: BoxDecoration( + color: !isEditMode ? Colors.grey[100] : Colors.white, + borderRadius: BorderRadius.circular(8), + border: Border.all(color: Colors.grey.shade300), + ), + child: DropdownButtonHideUnderline( + child: DropdownButton( + value: value, + isExpanded: true, + items: items + .map((s) => DropdownMenuItem( + value: s, + child: + Text(s, style: GoogleFonts.poppins(fontSize: 14)))) + .toList(), + onChanged: isEditMode ? onChanged : null, + ), + ), + ), + ], + ), + ); + } + + Widget _buildField(String label, TextEditingController controller, + {bool isReadOnly = false, bool isNumber = false}) { + return Padding( + padding: const EdgeInsets.only(bottom: 15), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(label, + style: GoogleFonts.poppins( + fontSize: 12, + fontWeight: FontWeight.w600, + color: Colors.grey[600])), + const SizedBox(height: 5), + TextField( + controller: controller, + readOnly: isReadOnly || !isEditMode, + keyboardType: isNumber ? TextInputType.phone : TextInputType.text, + style: GoogleFonts.poppins(fontSize: 14), + decoration: InputDecoration( + filled: true, + fillColor: + (isReadOnly || !isEditMode) ? Colors.grey[100] : Colors.white, + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide(color: Colors.grey.shade300)), + contentPadding: + const EdgeInsets.symmetric(horizontal: 12, vertical: 12), + ), + ), + ], + ), + ); + } + + Widget _buildPasswordField(String label, TextEditingController controller) { + return Padding( + padding: const EdgeInsets.only(bottom: 15), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(label, + style: GoogleFonts.poppins( + fontSize: 12, + fontWeight: FontWeight.w600, + color: Colors.grey[600])), + const SizedBox(height: 5), + TextField( + controller: controller, + obscureText: _obscurePassword, + readOnly: !isEditMode, + style: GoogleFonts.poppins(fontSize: 14), + decoration: InputDecoration( + filled: true, + fillColor: !isEditMode ? Colors.grey[100] : Colors.white, + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide(color: Colors.grey.shade300)), + suffixIcon: IconButton( + icon: Icon( + _obscurePassword ? Icons.visibility_off : Icons.visibility), + onPressed: () => + setState(() => _obscurePassword = !_obscurePassword), + ), + ), + ), + ], + ), + ); + } + + Widget _buildActionButton( + {required String label, + required Color color, + required VoidCallback onTap}) { + return ElevatedButton( + onPressed: onTap, + style: ElevatedButton.styleFrom( + backgroundColor: color, + padding: const EdgeInsets.symmetric(vertical: 15), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)), + ), + child: Text(label, + style: GoogleFonts.poppins( + color: Colors.white, fontWeight: FontWeight.bold)), + ); + } +} diff --git a/lib/kader/crud_balita/edit_balita.dart b/lib/kader/crud_balita/edit_balita.dart new file mode 100644 index 0000000..3ac6094 --- /dev/null +++ b/lib/kader/crud_balita/edit_balita.dart @@ -0,0 +1,455 @@ +import 'dart:convert'; +import 'dart:developer'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:http/http.dart' as http; +import 'package:shared_preferences/shared_preferences.dart'; + +class EditBalitaPage extends StatefulWidget { + final Map data; + + const EditBalitaPage({super.key, required this.data}); + + @override + State createState() => _EditBalitaPageState(); +} + +class _EditBalitaPageState extends State { + final _formKey = GlobalKey(); + + final namaC = TextEditingController(); + final nikC = TextEditingController(); + final tglLahirC = TextEditingController(); + final usiaC = TextEditingController(); + final tempatLahirC = TextEditingController(); + final anakKeC = TextEditingController(); + final beratC = TextEditingController(); + final panjangC = TextEditingController(); + final tglDaftarC = TextEditingController(); + + bool _isSaving = false; + bool _isLoadingIbu = true; + + List ibuList = []; + String? selectedIbuId; + String? selectedJK; + + // Tambahkan Variabel Status + String? selectedStatus; + + int usiaBulan = 0; + + @override + void initState() { + super.initState(); + + namaC.text = widget.data["nama"] ?? ""; + nikC.text = widget.data["nik_balita"] ?? ""; + tglLahirC.text = widget.data["tanggal_lahir"] ?? ""; + tempatLahirC.text = widget.data["tempat_lahir"] ?? ""; + anakKeC.text = widget.data["anak_ke"]?.toString() ?? ""; + beratC.text = widget.data["berat_lahir"]?.toString() ?? ""; + panjangC.text = widget.data["panjang_lahir"]?.toString() ?? ""; + tglDaftarC.text = widget.data["tanggal_daftar"] ?? ""; + + selectedIbuId = widget.data["ibu_id"]?.toString(); + selectedJK = widget.data["jenis_kelamin"]; + + // Inisialisasi Status dari data yang diterima + selectedStatus = widget.data["status"]?.toString().toLowerCase(); + + if (tglLahirC.text.isNotEmpty) { + try { + DateTime tgl = DateTime.parse(tglLahirC.text); + _hitungUsia(tgl); + } catch (e) { + usiaBulan = int.tryParse(widget.data["usia"]?.toString() ?? "0") ?? 0; + _setUsiaText(); + } + } else { + usiaBulan = int.tryParse(widget.data["usia"]?.toString() ?? "0") ?? 0; + _setUsiaText(); + } + + _loadIbu(); + } + + @override + void dispose() { + namaC.dispose(); + nikC.dispose(); + tglLahirC.dispose(); + usiaC.dispose(); + tempatLahirC.dispose(); + anakKeC.dispose(); + beratC.dispose(); + panjangC.dispose(); + tglDaftarC.dispose(); + super.dispose(); + } + + Future _loadIbu() async { + try { + final prefs = await SharedPreferences.getInstance(); + final String? role = prefs.getString("role"); + final dynamic rawDusunId = prefs.get("dusun_id"); + final String userDusunId = rawDusunId?.toString() ?? ""; + + final res = await http.get( + Uri.parse( + "http://ta.myhost.id/E31230549/mposyandu_api/ibu/get_ibu_dropdown.php?dusun_id=$userDusunId"), + ); + + final data = json.decode(res.body); + + if (data["success"] == true) { + List allIbu = data["data"] ?? []; + + if (mounted) { + setState(() { + if (role == 'kader' && userDusunId != "" && userDusunId != "0") { + ibuList = allIbu.where((ibu) { + return ibu["dusun_id"].toString() == userDusunId; + }).toList(); + + bool exists = + ibuList.any((e) => e["id"].toString() == selectedIbuId); + if (!exists) { + var currentIbu = allIbu.firstWhere( + (e) => e["id"].toString() == selectedIbuId, + orElse: () => null); + + if (currentIbu != null) { + ibuList.add(currentIbu); + } else { + ibuList.add({ + "id": selectedIbuId, + "label": widget.data["nama_ibu"] ?? "Ibu Saat Ini" + }); + } + } + } else { + ibuList = allIbu; + } + _isLoadingIbu = false; + }); + } + } + } catch (e) { + log("Error load ibu: $e"); + if (mounted) setState(() => _isLoadingIbu = false); + } + } + + void _hitungUsia(DateTime tgl) { + final now = DateTime.now(); + int tahun = now.year - tgl.year; + int bulan = now.month - tgl.month; + int hari = now.day - tgl.day; + + if (hari < 0) { + bulan--; + final prevMonth = DateTime(now.year, now.month, 0); + hari += prevMonth.day; + } + + if (bulan < 0) { + tahun--; + bulan += 12; + } + + usiaBulan = (tahun * 12) + bulan; + _setUsiaText(tahun, bulan, hari); + } + + void _setUsiaText([int? tahun, int? bulan, int? hari]) { + if (tahun == null || bulan == null) { + tahun = usiaBulan ~/ 12; + bulan = usiaBulan % 12; + hari = 0; + } + usiaC.text = "$tahun tahun $bulan bulan $hari hari"; + } + + Future _pickDate(TextEditingController controller) async { + DateTime initialDate = DateTime.now(); + if (controller.text.isNotEmpty) { + try { + initialDate = DateTime.parse(controller.text); + } catch (_) {} + } + + final picked = await showDatePicker( + context: context, + firstDate: DateTime(2000), + lastDate: DateTime.now(), + initialDate: initialDate, + ); + + if (picked != null) { + setState(() { + controller.text = picked.toIso8601String().split("T").first; + if (controller == tglLahirC) { + _hitungUsia(picked); + } + }); + } + } + + Future _update() async { + if (!_formKey.currentState!.validate()) return; + + if (selectedIbuId == null || selectedJK == null || selectedStatus == null) { + _showSnackBar("Lengkapi data wajib terlebih dahulu"); + return; + } + + setState(() => _isSaving = true); + + try { + final response = await http.post( + Uri.parse( + "http://ta.myhost.id/E31230549/mposyandu_api/balita/edit_balita.php"), + body: { + "id": widget.data["id"].toString(), + "ibu_id": selectedIbuId!, + "nama": namaC.text.trim(), + "nik_balita": nikC.text.trim(), + "jenis_kelamin": selectedJK!, + "tanggal_lahir": tglLahirC.text.trim(), + "tempat_lahir": tempatLahirC.text.trim(), + "anak_ke": anakKeC.text.trim(), + "berat_lahir": beratC.text.trim(), + "panjang_lahir": panjangC.text.trim(), + "tanggal_daftar": tglDaftarC.text.trim(), + "status": selectedStatus!, // Kirim status ke API + }, + ); + + log("Response: ${response.body}"); + final data = json.decode(response.body); + + if (data["success"] == true) { + if (!mounted) return; + _showSnackBar("Data berhasil diupdate"); + Navigator.pop(context, true); + } else { + _showSnackBar(data["message"] ?? "Gagal update"); + } + } catch (e) { + log("Error update: $e"); + _showSnackBar("Terjadi kesalahan koneksi"); + } finally { + if (mounted) setState(() => _isSaving = false); + } + } + + void _showSnackBar(String msg) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(msg, style: GoogleFonts.poppins(fontSize: 12))), + ); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + backgroundColor: Colors.blue, + foregroundColor: Colors.white, + title: Text("", + style: + GoogleFonts.poppins(fontSize: 14, fontWeight: FontWeight.w600)), + ), + backgroundColor: const Color(0xfff4f6fb), + body: Center( + child: SingleChildScrollView( + padding: const EdgeInsets.all(16), + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 420), + child: Container( + padding: const EdgeInsets.all(24), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(20), + boxShadow: const [ + BoxShadow( + blurRadius: 16, + color: Colors.black12, + offset: Offset(0, 8)) + ], + ), + child: Form( + key: _formKey, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text( + "Edit Data Balita", + textAlign: TextAlign.center, + style: GoogleFonts.poppins( + fontSize: 18, + fontWeight: FontWeight.bold, + color: Colors.black87, + ), + ), + const SizedBox(height: 24), + _isLoadingIbu + ? const Center(child: CircularProgressIndicator()) + : DropdownButtonFormField( + isExpanded: true, + value: selectedIbuId, + style: GoogleFonts.poppins( + fontSize: 12, color: Colors.black), + decoration: _decoration("Pilih Ibu (Orang Tua)"), + items: ibuList.map((item) { + return DropdownMenuItem( + value: item["id"].toString(), + child: Text(item["label"] ?? item["nama"] ?? "", + overflow: TextOverflow.ellipsis, + style: GoogleFonts.poppins(fontSize: 12)), + ); + }).toList(), + onChanged: (v) => setState(() => selectedIbuId = v), + validator: (v) => + v == null ? "Ibu wajib dipilih" : null, + ), + const SizedBox(height: 16), + _input("Nama Lengkap Balita", namaC), + _input("NIK Balita", nikC, keyboard: TextInputType.number), + DropdownButtonFormField( + value: selectedJK, + style: GoogleFonts.poppins( + fontSize: 12, color: Colors.black), + decoration: _decoration("Jenis Kelamin"), + items: const [ + DropdownMenuItem(value: "L", child: Text("Laki-laki")), + DropdownMenuItem(value: "P", child: Text("Perempuan")), + ], + onChanged: (v) => setState(() => selectedJK = v), + validator: (v) => + v == null ? "Pilih jenis kelamin" : null, + ), + const SizedBox(height: 16), + _input("Tempat Lahir", tempatLahirC, isOptional: true), + TextFormField( + controller: tglLahirC, + readOnly: true, + style: GoogleFonts.poppins(fontSize: 12), + onTap: () => _pickDate(tglLahirC), + decoration: _decoration("Tanggal Lahir").copyWith( + suffixIcon: const Icon(Icons.calendar_today, + size: 18, color: Colors.black), + ), + validator: (v) => + (v == null || v.isEmpty) ? "Wajib diisi" : null, + ), + const SizedBox(height: 16), + TextFormField( + controller: usiaC, + readOnly: true, + style: GoogleFonts.poppins(fontSize: 12), + decoration: _decoration("Usia (Otomatis)"), + ), + const SizedBox(height: 16), + _input("Anak Ke-", anakKeC, + keyboard: TextInputType.number, isOptional: true), + _input("Berat Lahir (kg)", beratC, + keyboard: const TextInputType.numberWithOptions( + decimal: true), + isOptional: true), + _input("Panjang Lahir (cm)", panjangC, + keyboard: const TextInputType.numberWithOptions( + decimal: true), + isOptional: true), + + // DROPDOWN STATUS BARU + DropdownButtonFormField( + value: selectedStatus, + style: GoogleFonts.poppins( + fontSize: 12, color: Colors.black), + decoration: _decoration("Status Seleksi"), + items: const [ + DropdownMenuItem( + value: "belum lolos", child: Text("Belum Lolos")), + DropdownMenuItem(value: "lolos", child: Text("Lolos")), + ], + onChanged: (v) => setState(() => selectedStatus = v), + validator: (v) => v == null ? "Pilih status" : null, + ), + const SizedBox(height: 16), + + TextFormField( + controller: tglDaftarC, + readOnly: true, + style: GoogleFonts.poppins(fontSize: 12), + onTap: () => _pickDate(tglDaftarC), + decoration: _decoration("Tanggal Daftar").copyWith( + suffixIcon: const Icon(Icons.calendar_today, + size: 18, color: Colors.black), + ), + validator: (v) => + (v == null || v.isEmpty) ? "Wajib diisi" : null, + ), + const SizedBox(height: 28), + SizedBox( + height: 50, + child: OutlinedButton( + onPressed: _isSaving ? null : _update, + style: OutlinedButton.styleFrom( + side: const BorderSide( + color: Colors.blueAccent, width: 2), + shape: const StadiumBorder(), + ), + child: _isSaving + ? const Center( + child: SizedBox( + width: 20, + height: 20, + child: CircularProgressIndicator( + strokeWidth: 2, + color: Colors.blueAccent))) + : Text("Simpan Perubahan", + style: GoogleFonts.poppins( + fontWeight: FontWeight.bold, + fontSize: 14, + color: Colors.blueAccent)), + ), + ) + ], + ), + ), + ), + ), + ), + ), + ); + } + + Widget _input(String label, TextEditingController c, + {TextInputType keyboard = TextInputType.text, bool isOptional = false}) { + return Padding( + padding: const EdgeInsets.only(bottom: 16), + child: TextFormField( + controller: c, + keyboardType: keyboard, + style: GoogleFonts.poppins(fontSize: 12), + decoration: _decoration(label), + validator: (v) { + if (isOptional) return null; + return (v == null || v.trim().isEmpty) ? "$label wajib diisi" : null; + }, + ), + ); + } + + InputDecoration _decoration(String label) { + return InputDecoration( + filled: true, + fillColor: Colors.white, + labelText: label, + labelStyle: GoogleFonts.poppins(fontSize: 12), + border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)), + contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + ); + } +} diff --git a/lib/kader/crud_balita/tambah_balita.dart b/lib/kader/crud_balita/tambah_balita.dart new file mode 100644 index 0000000..2debac9 --- /dev/null +++ b/lib/kader/crud_balita/tambah_balita.dart @@ -0,0 +1,367 @@ +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:http/http.dart' as http; +import 'package:shared_preferences/shared_preferences.dart'; + +class TambahBalitaPage extends StatefulWidget { + const TambahBalitaPage({super.key}); + + @override + State createState() => _TambahBalitaPageState(); +} + +class _TambahBalitaPageState extends State { + final _formKey = GlobalKey(); + + final namaC = TextEditingController(); + final nikC = TextEditingController(); + final tglLahirC = TextEditingController(); + final tempatLahirC = TextEditingController(); + final anakKeC = TextEditingController(); + final beratC = TextEditingController(); + final panjangC = TextEditingController(); + final tglDaftarC = TextEditingController(); + final usiaC = TextEditingController(); + + bool _isSaving = false; + bool _isLoadingIbu = true; + + List ibuList = []; + String? selectedIbuId; + String? selectedJK; + + // Tambahkan Variabel Status + String selectedStatus = "belum lolos"; // Default sesuai DB + + @override + void initState() { + super.initState(); + tglDaftarC.text = DateTime.now().toIso8601String().split("T").first; + _loadIbu(); + } + + @override + void dispose() { + namaC.dispose(); + nikC.dispose(); + tglLahirC.dispose(); + tempatLahirC.dispose(); + anakKeC.dispose(); + beratC.dispose(); + panjangC.dispose(); + tglDaftarC.dispose(); + usiaC.dispose(); + super.dispose(); + } + + Future _loadIbu() async { + try { + final prefs = await SharedPreferences.getInstance(); + final dynamic rawDusunId = prefs.get("dusun_id"); + final String userDusunId = rawDusunId?.toString() ?? ""; + + final res = await http.get( + Uri.parse( + "http://ta.myhost.id/E31230549/mposyandu_api/ibu/get_ibu_dropdown.php?dusun_id=$userDusunId"), + ); + + final data = json.decode(res.body); + if (data["success"] == true) { + setState(() { + ibuList = data["data"] ?? []; + _isLoadingIbu = false; + }); + } else { + if (mounted) setState(() => _isLoadingIbu = false); + } + } catch (e) { + if (mounted) setState(() => _isLoadingIbu = false); + } + } + + void _hitungUsia(DateTime tgl) { + final now = DateTime.now(); + int tahun = now.year - tgl.year; + int bulan = now.month - tgl.month; + int hari = now.day - tgl.day; + + if (hari < 0) { + final prevMonth = DateTime(now.year, now.month, 0); + hari += prevMonth.day; + bulan--; + } + if (bulan < 0) { + bulan += 12; + tahun--; + } + usiaC.text = "$tahun tahun $bulan bulan $hari hari"; + } + + Future _pickDate(TextEditingController controller) async { + final picked = await showDatePicker( + context: context, + firstDate: DateTime(2000), + lastDate: DateTime.now(), + initialDate: DateTime.now(), + ); + + if (picked != null) { + setState(() { + controller.text = picked.toIso8601String().split("T").first; + if (controller == tglLahirC) { + _hitungUsia(picked); + } + }); + } + } + + Future _simpan() async { + if (!_formKey.currentState!.validate()) return; + if (selectedIbuId == null) { + _showMsg("Pilih ibu terlebih dahulu"); + return; + } + if (selectedJK == null) { + _showMsg("Pilih jenis kelamin"); + return; + } + + setState(() => _isSaving = true); + try { + final url = Uri.parse( + "http://ta.myhost.id/E31230549/mposyandu_api/balita/tambah_balita.php"); + final response = await http.post(url, body: { + "ibu_id": selectedIbuId!, + "nama": namaC.text.trim(), + "nik_balita": nikC.text.trim(), + "jenis_kelamin": selectedJK!, + "tanggal_lahir": tglLahirC.text.trim(), + "tempat_lahir": tempatLahirC.text.trim(), + "anak_ke": anakKeC.text.trim(), + "berat_lahir": beratC.text.trim(), + "panjang_lahir": panjangC.text.trim(), + "tanggal_daftar": tglDaftarC.text.trim(), + "status": selectedStatus, // Mengirim status ke API + }); + + final data = json.decode(response.body); + if (data["success"] == true) { + _showMsg("Data balita berhasil disimpan"); + if (mounted) Navigator.pop(context, true); + } else { + _showMsg(data["message"] ?? "Gagal simpan"); + } + } catch (e) { + _showMsg("Gagal koneksi server"); + } finally { + if (mounted) setState(() => _isSaving = false); + } + } + + void _showMsg(String msg) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(msg, style: GoogleFonts.poppins(fontSize: 12))), + ); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + backgroundColor: Colors.blue, + foregroundColor: Colors.white, + title: Text("", + style: + GoogleFonts.poppins(fontSize: 14, fontWeight: FontWeight.w600)), + ), + backgroundColor: const Color(0xfff4f6fb), + body: Center( + child: SingleChildScrollView( + padding: const EdgeInsets.all(16), + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 420), + child: Container( + padding: const EdgeInsets.all(24), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(20), + boxShadow: const [ + BoxShadow( + blurRadius: 16, + color: Colors.black12, + offset: Offset(0, 8)) + ], + ), + child: Form( + key: _formKey, + child: Column( + children: [ + Text("Tambah Data Balita", + style: GoogleFonts.poppins( + fontSize: 18, fontWeight: FontWeight.bold)), + const SizedBox(height: 24), + _isLoadingIbu + ? const Center(child: CircularProgressIndicator()) + : DropdownButtonFormField( + isExpanded: true, + value: selectedIbuId, + style: GoogleFonts.poppins( + fontSize: 12, color: Colors.black), + decoration: _decoration("Pilih Ibu (Orang Tua)"), + items: ibuList.map((item) { + return DropdownMenuItem( + value: item["id"].toString(), + child: Text( + "${item["nama"]} (${item["nama_suami"] ?? '-'})", + overflow: TextOverflow.ellipsis), + ); + }).toList(), + onChanged: (v) => setState(() => selectedIbuId = v), + validator: (v) => + v == null ? "Ibu wajib dipilih" : null, + ), + const SizedBox(height: 16), + _input("Nama Lengkap Balita", namaC), + _input("NIK Balita", nikC, + keyboard: TextInputType.number, isNik: true), + DropdownButtonFormField( + value: selectedJK, + style: GoogleFonts.poppins( + fontSize: 12, color: Colors.black), + decoration: _decoration("Jenis Kelamin"), + items: const [ + DropdownMenuItem(value: "L", child: Text("Laki-laki")), + DropdownMenuItem(value: "P", child: Text("Perempuan")), + ], + onChanged: (v) => setState(() => selectedJK = v), + validator: (v) => v == null ? "Wajib dipilih" : null, + ), + const SizedBox(height: 16), + _input("Tempat Lahir", tempatLahirC), + TextFormField( + controller: tglLahirC, + readOnly: true, + style: GoogleFonts.poppins(fontSize: 12), + onTap: () => _pickDate(tglLahirC), + decoration: _decoration("Tanggal Lahir").copyWith( + suffixIcon: const Icon(Icons.calendar_today, size: 18), + ), + validator: (v) => + v == null || v.isEmpty ? "Wajib diisi" : null, + ), + const SizedBox(height: 16), + TextFormField( + controller: usiaC, + readOnly: true, + style: GoogleFonts.poppins(fontSize: 12), + decoration: _decoration("Usia (Otomatis)"), + ), + const SizedBox(height: 16), + _input("Anak Ke-", anakKeC, keyboard: TextInputType.number), + _input("Berat Lahir (kg)", beratC, + keyboard: TextInputType.number), + _input("Panjang Lahir (cm)", panjangC, + keyboard: TextInputType.number), + + // DROPDOWN STATUS BARU + DropdownButtonFormField( + value: selectedStatus, + style: GoogleFonts.poppins( + fontSize: 12, color: Colors.black), + decoration: _decoration("Status Seleksi"), + items: const [ + DropdownMenuItem( + value: "belum lolos", child: Text("Belum Lolos")), + DropdownMenuItem(value: "lolos", child: Text("Lolos")), + ], + onChanged: (v) => setState(() => selectedStatus = v!), + ), + const SizedBox(height: 16), + + TextFormField( + controller: tglDaftarC, + readOnly: true, + style: GoogleFonts.poppins(fontSize: 12), + onTap: () => _pickDate(tglDaftarC), + decoration: _decoration("Tanggal Pendaftaran").copyWith( + suffixIcon: const Icon(Icons.calendar_today, size: 18), + ), + ), + const SizedBox(height: 28), + SizedBox( + width: double.infinity, + height: 50, + child: OutlinedButton( + onPressed: _isSaving ? null : _simpan, + style: OutlinedButton.styleFrom( + side: const BorderSide( + color: Colors.blueAccent, width: 1.5), + shape: const StadiumBorder(), + ), + child: _isSaving + ? const SizedBox( + height: 20, + width: 20, + child: + CircularProgressIndicator(strokeWidth: 2)) + : Text("Simpan Data Balita", + style: GoogleFonts.poppins( + fontWeight: FontWeight.bold, + color: Colors.blueAccent)), + ), + ), + ], + ), + ), + ), + ), + ), + ), + ); + } + + Widget _input(String label, TextEditingController c, + {TextInputType keyboard = TextInputType.text, bool isNik = false}) { + return Padding( + padding: const EdgeInsets.only(bottom: 16), + child: TextFormField( + controller: c, + keyboardType: keyboard, + inputFormatters: isNik + ? [ + FilteringTextInputFormatter.digitsOnly, + LengthLimitingTextInputFormatter(16) + ] + : null, + style: GoogleFonts.poppins(fontSize: 12), + decoration: _decoration(label), + validator: (v) { + if (![ + "Tempat Lahir", + "Anak Ke-", + "Berat Lahir (kg)", + "Panjang Lahir (cm)" + ].contains(label)) { + if (v == null || v.isEmpty) return "$label wajib"; + } + if (isNik && v != null && v.isNotEmpty && v.length != 16) + return "Harus 16 digit"; + return null; + }, + ), + ); + } + + InputDecoration _decoration(String label) { + return InputDecoration( + filled: true, + fillColor: Colors.white, + labelText: label, + labelStyle: GoogleFonts.poppins(fontSize: 12), + border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)), + contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + ); + } +} diff --git a/lib/kader/crud_ibu/edit_ibu.dart b/lib/kader/crud_ibu/edit_ibu.dart new file mode 100644 index 0000000..f8f2e18 --- /dev/null +++ b/lib/kader/crud_ibu/edit_ibu.dart @@ -0,0 +1,408 @@ +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:http/http.dart' as http; +import 'package:shared_preferences/shared_preferences.dart'; + +class EditIbuPage extends StatefulWidget { + final Map data; + + const EditIbuPage({super.key, required this.data}); + + @override + State createState() => _EditIbuPageState(); +} + +class _EditIbuPageState extends State { + final _formKey = GlobalKey(); + + // ================= CONTROLLER ================= + final nikC = TextEditingController(); + final noKkC = TextEditingController(); + final namaC = TextEditingController(); + final namaSuamiC = TextEditingController(); + final tempatLahirC = TextEditingController(); + final tglC = TextEditingController(); + final pendidikanC = TextEditingController(); + final pekerjaanC = TextEditingController(); + final alamatC = TextEditingController(); + final hpC = TextEditingController(); + final emailC = TextEditingController(); + final desaC = TextEditingController(); + final dusunC = TextEditingController(); + + String? selectedGolDarah; + String? selectedAgama; + int? selectedDesa; + int? selectedDusun; + + bool _isSaving = false; + bool isKader = false; + String? _emailError; + + final List golDarahList = const ['A', 'B', 'AB', 'O', '-']; + final List agamaList = const [ + 'Islam', + 'Kristen', + 'Katolik', + 'Hindu', + 'Buddha', + 'Konghucu' + ]; + + @override + void initState() { + super.initState(); + nikC.text = widget.data["nik"]?.toString() ?? ""; + noKkC.text = widget.data["no_kk"]?.toString() ?? ""; + namaC.text = widget.data["nama"]?.toString() ?? ""; + namaSuamiC.text = widget.data["nama_suami"]?.toString() ?? ""; + tempatLahirC.text = widget.data["tempat_lahir"]?.toString() ?? ""; + tglC.text = widget.data["tanggal_lahir"]?.toString() ?? ""; + pendidikanC.text = widget.data["pendidikan"]?.toString() ?? ""; + pekerjaanC.text = widget.data["pekerjaan"]?.toString() ?? ""; + alamatC.text = widget.data["alamat_detail"]?.toString() ?? ""; + hpC.text = widget.data["no_hp"]?.toString() ?? ""; + emailC.text = widget.data["email"]?.toString() ?? ""; + + selectedGolDarah = widget.data["golongan_darah"]; + selectedAgama = widget.data["agama"]; + selectedDesa = int.tryParse(widget.data["desa_id"].toString()); + selectedDusun = int.tryParse(widget.data["dusun_id"].toString()); + + _checkUserRole(); + } + + @override + void dispose() { + nikC.dispose(); + noKkC.dispose(); + namaC.dispose(); + namaSuamiC.dispose(); + tempatLahirC.dispose(); + tglC.dispose(); + pendidikanC.dispose(); + pekerjaanC.dispose(); + alamatC.dispose(); + hpC.dispose(); + emailC.dispose(); + desaC.dispose(); + dusunC.dispose(); + super.dispose(); + } + + Future _checkUserRole() async { + final prefs = await SharedPreferences.getInstance(); + final role = prefs.getString('role'); + if (role == 'kader') setState(() => isKader = true); + _getNamaWilayah(); + } + + Future _getNamaWilayah() async { + try { + final resDesa = await http + .get(Uri.parse("http://ta.myhost.id/E31230549/mposyandu_api/desa/get_desa.php")); + final dataDesa = _safeJson(resDesa.body); + if (dataDesa != null) { + final list = dataDesa is List ? dataDesa : dataDesa['data']; + final d = list.firstWhere( + (e) => int.parse(e['id'].toString()) == selectedDesa, + orElse: () => null); + if (d != null) desaC.text = d['nama_desa'].toString(); + } + + if (selectedDesa != null) { + final resDusun = await http.get(Uri.parse( + "http://ta.myhost.id/E31230549/mposyandu_api/dusun/get_dusun.php?desa_id=$selectedDesa")); + final dataDusun = _safeJson(resDusun.body); + if (dataDusun != null) { + final list = dataDusun is List ? dataDusun : dataDusun['data']; + final du = list.firstWhere( + (e) => int.parse(e['id'].toString()) == selectedDusun, + orElse: () => null); + if (du != null) dusunC.text = du['nama_dusun'].toString(); + } + } + } catch (e) { + debugPrint("Gagal memuat wilayah: $e"); + } + } + + dynamic _safeJson(String body) { + try { + if (body.trim().startsWith("<")) return null; + return json.decode(body); + } catch (e) { + return null; + } + } + + Future _update() async { + setState(() => _emailError = null); + if (!_formKey.currentState!.validate()) return; + setState(() => _isSaving = true); + + final Map bodyData = { + "id": widget.data["id"].toString(), + "nik": nikC.text.trim(), + "no_kk": noKkC.text.trim(), + "nama": namaC.text.trim(), + "nama_suami": namaSuamiC.text.trim(), + "tempat_lahir": tempatLahirC.text.trim(), + "tanggal_lahir": tglC.text.trim(), + "golongan_darah": selectedGolDarah ?? "-", + "pendidikan": pendidikanC.text.trim(), + "pekerjaan": pekerjaanC.text.trim(), + "agama": selectedAgama ?? "", + "no_hp": hpC.text.trim(), + "email": emailC.text.trim(), + "desa_id": selectedDesa.toString(), + "dusun_id": selectedDusun.toString(), + "alamat_detail": alamatC.text.trim(), + }; + + try { + final res = await http.post( + Uri.parse("http://ta.myhost.id/E31230549/mposyandu_api/ibu/update_ibu.php"), + body: bodyData, + ); + + final responseData = _safeJson(res.body); + + if (responseData != null) { + if (responseData["success"] == true) { + if (!mounted) return; + _showMsg("Data berhasil diperbarui"); + Navigator.pop(context, true); + } else { + String serverMsg = responseData["message"] ?? "Gagal memperbarui"; + if (serverMsg.toLowerCase().contains("email")) { + setState(() => _emailError = "Email sudah terdaftar"); + } else { + _showMsg("Gagal: $serverMsg"); + } + } + } else { + _showMsg("Terjadi kesalahan pada server (Format Response Salah)"); + } + } catch (e) { + _showMsg("Error Koneksi: $e"); + } finally { + if (mounted) setState(() => _isSaving = false); + } + } + + void _showMsg(String msg) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(msg, style: GoogleFonts.poppins(fontSize: 12))), + ); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + backgroundColor: Colors.blue, + foregroundColor: Colors.white, + elevation: 0, + title: Text("", + style: + GoogleFonts.poppins(fontSize: 18, fontWeight: FontWeight.w600)), + ), + body: SingleChildScrollView( + padding: const EdgeInsets.all(20), + child: Center( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 950), + child: Container( + padding: const EdgeInsets.all(24), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(20), + boxShadow: const [ + BoxShadow(blurRadius: 10, color: Colors.black12) + ]), + child: Form( + key: _formKey, + child: Column( + children: [ + // ================= JUDUL DI DALAM CARD ================= + Padding( + padding: const EdgeInsets.only(bottom: 30), + child: Text( + "Edit Data Ibu", + textAlign: TextAlign.center, + style: GoogleFonts.poppins( + fontSize: 18, + color: Colors.black, + fontWeight: FontWeight.bold, + ), + ), + ), + // ======================================================== + Wrap( + spacing: 20, + runSpacing: 20, + alignment: WrapAlignment.center, + children: [ + _input("NIK", nikC, isNikOrKk: true), + _input("No KK", noKkC, isNikOrKk: true), + _input("Nama Ibu", namaC), + _input("Nama Suami", namaSuamiC), + _input("Tempat Lahir", tempatLahirC), + _dateInput(), + _dropdown("Gol. Darah", selectedGolDarah, golDarahList, + (v) => setState(() => selectedGolDarah = v)), + _dropdown("Agama", selectedAgama, agamaList, + (v) => setState(() => selectedAgama = v)), + _input("Pendidikan", pendidikanC), + _input("Pekerjaan", pekerjaanC), + _input("No HP", hpC, isPhone: true), + _input("Email", emailC, isEmail: true), + _input("Desa", desaC, readOnly: true), + _input("Dusun", dusunC, readOnly: true), + _input("Alamat Detail", alamatC, lines: 2), + ], + ), + const SizedBox(height: 40), + SizedBox( + width: 300, // Ukuran tombol disesuaikan agar rapi + height: 50, + child: OutlinedButton( + onPressed: _isSaving ? null : _update, + style: OutlinedButton.styleFrom( + side: const BorderSide(color: Colors.blue, width: 2), + shape: const StadiumBorder(), + ), + child: _isSaving + ? const SizedBox( + height: 20, + width: 20, + child: CircularProgressIndicator( + color: Colors.blue, strokeWidth: 2)) + : Text("Simpan Perubahan", + style: GoogleFonts.poppins( + color: Colors.blue, + fontSize: 14, + fontWeight: FontWeight.bold, + )), + ), + ) + ], + ), + ), + ), + ), + ), + ), + ); + } + + // Widget Helper _input, _dateInput, _dropdown tetap sama seperti sebelumnya... + Widget _input(String label, TextEditingController c, + {bool isNikOrKk = false, + bool isPhone = false, + bool isEmail = false, + bool readOnly = false, + int lines = 1}) { + return SizedBox( + width: 280, + child: TextFormField( + controller: c, + readOnly: readOnly, + onChanged: (v) { + if (isEmail && _emailError != null) { + setState(() => _emailError = null); + } + }, + keyboardType: (isNikOrKk || isPhone) + ? TextInputType.number + : (isEmail ? TextInputType.emailAddress : TextInputType.text), + maxLines: lines, + inputFormatters: [ + if (isNikOrKk || isPhone) FilteringTextInputFormatter.digitsOnly, + if (isNikOrKk) LengthLimitingTextInputFormatter(16), + if (isPhone) LengthLimitingTextInputFormatter(13), + ], + style: GoogleFonts.poppins(fontSize: 12), + decoration: InputDecoration( + labelText: label, + filled: readOnly, + fillColor: readOnly ? Colors.grey[100] : Colors.white, + errorText: isEmail ? _emailError : null, + labelStyle: GoogleFonts.poppins(fontSize: 12), + errorStyle: GoogleFonts.poppins(color: Colors.red, fontSize: 10), + border: + OutlineInputBorder(borderRadius: BorderRadius.circular(10))), + validator: (v) { + if (v == null || v.isEmpty) return "Wajib diisi"; + if (isNikOrKk && v.length != 16) return "Harus 16 digit angka"; + if (isPhone && (v.length < 10 || v.length > 13)) + return "Harus 10 - 13 digit"; + if (isEmail) { + final emailRegExp = RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$'); + if (!emailRegExp.hasMatch(v)) return "Format email tidak valid"; + } + return null; + }, + ), + ); + } + + Widget _dateInput() { + return SizedBox( + width: 280, + child: TextFormField( + controller: tglC, + readOnly: true, + style: GoogleFonts.poppins(fontSize: 12), + decoration: InputDecoration( + labelText: "Tanggal Lahir", + labelStyle: GoogleFonts.poppins(fontSize: 12), + errorStyle: GoogleFonts.poppins(color: Colors.red, fontSize: 10), + suffixIcon: const Icon(Icons.calendar_today, size: 18), + border: + OutlineInputBorder(borderRadius: BorderRadius.circular(10))), + onTap: () async { + DateTime initial = + DateTime.tryParse(tglC.text) ?? DateTime(1990, 1, 1); + DateTime? p = await showDatePicker( + context: context, + initialDate: initial, + firstDate: DateTime(1950), + lastDate: DateTime.now()); + if (p != null) { + setState(() => tglC.text = p.toIso8601String().split("T").first); + } + }, + validator: (v) => (v == null || v.isEmpty) ? "Wajib diisi" : null, + ), + ); + } + + Widget _dropdown( + String label, String? val, List items, Function(String?) onChg) { + return SizedBox( + width: 280, + child: DropdownButtonFormField( + value: val, + style: GoogleFonts.poppins(color: Colors.black, fontSize: 12), + items: items + .map((e) => DropdownMenuItem( + value: e, + child: Text(e, style: GoogleFonts.poppins(fontSize: 12)))) + .toList(), + onChanged: onChg, + decoration: InputDecoration( + labelText: label, + labelStyle: GoogleFonts.poppins(fontSize: 12), + errorStyle: GoogleFonts.poppins(color: Colors.red, fontSize: 10), + border: + OutlineInputBorder(borderRadius: BorderRadius.circular(10))), + validator: (v) => (v == null || v.isEmpty) ? "Wajib dipilih" : null, + ), + ); + } +} diff --git a/lib/kader/crud_ibu/tambah_ibu.dart b/lib/kader/crud_ibu/tambah_ibu.dart new file mode 100644 index 0000000..3fdf453 --- /dev/null +++ b/lib/kader/crud_ibu/tambah_ibu.dart @@ -0,0 +1,411 @@ +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:http/http.dart' as http; +import 'package:shared_preferences/shared_preferences.dart'; + +class TambahIbuPage extends StatefulWidget { + const TambahIbuPage({super.key}); + + @override + State createState() => _TambahIbuPageState(); +} + +class _TambahIbuPageState extends State { + final _formKey = GlobalKey(); + + // ================= CONTROLLER ================= + final nikC = TextEditingController(); + final noKkC = TextEditingController(); + final namaC = TextEditingController(); + final namaSuamiC = TextEditingController(); + final tempatLahirC = TextEditingController(); + final tglC = TextEditingController(); + final pendidikanC = TextEditingController(); + final pekerjaanC = TextEditingController(); + final alamatC = TextEditingController(); + final hpC = TextEditingController(); + final emailC = TextEditingController(); + final passwordC = TextEditingController(); + + final desaC = TextEditingController(); + final dusunC = TextEditingController(); + + bool _isSaving = false; + String? _emailError; // Menyimpan pesan error email dari server + + String? selectedGolDarah; + String? selectedAgama; + String? selectedDesa; + String? selectedDusun; + String? currentKaderId; + + bool isKader = false; + + final List golDarahList = const ['A', 'B', 'AB', 'O', '-']; + final List agamaList = const [ + 'Islam', + 'Kristen', + 'Katolik', + 'Hindu', + 'Buddha', + 'Konghucu' + ]; + + @override + void initState() { + super.initState(); + _checkUserRole(); + + nikC.addListener(() { + String nikValue = nikC.text.trim(); + if (nikValue.length >= 6) { + passwordC.text = nikValue.substring(nikValue.length - 6); + } else { + passwordC.text = ""; + } + }); + } + + @override + void dispose() { + nikC.dispose(); + noKkC.dispose(); + namaC.dispose(); + namaSuamiC.dispose(); + tempatLahirC.dispose(); + tglC.dispose(); + pendidikanC.dispose(); + pekerjaanC.dispose(); + alamatC.dispose(); + hpC.dispose(); + emailC.dispose(); + passwordC.dispose(); + desaC.dispose(); + dusunC.dispose(); + super.dispose(); + } + + Future _checkUserRole() async { + try { + final prefs = await SharedPreferences.getInstance(); + final role = prefs.getString('role'); + final sessionDesaId = prefs.get('desa_id')?.toString(); + final sessionDusunId = prefs.get('dusun_id')?.toString(); + final sessionIdUser = prefs.getString('id_user'); + final sessionNamaDesa = prefs.getString('nama_desa') ?? ""; + final sessionNamaDusun = prefs.getString('nama_dusun') ?? ""; + + if (role == 'kader' && sessionDusunId != null) { + if (mounted) { + setState(() { + isKader = true; + selectedDesa = sessionDesaId; + selectedDusun = sessionDusunId; + currentKaderId = sessionIdUser; + desaC.text = sessionNamaDesa; + dusunC.text = sessionNamaDusun; + }); + } + } + } catch (e) { + debugPrint("Error Check Role: $e"); + } + } + + dynamic _safeJson(String body) { + try { + if (body.trim().startsWith("<")) return null; + return json.decode(body); + } catch (e) { + return null; + } + } + + Future _simpan() async { + // Reset status error email sebelum mencoba simpan + setState(() => _emailError = null); + + if (!_formKey.currentState!.validate()) return; + + if (selectedDesa == null || selectedDusun == null) { + _showMsg("Wilayah tidak terdeteksi"); + return; + } + + if (currentKaderId == null) { + _showMsg("Sesi login Kader tidak valid, silakan login ulang"); + return; + } + + setState(() => _isSaving = true); + + try { + final res = await http.post( + Uri.parse("http://ta.myhost.id/E31230549/mposyandu_api/ibu/tambah_ibu.php"), + body: { + "nik": nikC.text.trim(), + "no_kk": noKkC.text.trim(), + "nama": namaC.text.trim(), + "nama_suami": namaSuamiC.text.trim(), + "tempat_lahir": tempatLahirC.text.trim(), + "tanggal_lahir": tglC.text.trim(), + "golongan_darah": selectedGolDarah ?? "-", + "pendidikan": pendidikanC.text.trim(), + "pekerjaan": pekerjaanC.text.trim(), + "agama": selectedAgama ?? "", + "no_hp": hpC.text.trim(), + "email": emailC.text.trim(), + "password": passwordC.text.trim(), + "desa_id": selectedDesa, + "dusun_id": selectedDusun, + "alamat_detail": alamatC.text.trim(), + "kader_id": currentKaderId, + }, + ); + + final data = _safeJson(res.body); + if (data != null && data["success"] == true) { + _showMsg("Data berhasil disimpan"); + if (mounted) Navigator.pop(context, true); + } else { + String serverMsg = data?["message"] ?? "Gagal menyimpan"; + + // Logika pengecekan email terdaftar + if (serverMsg.toLowerCase().contains("email")) { + setState(() => _emailError = "Email sudah terdaftar"); + } else { + _showMsg(serverMsg); + } + } + } catch (e) { + _showMsg("Gagal terhubung ke server"); + } + + if (mounted) setState(() => _isSaving = false); + } + + void _showMsg(String msg) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(msg, style: GoogleFonts.poppins(fontSize: 12))), + ); + } + + Future _pickDate() async { + final picked = await showDatePicker( + context: context, + firstDate: DateTime(1950), + lastDate: DateTime.now(), + initialDate: DateTime(2000), + ); + if (picked != null) { + tglC.text = picked.toIso8601String().split("T").first; + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: Text("", + style: + GoogleFonts.poppins(fontSize: 14, fontWeight: FontWeight.w600)), + backgroundColor: Colors.blue, + foregroundColor: Colors.white, + ), + backgroundColor: const Color(0xfff4f6fb), + body: Center( + child: SingleChildScrollView( + padding: const EdgeInsets.all(16), + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 900), + child: Container( + padding: const EdgeInsets.all(24), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(20), + boxShadow: const [ + BoxShadow( + blurRadius: 16, + color: Colors.black12, + offset: Offset(0, 8)) + ], + ), + child: Form( + key: _formKey, + child: Column( + children: [ + Text("Tambah Data Ibu", + style: GoogleFonts.poppins( + fontSize: 18, fontWeight: FontWeight.bold)), + const SizedBox(height: 24), + Wrap( + spacing: 16, + runSpacing: 16, + children: [ + _field("NIK", nikC, + keyboard: TextInputType.number, isNik: true), + _field("No KK", noKkC, + keyboard: TextInputType.number, isKk: true), + _field("Nama Lengkap", namaC), + _field("Nama Suami", namaSuamiC), + _field("Tempat Lahir", tempatLahirC), + SizedBox( + width: 260, + child: TextFormField( + controller: tglC, + readOnly: true, + onTap: _pickDate, + style: GoogleFonts.poppins(fontSize: 12), + decoration: _decoration("Tanggal Lahir").copyWith( + suffixIcon: const Icon(Icons.calendar_today, + size: 18, color: Colors.black), + ), + validator: (v) => v!.isEmpty ? "Wajib diisi" : null, + ), + ), + SizedBox( + width: 260, + child: DropdownButtonFormField( + value: selectedGolDarah, + style: GoogleFonts.poppins( + fontSize: 12, color: Colors.black), + decoration: _decoration("Golongan Darah"), + items: golDarahList + .map((e) => + DropdownMenuItem(value: e, child: Text(e))) + .toList(), + onChanged: (v) => + setState(() => selectedGolDarah = v), + validator: (v) => + v == null ? "Wajib dipilih" : null, + ), + ), + _field("Pendidikan", pendidikanC), + _field("Pekerjaan", pekerjaanC), + SizedBox( + width: 260, + child: DropdownButtonFormField( + value: selectedAgama, + style: GoogleFonts.poppins( + fontSize: 12, color: Colors.black), + decoration: _decoration("Agama"), + items: agamaList + .map((e) => + DropdownMenuItem(value: e, child: Text(e))) + .toList(), + onChanged: (v) => setState(() => selectedAgama = v), + validator: (v) => + v == null ? "Agama wajib dipilih" : null, + ), + ), + _field("Desa", desaC, readOnly: true), + _field("Dusun", dusunC, readOnly: true), + _field("No HP", hpC, + keyboard: TextInputType.phone, isPhone: true), + _field("Email", emailC, + keyboard: TextInputType.emailAddress, + isEmail: true), + SizedBox( + width: 260, + child: TextFormField( + controller: passwordC, + obscureText: true, + readOnly: true, + style: GoogleFonts.poppins(fontSize: 12), + decoration: + _decoration("Password akan terisi otomatis"), + validator: (v) => (v == null || v.isEmpty) + ? "Password belum terisi (isi NIK dulu)" + : null, + ), + ), + _field("Alamat Detail", alamatC), + ], + ), + const SizedBox(height: 32), + SizedBox( + width: double.infinity, + height: 50, + child: OutlinedButton( + onPressed: _isSaving ? null : _simpan, + style: OutlinedButton.styleFrom( + side: const BorderSide(color: Colors.blue, width: 2), + shape: const StadiumBorder(), + ), + child: _isSaving + ? const Center( + child: SizedBox( + height: 20, + width: 20, + child: CircularProgressIndicator( + strokeWidth: 2, color: Colors.blue)), + ) + : Text("Simpan Data Ibu", + style: GoogleFonts.poppins( + fontWeight: FontWeight.bold, + color: Colors.blue)), + ), + ) + ], + ), + ), + ), + ), + ), + ), + ); + } + + Widget _field(String label, TextEditingController c, + {TextInputType keyboard = TextInputType.text, + bool isNik = false, + bool isKk = false, + bool isPhone = false, + bool isEmail = false, + bool readOnly = false}) { + return SizedBox( + width: 260, + child: TextFormField( + controller: c, + keyboardType: keyboard, + readOnly: readOnly, + onChanged: (v) { + // Menghilangkan pesan error saat user mulai mengetik ulang di kolom email + if (isEmail && _emailError != null) { + setState(() => _emailError = null); + } + }, + inputFormatters: (isNik || isKk || isPhone) + ? [FilteringTextInputFormatter.digitsOnly] + : null, + style: GoogleFonts.poppins(fontSize: 12), + decoration: _decoration(label).copyWith( + fillColor: readOnly ? Colors.grey[100] : Colors.white, + // Tampilan teks merah di bawah kolom jika error email ditemukan + errorText: isEmail ? _emailError : null, + errorStyle: GoogleFonts.poppins(color: Colors.red, fontSize: 10), + ), + validator: (v) { + if (v == null || v.isEmpty) return "$label wajib diisi"; + if ((isNik || isKk) && v.length != 16) return "Harus 16 digit"; + if (isPhone && (v.length < 10 || v.length > 13)) return "Digit 10-13"; + return null; + }, + ), + ); + } + + InputDecoration _decoration(String label) { + return InputDecoration( + filled: true, + fillColor: Colors.white, + labelText: label, + labelStyle: GoogleFonts.poppins(fontSize: 12), + border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)), + contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + ); + } +} diff --git a/lib/kader/crud_ibu_hamil/edit_ibu_hamil.dart b/lib/kader/crud_ibu_hamil/edit_ibu_hamil.dart new file mode 100644 index 0000000..28eb2ee --- /dev/null +++ b/lib/kader/crud_ibu_hamil/edit_ibu_hamil.dart @@ -0,0 +1,430 @@ +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:http/http.dart' as http; +import 'package:shared_preferences/shared_preferences.dart'; + +class EditIbuHamilPage extends StatefulWidget { + final Map data; + + const EditIbuHamilPage({super.key, required this.data}); + + @override + State createState() => _EditIbuHamilPageState(); +} + +class _EditIbuHamilPageState extends State { + final _formKey = GlobalKey(); + + String? selectedIbuId; + List listIbu = []; + + final hphtC = TextEditingController(); + final usiaC = TextEditingController(); + final hplC = TextEditingController(); + final tglPersalinanSblmC = TextEditingController(); + + final gravidaC = TextEditingController(); + final paraC = TextEditingController(); + final abortusC = TextEditingController(); + final hidupC = TextEditingController(); + + // Dropdown Data + String? selectedStatus; + final List listStatus = ['aktif', 'keguguran', 'melahirkan']; + + String? selectedPembiayaan; + final List listPembiayaan = [ + 'JKN', + 'JAMPERSAL', + 'ASURANSI KESEHATAN LAIN', + 'MANDIRI' + ]; + + bool _isSaving = false; + bool _isLoadingIbu = true; + + @override + void initState() { + super.initState(); + + // Inisialisasi Data Awal dari widget.data + hphtC.text = widget.data["hpht"] ?? ""; + hplC.text = widget.data["hpl"] ?? ""; + tglPersalinanSblmC.text = + widget.data["tanggal_persalinan_sebelumnya"] ?? ""; + gravidaC.text = widget.data["gravida"]?.toString() ?? ""; + paraC.text = widget.data["para"]?.toString() ?? ""; + abortusC.text = widget.data["abortus"]?.toString() ?? ""; + hidupC.text = widget.data["hidup"]?.toString() ?? ""; + + selectedIbuId = widget.data["ibu_id"]?.toString(); + selectedStatus = widget.data["status"]?.toString().toLowerCase(); + selectedPembiayaan = widget.data["pembiayaan"]; + + // Hitung usia kehamilan awal jika HPHT tersedia + if (hphtC.text.isNotEmpty) { + try { + DateTime hphtDate = DateTime.parse(hphtC.text); + _hitungDariHPHT(hphtDate); + } catch (e) { + debugPrint("Error parse HPHT: $e"); + } + } + + _fetchIbu(); + } + + @override + void dispose() { + hphtC.dispose(); + usiaC.dispose(); + hplC.dispose(); + tglPersalinanSblmC.dispose(); + gravidaC.dispose(); + paraC.dispose(); + abortusC.dispose(); + hidupC.dispose(); + super.dispose(); + } + + Future _fetchIbu() async { + try { + final prefs = await SharedPreferences.getInstance(); + final dynamic rawDusunId = prefs.get("dusun_id"); + final String userDusunId = rawDusunId?.toString() ?? ""; + + final url = Uri.parse( + "http://ta.myhost.id/E31230549/mposyandu_api/ibu/get_ibu.php?dusun_id=$userDusunId"); + final response = await http.get(url).timeout(const Duration(seconds: 10)); + final data = json.decode(response.body); + + if (data["success"] == true) { + if (mounted) { + setState(() { + listIbu = data["data"] ?? []; + _isLoadingIbu = false; + + bool exists = + listIbu.any((item) => item["id"].toString() == selectedIbuId); + if (!exists) { + listIbu.add({ + "id": widget.data["ibu_id"], + "nama": widget.data["nama_ibu"] ?? + widget.data["nama"] ?? + "Data Saat Ini", + "nama_suami": widget.data["nama_suami"] ?? "-" + }); + } + }); + } + } else { + if (mounted) setState(() => _isLoadingIbu = false); + } + } catch (e) { + if (mounted) setState(() => _isLoadingIbu = false); + } + } + + Future _pickDate(TextEditingController controller, + {bool updateHpl = false}) async { + final picked = await showDatePicker( + context: context, + firstDate: DateTime(2000), + lastDate: DateTime.now().add(const Duration(days: 365)), + initialDate: DateTime.tryParse(controller.text) ?? DateTime.now(), + ); + + if (picked != null) { + if (mounted) { + setState(() { + controller.text = picked.toIso8601String().split("T").first; + if (updateHpl) _hitungDariHPHT(picked); + }); + } + } + } + + void _hitungDariHPHT(DateTime hphtDate) { + final now = DateTime.now(); + final diffDays = now.difference(hphtDate).inDays; + final minggu = diffDays < 0 ? 0 : (diffDays / 7).floor(); + usiaC.text = minggu.toString(); + final hplDate = hphtDate.add(const Duration(days: 280)); + hplC.text = hplDate.toIso8601String().split("T").first; + } + + Future _update() async { + if (!_formKey.currentState!.validate()) return; + if (selectedIbuId == null) { + _showMsg("Ibu wajib dipilih"); + return; + } + if (selectedStatus == null) { + _showMsg("Status wajib dipilih"); + return; + } + + setState(() => _isSaving = true); + + try { + final url = Uri.parse( + "http://ta.myhost.id/E31230549/mposyandu_api/ibu_hamil/update_ibu_hamil.php"); + final response = await http.post(url, body: { + "id": widget.data["id"].toString(), + "ibu_id": selectedIbuId!, + "hpht": hphtC.text.trim(), + "hpl": hplC.text.trim(), + "tanggal_persalinan_sebelumnya": tglPersalinanSblmC.text.trim(), + "gravida": gravidaC.text.trim(), + "para": paraC.text.trim(), + "abortus": abortusC.text.trim(), + "hidup": hidupC.text.trim(), + "status": selectedStatus!, + "pembiayaan": selectedPembiayaan ?? "", // Boleh kosong + }); + + final data = json.decode(response.body); + + if (data["success"] == true) { + if (!mounted) return; + _showMsg("Data berhasil diupdate"); + Navigator.pop(context, true); + } else { + _showMsg(data["message"] ?? "Gagal update"); + } + } catch (e) { + _showMsg("Terjadi kesalahan koneksi: $e"); + } + if (mounted) setState(() => _isSaving = false); + } + + void _showMsg(String msg) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(msg, style: GoogleFonts.poppins(fontSize: 12))), + ); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + elevation: 0, + backgroundColor: Colors.blue, + foregroundColor: Colors.white, + title: Text("", + style: + GoogleFonts.poppins(fontSize: 14, fontWeight: FontWeight.w600)), + ), + backgroundColor: const Color(0xfff4f6fb), + body: Center( + child: SingleChildScrollView( + padding: const EdgeInsets.all(16), + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 420), + child: Container( + padding: const EdgeInsets.all(24), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(20), + boxShadow: const [ + BoxShadow( + blurRadius: 16, + color: Colors.black12, + offset: Offset(0, 8)) + ], + ), + child: Form( + key: _formKey, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Center( + child: Text("Edit Data Ibu Hamil", + style: GoogleFonts.poppins( + fontSize: 18, fontWeight: FontWeight.bold)), + ), + const SizedBox(height: 24), + + _isLoadingIbu + ? const Center(child: CircularProgressIndicator()) + : DropdownButtonFormField( + isExpanded: true, + value: selectedIbuId, + style: GoogleFonts.poppins( + fontSize: 12, color: Colors.black), + hint: Text("Pilih Ibu", + style: GoogleFonts.poppins(fontSize: 12)), + decoration: _decoration("Pilih Ibu"), + items: + listIbu.map>((item) { + return DropdownMenuItem( + value: item["id"].toString(), + child: Text( + "${item["nama"]} (${item["nama_suami"] ?? '-'})", + overflow: TextOverflow.ellipsis, + style: GoogleFonts.poppins(fontSize: 12)), + ); + }).toList(), + onChanged: (value) => + setState(() => selectedIbuId = value), + validator: (v) => + v == null ? "Ibu wajib dipilih" : null, + ), + const SizedBox(height: 16), + + TextFormField( + controller: hphtC, + readOnly: true, + onTap: () => _pickDate(hphtC, updateHpl: true), + style: GoogleFonts.poppins(fontSize: 12), + decoration: + _decoration("HPHT (Hari Pertama Haid Terakhir)") + .copyWith( + suffixIcon: const Icon(Icons.calendar_today, + size: 18, color: Colors.black), + ), + validator: (v) => + v == null || v.isEmpty ? "HPHT wajib diisi" : null, + ), + const SizedBox(height: 16), + + TextFormField( + controller: usiaC, + readOnly: true, + style: GoogleFonts.poppins(fontSize: 12), + decoration: _decoration("Usia Kehamilan (Minggu)"), + ), + const SizedBox(height: 16), + + TextFormField( + controller: hplC, + readOnly: true, + style: GoogleFonts.poppins(fontSize: 12), + decoration: _decoration("HPL (Hari Perkiraan Lahir)"), + ), + const SizedBox(height: 16), + + TextFormField( + controller: tglPersalinanSblmC, + readOnly: true, + onTap: () => _pickDate(tglPersalinanSblmC), + style: GoogleFonts.poppins(fontSize: 12), + decoration: _decoration( + "Tanggal Persalinan Sebelumnya (Opsional)") + .copyWith( + suffixIcon: const Icon(Icons.history, + size: 18, color: Colors.black), + ), + ), + const SizedBox(height: 16), + + _input("Gravida (G)", gravidaC, + keyboard: TextInputType.number), + const SizedBox(height: 16), + _input("Para (P)", paraC, keyboard: TextInputType.number), + const SizedBox(height: 16), + _input("Abortus (A)", abortusC, + keyboard: TextInputType.number), + const SizedBox(height: 16), + _input("Hidup", hidupC, keyboard: TextInputType.number), + const SizedBox(height: 16), + + // DROPDOWN PEMBIAYAAN (Opsional) + DropdownButtonFormField( + isExpanded: true, + value: (selectedPembiayaan == null || + selectedPembiayaan!.isEmpty) + ? null + : selectedPembiayaan, + style: GoogleFonts.poppins( + fontSize: 12, color: Colors.black), + decoration: _decoration("Pembiayaan"), + hint: Text("Pilih Pembiayaan (Opsional)", + style: GoogleFonts.poppins(fontSize: 12)), + items: listPembiayaan + .map((e) => DropdownMenuItem( + value: e, + child: Text(e, + style: GoogleFonts.poppins(fontSize: 12)))) + .toList(), + onChanged: (v) => setState(() => selectedPembiayaan = v), + ), + const SizedBox(height: 16), + + // DROPDOWN STATUS + DropdownButtonFormField( + value: selectedStatus, + style: GoogleFonts.poppins( + fontSize: 12, color: Colors.black), + decoration: _decoration("Status"), + items: listStatus + .map((e) => DropdownMenuItem( + value: e, + child: Text(e.toUpperCase(), + style: GoogleFonts.poppins(fontSize: 12)))) + .toList(), + onChanged: (v) => setState(() => selectedStatus = v), + validator: (v) => v == null ? "Wajib dipilih" : null, + ), + const SizedBox(height: 28), + + SizedBox( + height: 50, + child: OutlinedButton( + onPressed: _isSaving ? null : _update, + style: OutlinedButton.styleFrom( + side: const BorderSide( + color: Colors.blueAccent, width: 2), + shape: const StadiumBorder(), + ), + child: _isSaving + ? const SizedBox( + height: 20, + width: 20, + child: + CircularProgressIndicator(strokeWidth: 2)) + : Text("Simpan Perubahan", + style: GoogleFonts.poppins( + fontWeight: FontWeight.bold, + fontSize: 14, + color: Colors.blueAccent)), + ), + ), + ], + ), + ), + ), + ), + ), + ), + ); + } + + Widget _input(String label, TextEditingController c, + {TextInputType keyboard = TextInputType.text}) { + return TextFormField( + controller: c, + keyboardType: keyboard, + style: GoogleFonts.poppins(fontSize: 12), + inputFormatters: keyboard == TextInputType.number + ? [FilteringTextInputFormatter.digitsOnly] + : null, + decoration: _decoration(label), + validator: (v) => v == null || v.isEmpty ? "$label wajib diisi" : null, + ); + } + + InputDecoration _decoration(String label) { + return InputDecoration( + filled: true, + fillColor: Colors.white, + labelText: label, + labelStyle: GoogleFonts.poppins(fontSize: 12), + border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)), + contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + ); + } +} diff --git a/lib/kader/crud_ibu_hamil/tambah_ibu_hamil.dart b/lib/kader/crud_ibu_hamil/tambah_ibu_hamil.dart new file mode 100644 index 0000000..184104e --- /dev/null +++ b/lib/kader/crud_ibu_hamil/tambah_ibu_hamil.dart @@ -0,0 +1,381 @@ +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:http/http.dart' as http; +import 'package:shared_preferences/shared_preferences.dart'; + +class TambahIbuHamilPage extends StatefulWidget { + const TambahIbuHamilPage({super.key}); + + @override + State createState() => _TambahIbuHamilPageState(); +} + +class _TambahIbuHamilPageState extends State { + final _formKey = GlobalKey(); + + String? selectedIbuId; + List listIbu = []; + + final hphtC = TextEditingController(); + final usiaC = TextEditingController(); + final hplC = TextEditingController(); + final tglPersalinanSblmC = TextEditingController(); + + final gravidaC = TextEditingController(); + final paraC = TextEditingController(); + final abortusC = TextEditingController(); + final hidupC = TextEditingController(); + + // Dropdown Values + String selectedStatus = "aktif"; + final List listStatus = ['aktif', 'keguguran', 'melahirkan']; + + // Diubah menjadi null agar memicu tampilan Hint + String? selectedPembiayaan; + final List listPembiayaan = [ + 'JKN', + 'JAMPERSAL', + 'ASURANSI KESEHATAN LAIN', + 'MANDIRI' + ]; + + bool _isSaving = false; + bool _isLoadingIbu = true; + + @override + void initState() { + super.initState(); + _fetchIbu(); + } + + @override + void dispose() { + hphtC.dispose(); + usiaC.dispose(); + hplC.dispose(); + tglPersalinanSblmC.dispose(); + gravidaC.dispose(); + paraC.dispose(); + abortusC.dispose(); + hidupC.dispose(); + super.dispose(); + } + + void _hitungDariHPHT(DateTime hphtDate) { + final now = DateTime.now(); + final diffDays = now.difference(hphtDate).inDays; + final minggu = diffDays < 0 ? 0 : (diffDays / 7).floor(); + usiaC.text = minggu.toString(); + final hplDate = hphtDate.add(const Duration(days: 280)); + hplC.text = hplDate.toIso8601String().split("T").first; + } + + Future _fetchIbu() async { + try { + final prefs = await SharedPreferences.getInstance(); + final dynamic rawDusunId = prefs.get("dusun_id"); + final String userDusunId = rawDusunId?.toString() ?? ""; + + final url = Uri.parse( + "http://ta.myhost.id/E31230549/mposyandu_api/ibu/get_ibu.php?dusun_id=$userDusunId"); + + final response = await http.get(url); + final data = json.decode(response.body); + + if (data["success"] == true) { + setState(() { + listIbu = data["data"] ?? []; + _isLoadingIbu = false; + }); + } else { + if (mounted) setState(() => _isLoadingIbu = false); + } + } catch (e) { + if (mounted) setState(() => _isLoadingIbu = false); + } + } + + Future _simpan() async { + if (!_formKey.currentState!.validate()) return; + + if (selectedIbuId == null) { + _showSnackBar("Ibu wajib dipilih"); + return; + } + + setState(() => _isSaving = true); + try { + final url = Uri.parse( + "http://ta.myhost.id/E31230549/mposyandu_api/ibu_hamil/tambah_ibu_hamil.php"); + + // Data dikirim dengan pengaman ?? "" agar jika kosong tetap terkirim sebagai string kosong + final response = await http.post(url, body: { + "ibu_id": selectedIbuId!, + "hpht": hphtC.text.trim(), + "hpl": hplC.text.trim(), + "tanggal_persalinan_sebelumnya": tglPersalinanSblmC.text.trim(), + "gravida": gravidaC.text.trim(), + "para": paraC.text.trim(), + "abortus": abortusC.text.trim(), + "hidup": hidupC.text.trim(), + "status": selectedStatus, + "pembiayaan": selectedPembiayaan ?? "", + }); + + final data = json.decode(response.body); + if (data["success"] == true) { + _showSnackBar("Data berhasil disimpan"); + if (mounted) Navigator.pop(context, true); + } else { + _showSnackBar(data["message"] ?? "Gagal menyimpan"); + } + } catch (e) { + _showSnackBar("Gagal: $e"); + } finally { + if (mounted) setState(() => _isSaving = false); + } + } + + void _showSnackBar(String msg) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(msg, style: GoogleFonts.poppins(fontSize: 12))), + ); + } + + Future _pickHPHT() async { + final picked = await showDatePicker( + context: context, + firstDate: DateTime(2000), + lastDate: DateTime.now(), + initialDate: DateTime.now(), + ); + if (picked != null) { + hphtC.text = picked.toIso8601String().split("T").first; + _hitungDariHPHT(picked); + } + } + + Future _pickTanggalPersalinan() async { + final picked = await showDatePicker( + context: context, + firstDate: DateTime(1990), + lastDate: DateTime.now(), + initialDate: DateTime.now(), + ); + if (picked != null) { + tglPersalinanSblmC.text = picked.toIso8601String().split("T").first; + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + backgroundColor: Colors.blue, + foregroundColor: Colors.white, + title: Text( + "", + style: GoogleFonts.poppins(fontSize: 14, fontWeight: FontWeight.w600), + ), + ), + backgroundColor: const Color(0xfff4f6fb), + body: Center( + child: SingleChildScrollView( + padding: const EdgeInsets.all(16), + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 420), + child: Container( + padding: const EdgeInsets.all(24), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(20), + boxShadow: const [ + BoxShadow( + blurRadius: 16, + color: Colors.black12, + offset: Offset(0, 8)) + ], + ), + child: Form( + key: _formKey, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Center( + child: Text( + "Tambah Data Ibu Hamil", + style: GoogleFonts.poppins( + fontSize: 18, fontWeight: FontWeight.w700), + ), + ), + const SizedBox(height: 24), + _isLoadingIbu + ? const Center(child: CircularProgressIndicator()) + : DropdownButtonFormField( + isExpanded: true, + value: selectedIbuId, + hint: Text("Pilih Ibu", + style: GoogleFonts.poppins(fontSize: 12)), + style: GoogleFonts.poppins( + fontSize: 12, color: Colors.black), + decoration: _decoration("Pilih Ibu"), + items: + listIbu.map>((item) { + return DropdownMenuItem( + value: item["id"].toString(), + child: Text( + "${item["nama"]} (${item["nama_suami"] ?? '_'})", + overflow: TextOverflow.ellipsis, + style: GoogleFonts.poppins(fontSize: 12)), + ); + }).toList(), + onChanged: (v) => setState(() => selectedIbuId = v), + validator: (v) => + v == null ? "Ibu wajib dipilih" : null, + ), + const SizedBox(height: 16), + TextFormField( + controller: hphtC, + readOnly: true, + onTap: _pickHPHT, + style: GoogleFonts.poppins(fontSize: 12), + decoration: _decoration("HPHT").copyWith( + suffixIcon: const Icon(Icons.calendar_today, + size: 18, color: Colors.black), + ), + validator: (v) => v!.isEmpty ? "HPHT wajib diisi" : null, + ), + const SizedBox(height: 16), + TextFormField( + controller: usiaC, + readOnly: true, + style: GoogleFonts.poppins(fontSize: 12), + decoration: _decoration("Usia Kehamilan (Minggu)"), + ), + const SizedBox(height: 16), + TextFormField( + controller: hplC, + readOnly: true, + style: GoogleFonts.poppins(fontSize: 12), + decoration: _decoration("HPL (Perkiraan Lahir)"), + ), + const SizedBox(height: 16), + // Tanggal Persalinan Sebelumnya (Opsional) + TextFormField( + controller: tglPersalinanSblmC, + readOnly: true, + onTap: _pickTanggalPersalinan, + style: GoogleFonts.poppins(fontSize: 12), + decoration: _decoration( + "Tanggal Persalinan Sebelumnya (Opsional)") + .copyWith( + suffixIcon: const Icon(Icons.calendar_today, + size: 18, color: Colors.black), + ), + ), + const SizedBox(height: 16), + _input("Gravida (G)", gravidaC, + keyboard: TextInputType.number), + const SizedBox(height: 16), + _input("Para (P)", paraC, keyboard: TextInputType.number), + const SizedBox(height: 16), + _input("Abortus (A)", abortusC, + keyboard: TextInputType.number), + const SizedBox(height: 16), + _input("Hidup", hidupC, keyboard: TextInputType.number), + const SizedBox(height: 16), + + // DROPDOWN PEMBIAYAAN (Opsional) + DropdownButtonFormField( + isExpanded: true, + value: selectedPembiayaan, + hint: Text("Pilih Pembiayaan (Opsional)", + style: GoogleFonts.poppins(fontSize: 12)), + decoration: _decoration("Pembiayaan"), + style: GoogleFonts.poppins( + fontSize: 12, color: Colors.black), + items: listPembiayaan.map((val) { + return DropdownMenuItem( + value: val, + child: Text(val, + style: GoogleFonts.poppins(fontSize: 12)), + ); + }).toList(), + onChanged: (v) => setState(() => selectedPembiayaan = v), + // Validator dihapus agar boleh kosong + ), + + const SizedBox(height: 16), + // DROPDOWN STATUS + DropdownButtonFormField( + value: selectedStatus, + decoration: _decoration("Status"), + style: GoogleFonts.poppins( + fontSize: 12, color: Colors.black), + items: listStatus.map((val) { + return DropdownMenuItem( + value: val, + child: Text(val.toUpperCase(), + style: GoogleFonts.poppins(fontSize: 12)), + ); + }).toList(), + onChanged: (v) => setState(() => selectedStatus = v!), + ), + const SizedBox(height: 28), + SizedBox( + width: double.infinity, + height: 50, + child: OutlinedButton( + onPressed: _isSaving ? null : _simpan, + style: OutlinedButton.styleFrom( + side: const BorderSide( + color: Colors.blueAccent, width: 2), + shape: const StadiumBorder(), + ), + child: _isSaving + ? const SizedBox( + height: 20, + width: 20, + child: + CircularProgressIndicator(strokeWidth: 2)) + : Text("Simpan Data Ibu Hamil", + style: GoogleFonts.poppins( + fontWeight: FontWeight.bold, + fontSize: 14, + color: Colors.blueAccent)), + ), + ) + ], + ), + ), + ), + ), + ), + ), + ); + } + + Widget _input(String label, TextEditingController c, + {TextInputType keyboard = TextInputType.text}) { + return TextFormField( + controller: c, + keyboardType: keyboard, + style: GoogleFonts.poppins(fontSize: 12), + decoration: _decoration(label), + validator: (v) => v!.isEmpty ? "$label wajib diisi" : null, + ); + } + + InputDecoration _decoration(String label) { + return InputDecoration( + filled: true, + fillColor: Colors.white, + labelText: label, + labelStyle: GoogleFonts.poppins(fontSize: 12), + errorStyle: GoogleFonts.poppins(fontSize: 10), + contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)), + ); + } +} diff --git a/lib/kader/crud_kehadiran/riwayat_kehadiran.dart b/lib/kader/crud_kehadiran/riwayat_kehadiran.dart new file mode 100644 index 0000000..cdf9531 --- /dev/null +++ b/lib/kader/crud_kehadiran/riwayat_kehadiran.dart @@ -0,0 +1,368 @@ +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:http/http.dart' as http; +import 'package:intl/intl.dart'; +import 'package:intl/date_symbol_data_local.dart'; + +class RiwayatKehadiranPage extends StatefulWidget { + final String balitaId; + final String namaBalita; + + const RiwayatKehadiranPage({ + super.key, + required this.balitaId, + required this.namaBalita, + }); + + @override + State createState() => _RiwayatKehadiranPageState(); +} + +class _RiwayatKehadiranPageState extends State { + List _riwayatOriginal = []; + List _riwayatFiltered = []; + bool _isLoading = true; + + final TextEditingController _searchController = TextEditingController(); + + /// ================= PAGINATION ================= + int _currentPage = 0; + final int _rowsPerPage = 5; + + List get _paginatedData { + if (_riwayatFiltered.isEmpty) return []; + final start = _currentPage * _rowsPerPage; + final end = start + _rowsPerPage; + if (start >= _riwayatFiltered.length) return []; + return _riwayatFiltered.sublist( + start, + end > _riwayatFiltered.length ? _riwayatFiltered.length : end, + ); + } + + @override + void initState() { + super.initState(); + initializeDateFormatting('id_ID', null); + _fetchRiwayat(); + } + + @override + void dispose() { + _searchController.dispose(); + super.dispose(); + } + + String _formatTanggal(String? tanggal) { + if (tanggal == null || tanggal == "" || tanggal == "0000-00-00") { + return "-"; + } + try { + DateTime dt = DateTime.parse(tanggal); + return DateFormat('d MMMM yyyy', 'id_ID').format(dt); + } catch (e) { + return tanggal; + } + } + + void _filterData(String query) { + setState(() { + if (query.isEmpty) { + _riwayatFiltered = _riwayatOriginal; + } else { + _riwayatFiltered = _riwayatOriginal.where((item) { + String tglFormatted = + _formatTanggal(item["tanggal_posyandu"]).toLowerCase(); + String tglDatabase = + (item["tanggal_posyandu"] ?? "").toString().toLowerCase(); + return tglFormatted.contains(query.toLowerCase()) || + tglDatabase.contains(query.toLowerCase()); + }).toList(); + } + _currentPage = 0; + }); + } + + Future _fetchRiwayat() async { + try { + final response = await http.get( + Uri.parse( + "http://ta.myhost.id/E31230549/mposyandu_api/kehadiran/get_riwayat_balita.php?balita_id=${widget.balitaId}"), + ); + if (response.statusCode == 200) { + final res = json.decode(response.body); + if (res["success"] == true) { + setState(() { + _riwayatOriginal = res["data"]; + _riwayatFiltered = res["data"]; + }); + } + } + } catch (e) { + debugPrint("Error Fetch Riwayat: ${e.toString()}"); + } finally { + if (mounted) setState(() => _isLoading = false); + } + } + + Future _hapusData(String id) async { + try { + final response = await http.post( + Uri.parse( + "http://ta.myhost.id/E31230549/mposyandu_api/kehadiran/hapus_kehadiran.php"), + body: {"id": id}, + ); + final res = json.decode(response.body); + if (res["success"] == true) { + _fetchRiwayat(); + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text("Data berhasil dihapus")), + ); + } + } catch (e) { + debugPrint("Error Hapus: ${e.toString()}"); + } + } + + @override + Widget build(BuildContext context) { + final totalPages = _riwayatFiltered.isEmpty + ? 1 + : (_riwayatFiltered.length / _rowsPerPage).ceil(); + + return Scaffold( + backgroundColor: const Color(0xfff4f6fb), + appBar: AppBar( + backgroundColor: Colors.blueAccent, + foregroundColor: Colors.white, + elevation: 0, + centerTitle: true, + leading: IconButton( + icon: const Icon(Icons.arrow_back), + onPressed: () => Navigator.pop(context, true), + ), + ), + body: _isLoading + ? const Center(child: CircularProgressIndicator()) + : Column( + children: [ + const SizedBox(height: 14), + Text( + "Riwayat Kehadiran", + style: GoogleFonts.poppins( + fontSize: 18, fontWeight: FontWeight.bold), + ), + const SizedBox(height: 12), + + /// SEARCH + Padding( + padding: const EdgeInsets.symmetric(horizontal: 20), + child: TextField( + controller: _searchController, + onChanged: _filterData, + style: GoogleFonts.poppins(fontSize: 12), + decoration: InputDecoration( + hintText: "Cari tanggal...", + hintStyle: GoogleFonts.poppins(fontSize: 12), + prefixIcon: const Icon(Icons.search, size: 18), + filled: true, + fillColor: Colors.white, + contentPadding: const EdgeInsets.symmetric(vertical: 10), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10)), + ), + ), + ), + const SizedBox(height: 15), + + Expanded( + child: _riwayatFiltered.isEmpty + ? Center( + child: Text("Data tidak ditemukan", + style: GoogleFonts.poppins( + fontSize: 12, color: Colors.grey))) + : ListView.builder( + padding: const EdgeInsets.symmetric(horizontal: 16), + itemCount: _paginatedData.length, + itemBuilder: (context, index) { + final item = _paginatedData[index]; + return Card( + elevation: 2, + color: Colors.white, // Warna card putih + margin: const EdgeInsets.only(bottom: 14), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12)), + child: Column( + children: [ + Container( + width: double.infinity, + padding: const EdgeInsets.all(12), + decoration: const BoxDecoration( + color: Colors.blueAccent, + borderRadius: BorderRadius.vertical( + top: Radius.circular(12)), + ), + child: Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + Text(widget.namaBalita, + style: GoogleFonts.poppins( + color: Colors.white, + fontSize: 12, + fontWeight: FontWeight.bold)), + Text( + _formatTanggal( + item["tanggal_posyandu"]), + style: GoogleFonts.poppins( + color: Colors.white, + fontSize: 12)), + ], + ), + ), + Padding( + padding: const EdgeInsets.all(12), + child: Column( + children: [ + _infoRowAligned("Status Kehadiran", + item["status_hadir"] ?? "-"), + const SizedBox(height: 4), + _infoRowAligned("Catatan", + item["keterangan"] ?? "-"), + const Divider(), + const SizedBox(height: 4), + Align( + alignment: Alignment.centerRight, + child: SizedBox( + width: 110, + child: OutlinedButton.icon( + onPressed: () => + _showDeleteDialog( + item["id"].toString()), + icon: const Icon( + Icons.delete_outline, + size: 14, + color: Colors.red), + style: OutlinedButton.styleFrom( + side: const BorderSide( + color: Colors.red, + width: 1.5), + shape: const StadiumBorder(), + padding: + const EdgeInsets.symmetric( + vertical: 8), + ), + label: Text( + "Hapus", + style: GoogleFonts.poppins( + fontSize: 12, + color: Colors.red, + fontWeight: + FontWeight.bold), + ), + ), + ), + ) + ], + ), + ) + ], + ), + ); + }, + ), + ), + + /// PAGINATION + Container( + width: double.infinity, + padding: + const EdgeInsets.symmetric(vertical: 10, horizontal: 20), + decoration: BoxDecoration( + color: Colors.white, + border: + Border(top: BorderSide(color: Colors.grey.shade200))), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text("Halaman ${_currentPage + 1} dari $totalPages", + style: GoogleFonts.poppins( + fontSize: 12, fontWeight: FontWeight.w500)), + Row( + children: [ + IconButton( + icon: const Icon(Icons.chevron_left), + onPressed: _currentPage == 0 + ? null + : () => setState(() => _currentPage--), + ), + IconButton( + icon: const Icon(Icons.chevron_right), + onPressed: _currentPage >= totalPages - 1 + ? null + : () => setState(() => _currentPage++), + ), + ], + ), + ], + ), + ), + ], + ), + ); + } + + Widget _infoRowAligned(String label, String value) { + return Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: 120, + child: Text(label, + style: GoogleFonts.poppins( + fontSize: 12, fontWeight: FontWeight.w500))), + const Text(" : ", style: TextStyle(fontSize: 12)), + Expanded( + child: Text(value, + style: GoogleFonts.poppins( + fontSize: 12, fontWeight: FontWeight.w600))), + ], + ); + } + + void _showDeleteDialog(String id) { + showDialog( + context: context, + builder: (context) => AlertDialog( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)), + title: Text("Konfirmasi", + style: + GoogleFonts.poppins(fontWeight: FontWeight.bold, fontSize: 12)), + content: Text("Data riwayat ini akan dihapus permanen.", + style: GoogleFonts.poppins(fontSize: 12)), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: Text("Batal", + style: + GoogleFonts.poppins(color: Colors.grey, fontSize: 12))), + OutlinedButton( + onPressed: () { + Navigator.pop(context); + _hapusData(id); + }, + style: OutlinedButton.styleFrom( + side: const BorderSide(color: Colors.red), + shape: const StadiumBorder()), + child: Text("Hapus", + style: GoogleFonts.poppins( + color: Colors.red, + fontWeight: FontWeight.bold, + fontSize: 12)), + ), + ], + ), + ); + } +} diff --git a/lib/kader/crud_pemeriksaan/edit_pemeriksaan_balita.dart b/lib/kader/crud_pemeriksaan/edit_pemeriksaan_balita.dart new file mode 100644 index 0000000..b194257 --- /dev/null +++ b/lib/kader/crud_pemeriksaan/edit_pemeriksaan_balita.dart @@ -0,0 +1,385 @@ +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:http/http.dart' as http; +import 'package:intl/intl.dart'; + +class EditPemeriksaanBalitaPage extends StatefulWidget { + final Map data; + + const EditPemeriksaanBalitaPage({ + super.key, + required this.data, + }); + + @override + State createState() => + _EditPemeriksaanBalitaPageState(); +} + +class _EditPemeriksaanBalitaPageState extends State { + final _formKey = GlobalKey(); + + final bbController = TextEditingController(); + final tbController = TextEditingController(); + final lkController = TextEditingController(); + final catatanController = TextEditingController(); + final tanggalController = TextEditingController(); + + String? vitaminA; + String? pmt; + + bool _isSaving = false; + DateTime selectedDate = DateTime.now(); + + // Variabel untuk Imunisasi + List imunisasiList = []; + Map selectedImunisasi = {}; + bool loadingImunisasi = true; + + @override + void initState() { + super.initState(); + + // Load data awal dari widget.data + String tglStr = widget.data["tanggal_pemeriksaan"] ?? ""; + if (tglStr.isNotEmpty) { + selectedDate = DateTime.tryParse(tglStr) ?? DateTime.now(); + } + tanggalController.text = DateFormat('dd-MM-yyyy').format(selectedDate); + + bbController.text = widget.data["bb"]?.toString() ?? ""; + tbController.text = widget.data["tb"]?.toString() ?? ""; + lkController.text = widget.data["lk"]?.toString() ?? ""; + catatanController.text = widget.data["catatan"] ?? ""; + + vitaminA = widget.data["vitamin_a"]; + pmt = widget.data["pmt"]; + + // Ambil data imunisasi + ambilImunisasiOtomatis(); + } + + Future ambilImunisasiOtomatis() async { + try { + final idBalita = widget.data["id_balita"]?.toString() ?? "0"; + final response = await http.get( + Uri.parse( + "http://ta.myhost.id/E31230549/mposyandu_api/pemeriksaan_balita/get_imunisasi.php?id_balita=$idBalita"), + ); + + if (response.statusCode == 200) { + final data = json.decode(response.body); + if (data["success"] == true) { + imunisasiList = data["imunisasi"]; + Map tempSelected = {}; + for (var item in imunisasiList) { + int id = int.parse(item["id"].toString()); + tempSelected[id] = (item["checked"] == true || + item["checked"] == 1 || + item["checked"] == "true" || + item["checked"] == "1"); + } + setState(() { + selectedImunisasi = tempSelected; + loadingImunisasi = false; + }); + } + } + } catch (e) { + if (mounted) setState(() => loadingImunisasi = false); + debugPrint("Error loading imunisasi: $e"); + } + } + + Future _pickDate() async { + final picked = await showDatePicker( + context: context, + initialDate: selectedDate, + firstDate: DateTime(2000), + lastDate: DateTime(2100), + ); + + if (picked != null) { + setState(() { + selectedDate = picked; + tanggalController.text = DateFormat('dd-MM-yyyy').format(picked); + }); + } + } + + Future _update() async { + if (!_formKey.currentState!.validate()) return; + + setState(() => _isSaving = true); + + try { + final url = Uri.parse( + "http://ta.myhost.id/E31230549/mposyandu_api/pemeriksaan_balita/edit_pemeriksaan_balita.php"); + + // Format tanggal sesuai kebutuhan MySQL (YYYY-MM-DD) + String formatTanggalDb = DateFormat('yyyy-MM-dd').format(selectedDate); + + // Gabungkan ID imunisasi yang dicentang menjadi string (contoh: "1,2,5") + String imunisasiDipilih = selectedImunisasi.entries + .where((e) => e.value == true) + .map((e) => e.key.toString()) + .join(","); + + // Kirim data menggunakan Map agar kompatibel dengan http.post body + final response = await http.post(url, body: { + "id_pemeriksaan": widget.data["id_pemeriksaan"].toString(), + "tanggal_pemeriksaan": formatTanggalDb, + "bb": bbController.text + .replaceAll(',', '.') + .trim(), // Bersihkan input desimal + "tb": tbController.text.replaceAll(',', '.').trim(), + "lk": lkController.text.replaceAll(',', '.').trim(), + "vitamin_a": vitaminA ?? "", + "pmt": pmt ?? "", + "catatan": catatanController.text.trim(), + "imunisasi": imunisasiDipilih + }); + + final res = json.decode(response.body); + + if (res["success"] == true) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text("Data berhasil diperbarui"), + backgroundColor: Colors.green, + ), + ); + Navigator.pop(context, + true); // Kembali dengan nilai true untuk refresh data di halaman sebelumnya + } else { + throw res["message"] ?? "Gagal mengupdate data"; + } + } catch (e) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text("Gagal: $e"), + backgroundColor: Colors.red, + ), + ); + } + } finally { + if (mounted) setState(() => _isSaving = false); + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + backgroundColor: Colors.blue, + foregroundColor: Colors.white, + elevation: 0, + title: const Text(""), // Judul App Bar Kosong + ), + backgroundColor: const Color(0xfff4f6fb), + body: Center( + child: SingleChildScrollView( + padding: const EdgeInsets.all(16), + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 420), + child: Container( + padding: const EdgeInsets.all(24), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(20), + boxShadow: const [ + BoxShadow( + blurRadius: 16, + color: Colors.black12, + offset: Offset(0, 8)) + ], + ), + child: Form( + key: _formKey, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Judul di pindahkan ke sini dan dibuat ke tengah + Center( + child: Text( + "Edit Pemeriksaan Balita", + style: GoogleFonts.poppins( + fontSize: 18, + fontWeight: FontWeight.bold, + ), + ), + ), + const SizedBox(height: 24), + TextFormField( + readOnly: true, + onTap: _pickDate, + controller: tanggalController, + style: GoogleFonts.poppins(fontSize: 12), + decoration: _decoration("Tanggal Pemeriksaan").copyWith( + suffixIcon: const Icon(Icons.calendar_today, size: 16), + ), + validator: (v) => + v == null || v.isEmpty ? "Wajib diisi" : null, + ), + const SizedBox(height: 16), + _inputNumber(bbController, "Berat Badan (kg)"), + const SizedBox(height: 16), + _inputNumber(tbController, "Tinggi Badan (cm)"), + const SizedBox(height: 16), + _inputNumber(lkController, "Lingkar Kepala (cm)"), + const SizedBox(height: 20), + Text("Imunisasi Sesuai Usia", + style: GoogleFonts.poppins( + fontSize: 13, fontWeight: FontWeight.w600)), + const SizedBox(height: 8), + _buildCheckboxImunisasi(), + const SizedBox(height: 16), + _dropdown( + label: "Vitamin A", + hint: "Pilih Status", + items: const ["Diberikan", "Belum"], + value: vitaminA, + onChanged: (v) => setState(() => vitaminA = v), + ), + const SizedBox(height: 16), + _dropdown( + label: "PMT", + hint: "Pilih Status", + items: const ["Diberikan", "Belum"], + value: pmt, + onChanged: (v) => setState(() => pmt = v), + ), + const SizedBox(height: 16), + TextFormField( + controller: catatanController, + maxLines: 3, + style: GoogleFonts.poppins(fontSize: 12), + decoration: _decoration("Catatan (Opsional)"), + ), + const SizedBox(height: 28), + SizedBox( + width: double.infinity, + height: 50, + child: ElevatedButton( + onPressed: _isSaving ? null : _update, + style: ElevatedButton.styleFrom( + backgroundColor: Colors.blue, + foregroundColor: Colors.white, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + ), + elevation: 2, + ), + child: _isSaving + ? const SizedBox( + width: 20, + height: 20, + child: CircularProgressIndicator( + color: Colors.white, strokeWidth: 2)) + : Text("Simpan Perubahan", + style: GoogleFonts.poppins( + fontWeight: FontWeight.bold)), + ), + ), + ], + ), + ), + ), + ), + ), + ), + ); + } + + Widget _buildCheckboxImunisasi() { + if (loadingImunisasi) { + return const Padding( + padding: EdgeInsets.symmetric(vertical: 10), + child: Center(child: CircularProgressIndicator(strokeWidth: 2)), + ); + } + if (imunisasiList.isEmpty) { + return Text("Tidak ada daftar imunisasi", + style: GoogleFonts.poppins(fontSize: 12, color: Colors.grey)); + } + return Column( + children: imunisasiList.map((item) { + final int id = int.parse(item["id"].toString()); + + return CheckboxListTile( + value: selectedImunisasi[id] ?? false, + onChanged: (bool? value) { + setState(() { + selectedImunisasi[id] = value ?? false; + }); + }, + title: Text(item["nama_imunisasi"], + style: GoogleFonts.poppins(fontSize: 12)), + controlAffinity: ListTileControlAffinity.leading, + contentPadding: EdgeInsets.zero, + dense: true, + activeColor: Colors.blue, + ); + }).toList(), + ); + } + + Widget _inputNumber(TextEditingController controller, String label) { + return TextFormField( + controller: controller, + keyboardType: const TextInputType.numberWithOptions(decimal: true), + style: GoogleFonts.poppins(fontSize: 12), + decoration: _decoration("$label (Opsional)"), + ); + } + + Widget _dropdown({ + required String label, + required String hint, + required List items, + required String? value, + required Function(String?) onChanged, + }) { + return DropdownButtonFormField( + value: (value == null || value.isEmpty) ? null : value, + hint: Text(hint, style: GoogleFonts.poppins(fontSize: 12)), + style: GoogleFonts.poppins(fontSize: 12, color: Colors.black), + items: + items.map((e) => DropdownMenuItem(value: e, child: Text(e))).toList(), + onChanged: onChanged, + decoration: _decoration(label), + ); + } + + InputDecoration _decoration(String label) { + return InputDecoration( + filled: true, + fillColor: Colors.white, + labelText: label, + labelStyle: GoogleFonts.poppins(fontSize: 12), + border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: const BorderSide(color: Colors.black12), + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: const BorderSide(color: Colors.blue, width: 2), + ), + contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + ); + } + + @override + void dispose() { + bbController.dispose(); + tbController.dispose(); + lkController.dispose(); + catatanController.dispose(); + tanggalController.dispose(); + super.dispose(); + } +} diff --git a/lib/kader/crud_pemeriksaan/riwayat_pemeriksaan_balita.dart b/lib/kader/crud_pemeriksaan/riwayat_pemeriksaan_balita.dart new file mode 100644 index 0000000..34b4f2a --- /dev/null +++ b/lib/kader/crud_pemeriksaan/riwayat_pemeriksaan_balita.dart @@ -0,0 +1,565 @@ +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:http/http.dart' as http; +import 'dart:convert'; +import 'package:shared_preferences/shared_preferences.dart'; + +import '/../pages/login_page.dart'; +import 'edit_pemeriksaan_balita.dart'; + +class RiwayatPemeriksaanBalitaPage extends StatefulWidget { + final int idBalita; + + const RiwayatPemeriksaanBalitaPage({ + super.key, + required this.idBalita, + }); + + @override + State createState() => + _RiwayatPemeriksaanBalitaPageState(); +} + +class _RiwayatPemeriksaanBalitaPageState + extends State { + List> _data = []; + List> _allData = []; + + bool _loading = true; + bool _checkingLogin = true; + + int _currentPage = 0; + final int _rowsPerPage = 5; + + @override + void initState() { + super.initState(); + _checkLogin(); + } + + String hitungUsia(String tanggalLahir) { + try { + DateTime lahir = DateTime.parse(tanggalLahir); + DateTime now = DateTime.now(); + int tahun = now.year - lahir.year; + int bulan = now.month - lahir.month; + int hari = now.day - lahir.day; + if (hari < 0) { + bulan -= 1; + hari += DateTime(now.year, now.month, 0).day; + } + if (bulan < 0) { + tahun -= 1; + bulan += 12; + } + return "$tahun thn $bulan bln $hari hr"; + } catch (e) { + return "-"; + } + } + + String _formatTanggalIndo(String? tanggal) { + if (tanggal == null || tanggal.isEmpty || tanggal == "-") return "-"; + try { + DateTime dt = DateTime.parse(tanggal); + List bulanIndo = [ + "", + "Januari", + "Februari", + "Maret", + "April", + "Mei", + "Juni", + "Juli", + "Agustus", + "September", + "Oktober", + "November", + "Desember" + ]; + return "${dt.day} ${bulanIndo[dt.month]} ${dt.year}"; + } catch (e) { + return tanggal; + } + } + + Future _checkLogin() async { + final prefs = await SharedPreferences.getInstance(); + final isLogin = prefs.getBool('isLogin') ?? false; + + if (!isLogin) { + if (!mounted) return; + Navigator.pushReplacement( + context, + MaterialPageRoute(builder: (_) => const LoginPage()), + ); + return; + } + + setState(() => _checkingLogin = false); + _fetchData(); + } + + Future _fetchData() async { + setState(() => _loading = true); + final url = Uri.parse( + 'http://ta.myhost.id/E31230549/mposyandu_api/pemeriksaan_balita/get_riwayat_pemeriksaan_balita.php?id_balita=${widget.idBalita}', + ); + + try { + final response = await http.get(url); + if (response.statusCode == 200) { + final jsonData = json.decode(response.body); + if (jsonData["success"] == true) { + final List> data = + List>.from(jsonData["data"]); + + setState(() { + for (var item in data) { + item["jk_formatted"] = item["jenis_kelamin"] == "L" + ? "Laki-Laki" + : (item["jenis_kelamin"] == "P" ? "Perempuan" : "-"); + item["ibu_suami"] = + "${item["nama_ibu"] ?? '-'} (${item["nama_suami"] ?? '-'})"; + + if (item["tanggal_lahir"] != null) { + item["usia_formatted"] = hitungUsia(item["tanggal_lahir"]); + item["tgl_lahir_formatted"] = + _formatTanggalIndo(item["tanggal_lahir"]); + } else { + item["usia_formatted"] = "-"; + item["tgl_lahir_formatted"] = "-"; + } + + item["bb_formatted"] = "${item["bb"] ?? '-'} kg"; + item["tb_formatted"] = "${item["tb"] ?? '-'} cm"; + item["lk_formatted"] = "${item["lk"] ?? '-'} cm"; + } + _allData = data; + _data = data; + _loading = false; + }); + } else { + setState(() { + _data = []; + _loading = false; + }); + } + } + } catch (e) { + debugPrint("ERROR FETCH: $e"); + setState(() => _loading = false); + } + } + + Future _hapusData(int idPemeriksaan) async { + final confirm = await showDialog( + context: context, + builder: (c) => AlertDialog( + title: Text("Konfirmasi", + style: + GoogleFonts.poppins(fontSize: 14, fontWeight: FontWeight.bold)), + content: Text("Yakin ingin menghapus data ini?", + style: GoogleFonts.poppins(fontSize: 12)), + actions: [ + TextButton( + onPressed: () => Navigator.pop(c, false), child: Text("Batal")), + OutlinedButton( + onPressed: () => Navigator.pop(c, true), + style: OutlinedButton.styleFrom( + side: const BorderSide(color: Colors.red), + shape: const StadiumBorder()), + child: Text("Hapus", + style: GoogleFonts.poppins( + color: Colors.red, + fontSize: 12, + fontWeight: FontWeight.bold)), + ), + ], + ), + ); + + if (confirm != true) return; + + try { + final url = Uri.parse( + "http://ta.myhost.id/E31230549/mposyandu_api/pemeriksaan_balita/hapus_pemeriksaan_balita.php"); + final response = await http + .post(url, body: {"id_pemeriksaan": idPemeriksaan.toString()}); + final res = json.decode(response.body); + if (res["success"] == true) { + ScaffoldMessenger.of(context) + .showSnackBar(SnackBar(content: Text("Data berhasil dihapus"))); + _fetchData(); + } + } catch (e) { + ScaffoldMessenger.of(context) + .showSnackBar(SnackBar(content: Text("Gagal hapus: $e"))); + } + } + + List> get _paginatedData { + if (_data.isEmpty) return []; + final start = _currentPage * _rowsPerPage; + final end = start + _rowsPerPage; + return _data.sublist(start, end > _data.length ? _data.length : end); + } + + @override + Widget build(BuildContext context) { + if (_checkingLogin) + return const Scaffold(body: Center(child: CircularProgressIndicator())); + final totalPages = _data.isEmpty ? 1 : (_data.length / _rowsPerPage).ceil(); + + return Scaffold( + backgroundColor: Colors.grey[100], + appBar: AppBar( + backgroundColor: Colors.blueAccent, + elevation: 0, + title: const Text(""), + leading: IconButton( + icon: const Icon(Icons.arrow_back, color: Colors.white), + onPressed: () => Navigator.pop(context)), + ), + body: _loading + ? const Center(child: CircularProgressIndicator()) + : Padding( + padding: const EdgeInsets.all(16), + child: Column( + children: [ + Center( + child: Text("Data Riwayat Pemeriksaan", + style: GoogleFonts.poppins( + fontSize: 18, fontWeight: FontWeight.bold))), + const SizedBox(height: 15), + TextField( + style: GoogleFonts.poppins(fontSize: 12), + decoration: InputDecoration( + hintText: "Cari tanggal pemeriksaan....", + prefixIcon: const Icon(Icons.search, size: 20), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10)), + filled: true, + fillColor: Colors.white, + contentPadding: const EdgeInsets.symmetric(vertical: 8), + ), + onChanged: (value) { + setState(() { + _data = _allData + .where((b) => (b['tanggal_pemeriksaan'] ?? '') + .toString() + .toLowerCase() + .contains(value.toLowerCase())) + .toList(); + _currentPage = 0; + }); + }, + ), + const SizedBox(height: 15), + Expanded( + child: _data.isEmpty + ? Center( + child: Text("Tidak ada riwayat pemeriksaan", + style: GoogleFonts.poppins(fontSize: 12))) + : ListView.builder( + itemCount: _paginatedData.length, + itemBuilder: (context, index) { + final item = _paginatedData[index]; + bool isLolos = item["status"] == 'lolos'; + String? statusHadir = item["status_hadir"]; + + return Container( + margin: const EdgeInsets.symmetric(vertical: 8), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(14), + boxShadow: const [ + BoxShadow( + color: Colors.black12, + blurRadius: 8, + offset: Offset(0, 4)) + ], + ), + child: Column( + children: [ + Container( + width: double.infinity, + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: isLolos + ? Colors.green + : Colors.blueAccent, + borderRadius: + const BorderRadius.vertical( + top: Radius.circular(14)), + ), + child: Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: + MainAxisAlignment.spaceBetween, + children: [ + Expanded( + child: Text( + item["nama_balita"] ?? "-", + style: GoogleFonts.poppins( + color: Colors.white, + fontWeight: + FontWeight.bold, + fontSize: 14), + ), + ), + Row( + children: [ + // BADGE KEHADIRAN (Hanya muncul jika belum lolos) + if (!isLolos && + statusHadir != null && + statusHadir != "-") + Container( + margin: + const EdgeInsets.only( + right: 5), + padding: const EdgeInsets + .symmetric( + horizontal: 8, + vertical: 2), + decoration: BoxDecoration( + color: statusHadir == + 'Hadir' + ? Colors.green + : Colors.red, + borderRadius: + BorderRadius + .circular(10), + border: Border.all( + color: Colors.white, + width: 1), + ), + child: Text( + statusHadir + .toUpperCase(), + style: + GoogleFonts.poppins( + fontSize: 10, + fontWeight: + FontWeight + .bold, + color: Colors + .white), + ), + ), + if (isLolos) + Container( + padding: const EdgeInsets + .symmetric( + horizontal: 8, + vertical: 2), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: + BorderRadius + .circular( + 10)), + child: Text("LOLOS", + style: GoogleFonts + .poppins( + fontSize: 10, + fontWeight: + FontWeight + .bold, + color: Colors + .green)), + ), + ], + ) + ], + ), + const SizedBox(height: 4), + _rowHeader( + "Orang Tua", item["ibu_suami"]), + _rowHeader("Jenis Kelamin", + item["jk_formatted"]), + _rowHeader("Tgl Lahir", + item["tgl_lahir_formatted"]), + _rowHeader("Usia Saat Ini", + item["usia_formatted"]), + ], + ), + ), + Container( + padding: const EdgeInsets.all(12), + child: Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + Text("Hasil Pemeriksaan", + style: GoogleFonts.poppins( + fontWeight: FontWeight.w600, + fontSize: 12, + color: Colors.blueAccent)), + const Divider(), + _rowDetail( + "Tanggal Periksa", + _formatTanggalIndo( + item["tanggal_pemeriksaan"])), + _rowDetail("Berat Badan", + item["bb_formatted"]), + _rowDetail("Tinggi Badan", + item["tb_formatted"]), + _rowDetail("Lingkar Kepala", + item["lk_formatted"]), + _rowDetail( + "Imunisasi", item["imunisasi"]), + _rowDetail( + "Vitamin A", item["vitamin_a"]), + _rowDetail("PMT", item["pmt"]), + _rowDetail( + "Catatan", item["catatan"]), + const SizedBox(height: 10), + Row( + mainAxisAlignment: + MainAxisAlignment.end, + children: [ + _actionButton( + label: "Edit", + icon: Icons.edit, + color: Colors.orange, + onPressed: () async { + final result = await Navigator.push( + context, + MaterialPageRoute( + builder: (_) => + EditPemeriksaanBalitaPage( + data: item))); + if (result == true) + _fetchData(); + }, + ), + const SizedBox(width: 8), + _actionButton( + label: "Hapus", + icon: Icons.delete, + color: Colors.red, + onPressed: () => _hapusData( + int.parse( + item["id_pemeriksaan"] + .toString())), + ), + ], + ), + ], + ), + ), + ], + ), + ); + }, + ), + ), + const SizedBox(height: 10), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text("Halaman ${_currentPage + 1} dari $totalPages", + style: GoogleFonts.poppins(fontSize: 12)), + Row( + children: [ + IconButton( + icon: const Icon(Icons.chevron_left, size: 20), + onPressed: _currentPage == 0 + ? null + : () => setState(() => _currentPage--)), + IconButton( + icon: const Icon(Icons.chevron_right, size: 20), + onPressed: _currentPage >= totalPages - 1 + ? null + : () => setState(() => _currentPage++)), + ], + ), + ], + ), + ], + ), + ), + ); + } + + Widget _rowHeader(String label, dynamic value) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 1), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: 95, + child: Text(label, + style: GoogleFonts.poppins( + fontSize: 11, + fontWeight: FontWeight.w600, + color: Colors.white))), + Text(" : ", + style: GoogleFonts.poppins( + color: Colors.white, + fontSize: 11, + fontWeight: FontWeight.bold)), + Expanded( + child: Text("${value ?? '-'}", + style: GoogleFonts.poppins( + fontSize: 11, + color: Colors.white, + fontWeight: FontWeight.w400))), + ], + ), + ); + } + + Widget _rowDetail(String label, dynamic value) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 2), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: 105, + child: Text(label, + style: GoogleFonts.poppins( + fontSize: 12, + fontWeight: FontWeight.w600, + color: Colors.black87))), + Text(" : ", + style: GoogleFonts.poppins( + fontSize: 12, + color: Colors.black, + fontWeight: FontWeight.bold)), + Expanded( + child: Text("${value ?? '-'}", + style: + GoogleFonts.poppins(fontSize: 12, color: Colors.black))), + ], + ), + ); + } + + Widget _actionButton( + {required String label, + required IconData icon, + required Color color, + required VoidCallback onPressed}) { + return SizedBox( + height: 32, + child: OutlinedButton.icon( + style: OutlinedButton.styleFrom( + side: BorderSide(color: color, width: 1.5), + shape: const StadiumBorder(), + padding: const EdgeInsets.symmetric(horizontal: 12)), + onPressed: onPressed, + icon: Icon(icon, size: 14, color: color), + label: Text(label, + style: GoogleFonts.poppins( + fontSize: 11, fontWeight: FontWeight.bold, color: color)), + ), + ); + } +} diff --git a/lib/kader/crud_pemeriksaan/tambah_pemeriksaan.dart b/lib/kader/crud_pemeriksaan/tambah_pemeriksaan.dart new file mode 100644 index 0000000..27b228a --- /dev/null +++ b/lib/kader/crud_pemeriksaan/tambah_pemeriksaan.dart @@ -0,0 +1,316 @@ +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:http/http.dart' as http; +import 'package:intl/intl.dart'; + +class TambahPemeriksaanBalitaPage extends StatefulWidget { + final Map balita; + + const TambahPemeriksaanBalitaPage({ + super.key, + required this.balita, + }); + + @override + State createState() => + _TambahPemeriksaanBalitaPageState(); +} + +class _TambahPemeriksaanBalitaPageState + extends State { + final _formKey = GlobalKey(); + + final bbController = TextEditingController(); + final tbController = TextEditingController(); + final lkController = TextEditingController(); + final catatanController = TextEditingController(); + final tanggalController = TextEditingController(); + + String? vitaminA; + String? pmt; + + bool _isSaving = false; + DateTime selectedDate = DateTime.now(); + List imunisasiList = []; + Map selectedImunisasi = {}; + bool loadingImunisasi = true; + + @override + void initState() { + super.initState(); + tanggalController.text = DateFormat('dd-MM-yyyy').format(selectedDate); + ambilImunisasiOtomatis(); + } + + @override + void dispose() { + bbController.dispose(); + tbController.dispose(); + lkController.dispose(); + catatanController.dispose(); + tanggalController.dispose(); + super.dispose(); + } + + Future ambilImunisasiOtomatis() async { + try { + final response = await http.get( + Uri.parse( + "http://ta.myhost.id/E31230549/mposyandu_api/pemeriksaan_balita/get_imunisasi.php?id_balita=${widget.balita["id_balita"] ?? widget.balita["id"]}"), + ); + final data = json.decode(response.body); + if (data["success"] == true) { + imunisasiList = data["imunisasi"]; + for (var item in imunisasiList) { + selectedImunisasi[item["id"]] = item["checked"]; + } + setState(() => loadingImunisasi = false); + } + } catch (e) { + setState(() => loadingImunisasi = false); + } + } + + Future _pilihTanggal() async { + FocusScope.of(context).requestFocus(FocusNode()); + final picked = await showDatePicker( + context: context, + initialDate: selectedDate, + firstDate: DateTime(2000), + lastDate: DateTime(2101), + ); + if (picked != null) { + setState(() { + selectedDate = picked; + tanggalController.text = DateFormat('dd-MM-yyyy').format(picked); + }); + } + } + + Future _simpan() async { + // Validasi form dilewati untuk field opsional, tapi ID balita tetap dicek di logic + setState(() => _isSaving = true); + + try { + final url = Uri.parse( + "http://ta.myhost.id/E31230549/mposyandu_api/pemeriksaan_balita/tambah_pemeriksaan_balita.php"); + + String formatTanggalDb = DateFormat('yyyy-MM-dd').format(selectedDate); + + String imunisasiDipilih = selectedImunisasi.entries + .where((e) => e.value == true) + .map((e) => e.key.toString()) + .join(","); + + final response = await http.post(url, body: { + "id_balita": widget.balita["id_balita"]?.toString() ?? + widget.balita["id"]?.toString() ?? + "0", + "tanggal_pemeriksaan": formatTanggalDb, + "bb": bbController.text.trim(), + "tb": tbController.text.trim(), + "lk": lkController.text.trim(), + "vitamin_a": vitaminA ?? "", + "pmt": pmt ?? "", + "catatan": catatanController.text.trim(), + "imunisasi": imunisasiDipilih + }); + + final data = json.decode(response.body); + + if (data["success"] == true) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text("Data berhasil disimpan")), + ); + Navigator.pop(context, true); + } else { + throw Exception(data["message"] ?? "Terjadi kesalahan server"); + } + } catch (e) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text("Gagal: $e")), + ); + } finally { + if (mounted) setState(() => _isSaving = false); + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: const Text(""), + backgroundColor: Colors.blue, + foregroundColor: Colors.white, + ), + backgroundColor: const Color(0xfff4f6fb), + body: Center( + child: SingleChildScrollView( + padding: const EdgeInsets.all(16), + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 420), + child: Container( + padding: const EdgeInsets.all(24), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(20), + boxShadow: const [ + BoxShadow( + blurRadius: 16, + color: Colors.black12, + offset: Offset(0, 8)) + ], + ), + child: Form( + key: _formKey, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Center( + child: Text( + "Tambah Data Pemeriksaan", + style: GoogleFonts.poppins( + fontSize: 18, fontWeight: FontWeight.bold), + ), + ), + const SizedBox(height: 20), + TextFormField( + controller: tanggalController, + readOnly: true, + onTap: _pilihTanggal, + style: GoogleFonts.poppins(fontSize: 12), + decoration: _decoration("Tanggal Periksa").copyWith( + suffixIcon: const Icon(Icons.calendar_month, + size: 18, color: Colors.blue), + ), + ), + const SizedBox(height: 16), + _inputNumber(bbController, "Berat Badan (kg)"), + const SizedBox(height: 16), + _inputNumber(tbController, "Tinggi Badan (cm)"), + const SizedBox(height: 16), + _inputNumber(lkController, "Lingkar Kepala (cm)"), + const SizedBox(height: 20), + Text("Imunisasi Sesuai Usia", + style: GoogleFonts.poppins( + fontSize: 13, fontWeight: FontWeight.w600)), + const SizedBox(height: 8), + _buildCheckboxImunisasi(), + const SizedBox(height: 16), + _dropdown( + label: "Vitamin A", + hint: "Pilih Vitamin A (Opsional)", + items: const ["Diberikan", "Belum"], + value: vitaminA, + onChanged: (v) => setState(() => vitaminA = v), + ), + const SizedBox(height: 16), + _dropdown( + label: "PMT", + hint: "Pilih PMT (Opsional)", + items: const ["Diberikan", "Belum"], + value: pmt, + onChanged: (v) => setState(() => pmt = v), + ), + const SizedBox(height: 16), + TextFormField( + controller: catatanController, + maxLines: 3, + style: GoogleFonts.poppins(fontSize: 12), + decoration: _decoration("Catatan Pemeriksaan (Opsional)"), + ), + const SizedBox(height: 28), + SizedBox( + width: double.infinity, + height: 50, + child: OutlinedButton( + onPressed: _isSaving ? null : _simpan, + style: OutlinedButton.styleFrom( + side: const BorderSide( + color: Colors.blueAccent, width: 2), + shape: const StadiumBorder(), + ), + child: _isSaving + ? const SizedBox( + height: 20, + width: 20, + child: + CircularProgressIndicator(strokeWidth: 2), + ) + : Text("Simpan", + style: GoogleFonts.poppins( + fontWeight: FontWeight.bold, + color: Colors.blueAccent)), + ), + ), + ], + ), + ), + ), + ), + ), + ), + ); + } + + Widget _inputNumber(TextEditingController controller, String label) { + return TextFormField( + controller: controller, + keyboardType: const TextInputType.numberWithOptions(decimal: true), + style: GoogleFonts.poppins(fontSize: 12), + // Validator dihapus agar bisa kosong + decoration: _decoration(label + " (Opsional)"), + ); + } + + Widget _dropdown({ + required String label, + required String hint, + required List items, + required String? value, + required Function(String?) onChanged, + }) { + return DropdownButtonFormField( + value: value, + hint: Text(hint, style: GoogleFonts.poppins(fontSize: 12)), + style: GoogleFonts.poppins(fontSize: 12, color: Colors.black), + items: + items.map((e) => DropdownMenuItem(value: e, child: Text(e))).toList(), + onChanged: onChanged, + decoration: _decoration(label), + ); + } + + InputDecoration _decoration(String label) { + return InputDecoration( + filled: true, + fillColor: Colors.white, + labelText: label, + labelStyle: GoogleFonts.poppins(fontSize: 12), + border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)), + contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + ); + } + + Widget _buildCheckboxImunisasi() { + if (loadingImunisasi) + return const Center(child: CircularProgressIndicator()); + if (imunisasiList.isEmpty) return const Text("Tidak ada imunisasi"); + return Column( + children: imunisasiList.map((item) { + final bool sudah = item["status"] == "Sudah"; + return CheckboxListTile( + value: selectedImunisasi[item["id"]] ?? false, + onChanged: sudah + ? null + : (v) => setState(() => selectedImunisasi[item["id"]] = v!), + title: Text(item["nama_imunisasi"], + style: GoogleFonts.poppins(fontSize: 12)), + controlAffinity: ListTileControlAffinity.leading, + ); + }).toList(), + ); + } +} diff --git a/lib/kader/dashboard_kader.dart b/lib/kader/dashboard_kader.dart new file mode 100644 index 0000000..6ae7df9 --- /dev/null +++ b/lib/kader/dashboard_kader.dart @@ -0,0 +1,551 @@ +import 'dart:convert'; +import 'dart:async'; +import 'dart:io'; // Tambahkan ini +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; // Tambahkan ini untuk SystemNavigator.pop +import 'package:google_fonts/google_fonts.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:http/http.dart' as http; +import 'package:audioplayers/audioplayers.dart'; +import '../layout/main_layout.dart'; +import 'kader_drawer.dart'; +import '../pages/login_page.dart'; +import '../kader/data_kehamilan.dart'; +import '../kader/data_balita.dart'; + +class DashboardKaderPage extends StatefulWidget { + const DashboardKaderPage({super.key}); + + @override + State createState() => _DashboardKaderPageState(); +} + +class _DashboardKaderPageState extends State { + DateTime selectedDate = DateTime.now(); + List jadwalList = []; + Timer? _pollingTimer; + final AudioPlayer _audioPlayer = AudioPlayer(); + int _notificationCount = 0; + String userName = "Kader"; + String _lastJadwalDataString = ""; + String? keteranganKegiatan; + String? tempatKegiatan; + String? jamMulai; + String? jamSelesai; + bool isLoadingJadwal = true; + int jumlahIbu = 0; + int jumlahBalita = 0; + bool isLoading = true; + int? kaderId; + + static const String baseUrl = "http://ta.myhost.id/E31230549/mposyandu_api"; + final String dashboardUrl = "$baseUrl/dashboard_kader.php"; + final String jadwalUrl = "$baseUrl/jadwal_posyandu/get_jadwal_by_kader.php"; + + @override + void initState() { + super.initState(); + _audioPlayer.setReleaseMode(ReleaseMode.stop); + _initPage(); + _pollingTimer = Timer.periodic(const Duration(seconds: 10), (timer) { + if (kaderId != null && kaderId != 0) { + _loadJadwalKader(); + } + }); + } + + @override + void dispose() { + _pollingTimer?.cancel(); + _audioPlayer.dispose(); + super.dispose(); + } + + Future _playNotifSound() async { + try { + await _audioPlayer.stop(); + await _audioPlayer.play(AssetSource('sounds/notif.mp3')); + } catch (e) { + debugPrint("DEBUG AUDIO ERROR: $e"); + } + } + + Future _initPage() async { + final prefs = await SharedPreferences.getInstance(); + final isLogin = prefs.getBool('isLogin') ?? false; + + if (!isLogin) { + if (!mounted) return; + Navigator.pushAndRemoveUntil( + context, + MaterialPageRoute(builder: (_) => const LoginPage(fromGuard: true)), + (route) => false, + ); + return; + } + + String? idString = prefs.getString('id_user'); + int currentId = int.tryParse(idString ?? "0") ?? 0; + + setState(() { + userName = prefs.getString('nama') ?? "Kader"; + kaderId = currentId; + _notificationCount = prefs.getInt('unread_notif_count_$idString') ?? 0; + _lastJadwalDataString = + prefs.getString('last_jadwal_data_string_$idString') ?? ""; + }); + + if (currentId != 0) { + await _loadDashboard(); + await _loadJadwalKader(); + } else { + if (mounted) setState(() => isLoading = false); + } + } + + Future _loadDashboard() async { + if (kaderId == null || kaderId == 0) { + final prefs = await SharedPreferences.getInstance(); + kaderId = int.tryParse(prefs.getString('id_user') ?? "0"); + } + + if (kaderId == null || kaderId == 0) { + if (mounted) setState(() => isLoading = false); + return; + } + + try { + final res = await http + .get(Uri.parse("$dashboardUrl?id_kader=$kaderId")) + .timeout(const Duration(seconds: 10)); + + final data = jsonDecode(res.body); + + if (data['success'] == true) { + if (mounted) { + setState(() { + jumlahIbu = int.tryParse(data['jumlah_ibu'].toString()) ?? 0; + jumlahBalita = int.tryParse(data['jumlah_balita'].toString()) ?? 0; + isLoading = false; + }); + } + } else { + debugPrint("API Error: ${data['message']}"); + if (mounted) setState(() => isLoading = false); + } + } catch (e) { + debugPrint("Error Dashboard Connection: $e"); + if (mounted) setState(() => isLoading = false); + } + } + + Future _loadJadwalKader() async { + if (kaderId == null || kaderId == 0) return; + try { + final url = "$jadwalUrl?kader_id=$kaderId"; + final res = + await http.get(Uri.parse(url)).timeout(const Duration(seconds: 10)); + final data = jsonDecode(res.body); + + if (data['success'] == true) { + List fetchedJadwal = data['data'] ?? []; + String currentDataString = jsonEncode(fetchedJadwal); + final prefs = await SharedPreferences.getInstance(); + String idStr = kaderId.toString(); + + if (_lastJadwalDataString.isNotEmpty && + currentDataString != _lastJadwalDataString) { + List oldList = jsonDecode(_lastJadwalDataString); + if (fetchedJadwal.length >= oldList.length) { + _playNotifSound(); + setState(() { + _notificationCount += 1; + }); + await prefs.setInt('unread_notif_count_$idStr', _notificationCount); + + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: const Text("Jadwal diperbarui atau ditambah!"), + backgroundColor: Colors.blue.shade700, + duration: const Duration(seconds: 2), + ), + ); + } + } + } + + await prefs.setString( + 'last_jadwal_data_string_$idStr', currentDataString); + + if (mounted) { + setState(() { + jadwalList = fetchedJadwal; + _lastJadwalDataString = currentDataString; + isLoadingJadwal = false; + }); + _updateJadwalByDate(selectedDate); + } + } else { + _resetJadwal(); + } + } catch (e) { + debugPrint("Error polling: $e"); + if (mounted) setState(() => isLoadingJadwal = false); + } + } + + void _resetJadwal() { + if (mounted) { + setState(() { + keteranganKegiatan = null; + tempatKegiatan = null; + jamMulai = null; + jamSelesai = null; + isLoadingJadwal = false; + }); + } + } + + String formatTanggal(DateTime date) { + return "${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}"; + } + + void _updateJadwalByDate(DateTime date) { + String tanggalDipilih = formatTanggal(date); + Map? jadwalHariIni; + + for (var j in jadwalList) { + if (j['tanggal'] != null) { + String tanggalApi = j['tanggal'].toString().substring(0, 10); + if (tanggalApi == tanggalDipilih) { + jadwalHariIni = j; + break; + } + } + } + + if (jadwalHariIni != null) { + setState(() { + keteranganKegiatan = jadwalHariIni!['keterangan']; + tempatKegiatan = jadwalHariIni['lokasi']; + jamMulai = jadwalHariIni['jam_mulai']; + jamSelesai = jadwalHariIni['jam_selesai']; + }); + } else { + _resetJadwal(); + } + } + + Future _showNotifDialog() async { + final prefs = await SharedPreferences.getInstance(); + String idStr = kaderId.toString(); + setState(() { + _notificationCount = 0; + }); + await prefs.setInt('unread_notif_count_$idStr', 0); + + if (!mounted) return; + showDialog( + context: context, + builder: (_) { + return AlertDialog( + shape: + RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)), + title: Text("Pemberitahuan Jadwal", + style: GoogleFonts.poppins(fontWeight: FontWeight.w600)), + content: SizedBox( + width: 300, + child: jadwalList.isEmpty + ? const Padding( + padding: EdgeInsets.symmetric(vertical: 20), + child: + Text("Belum ada jadwal", textAlign: TextAlign.center), + ) + : ListView.builder( + shrinkWrap: true, + itemCount: jadwalList.length > 5 ? 5 : jadwalList.length, + itemBuilder: (_, index) { + final item = jadwalList[(jadwalList.length - 1) - index]; + return Card( + elevation: 2, + margin: const EdgeInsets.symmetric(vertical: 6), + child: ListTile( + leading: const CircleAvatar( + backgroundColor: Colors.blue, + child: Icon(Icons.event, + color: Colors.white, size: 20), + ), + title: Text( + item['keterangan'] ?? "Kegiatan Posyandu", + style: GoogleFonts.poppins( + fontWeight: FontWeight.w600, fontSize: 13), + ), + subtitle: Text( + "Tgl: ${item['tanggal']?.toString().substring(0, 10) ?? '-'}\nLokasi: ${item['lokasi'] ?? '-'}", + style: GoogleFonts.poppins(fontSize: 11), + ), + isThreeLine: true, + ), + ); + }, + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text("Tutup")) + ], + ); + }, + ); + } + + @override + Widget build(BuildContext context) { + return PopScope( + canPop: false, // Menahan aksi "back" standar + onPopInvokedWithResult: (didPop, result) { + if (didPop) return; + // Keluar dari aplikasi secara total + if (Platform.isAndroid) { + SystemNavigator.pop(); + } else if (Platform.isIOS) { + exit(0); + } + }, + child: Theme( + data: Theme.of(context).copyWith( + textTheme: GoogleFonts.poppinsTextTheme(Theme.of(context).textTheme), + dividerColor: Colors.transparent, + ), + child: Stack( + children: [ + MainLayout( + title: " ", + drawer: const KaderDrawer(), + body: _buildDashboard(), + ), + Positioned( + top: MediaQuery.of(context).padding.top + + (kToolbarHeight - 48) / 2, + right: 8, + child: Stack( + alignment: Alignment.center, + children: [ + IconButton( + icon: const Icon(Icons.notifications, + color: Colors.white, size: 26), + onPressed: _showNotifDialog, + ), + if (_notificationCount > 0) + Positioned( + right: 8, + top: 8, + child: Container( + padding: const EdgeInsets.all(2), + decoration: BoxDecoration( + color: Colors.red, + shape: BoxShape.circle, + border: Border.all(color: Colors.white, width: 1.5), + ), + constraints: + const BoxConstraints(minWidth: 18, minHeight: 18), + child: Center( + child: Text( + _notificationCount > 9 + ? "9+" + : _notificationCount.toString(), + style: const TextStyle( + color: Colors.white, + fontSize: 9, + fontWeight: FontWeight.bold), + ), + ), + ), + ) + ], + ), + ), + ], + ), + ), + ); + } + + Widget _buildDashboard() { + return RefreshIndicator( + onRefresh: () async { + await _loadDashboard(); + await _loadJadwalKader(); + }, + child: Padding( + padding: const EdgeInsets.all(16), + child: SingleChildScrollView( + physics: const AlwaysScrollableScrollPhysics(), + child: Column( + children: [ + Align( + alignment: Alignment.centerLeft, + child: RichText( + text: TextSpan( + children: [ + TextSpan( + text: 'Selamat Datang Kader $userName\n', + style: GoogleFonts.poppins( + fontSize: 20, + fontWeight: FontWeight.w700, + color: const Color.fromARGB(255, 19, 133, 226)), + ), + TextSpan( + text: 'Tetap semangat melayani masyarakat ', + style: GoogleFonts.poppins( + fontSize: 13, + fontWeight: FontWeight.w500, + color: Colors.black87), + ), + const WidgetSpan( + child: Icon(Icons.favorite, + color: Colors.blue, size: 18)), + ], + ), + ), + ), + const SizedBox(height: 15), + Center( + child: Image.asset('assets/images/logoo.webp', + width: 300, height: 200, fit: BoxFit.contain)), + const SizedBox(height: 25), + isLoading + ? const Center(child: CircularProgressIndicator()) + : Row( + children: [ + _infoBoxClickable(jumlahIbu.toString(), + 'Jumlah Ibu Hamil', Colors.pink, () async { + await Navigator.push( + context, + MaterialPageRoute( + builder: (_) => const DataIbuHamilPage())); + _loadDashboard(); + }), + const SizedBox(width: 10), + _infoBoxClickable( + jumlahBalita.toString(), + 'Jumlah Balita', + const Color.fromARGB(255, 240, 220, 39), () async { + await Navigator.push( + context, + MaterialPageRoute( + builder: (_) => const DataBalitaPage())); + _loadDashboard(); + }), + ], + ), + const SizedBox(height: 30), + const Text('Jadwal Posyandu', + style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)), + const SizedBox(height: 15), + isLoadingJadwal + ? const CircularProgressIndicator() + : keteranganKegiatan == null + ? const Text("Tidak ada kegiatan posyandu hari ini", + style: TextStyle(color: Colors.red)) + : Center( + child: IntrinsicWidth( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildDetailRow(Icons.access_time, "Jam", + "${jamMulai ?? '-'} s/d ${jamSelesai ?? '-'}"), + const SizedBox(height: 8), + _buildDetailRow(Icons.location_on, "Lokasi", + tempatKegiatan ?? "-"), + const SizedBox(height: 8), + _buildDetailRow(Icons.event_available, + "Kegiatan", keteranganKegiatan ?? "-"), + ], + ), + ), + ), + const SizedBox(height: 25), + Container( + width: 260, + padding: const EdgeInsets.all(6), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12), + boxShadow: [ + BoxShadow( + color: Colors.grey.withOpacity(0.2), blurRadius: 5) + ], + ), + child: Transform.scale( + scale: 0.8, + child: CalendarDatePicker( + initialDate: selectedDate, + firstDate: DateTime(2020), + lastDate: DateTime(2030), + onDateChanged: (date) { + setState(() => selectedDate = date); + _updateJadwalByDate(date); + }, + ), + ), + ), + ], + ), + ), + ), + ); + } + + Widget _buildDetailRow(IconData icon, String label, String value) { + return Row( + children: [ + Icon(icon, size: 18, color: Colors.blue), + const SizedBox(width: 10), + SizedBox( + width: 90, + child: Text(label, + style: const TextStyle( + fontWeight: FontWeight.w600, fontSize: 12))), + const SizedBox( + width: 10, + child: Text(":", style: TextStyle(fontWeight: FontWeight.bold))), + Expanded( + child: Text(value, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 12))), + ], + ); + } + + static Widget _infoBoxClickable( + String value, String label, Color color, VoidCallback onTap) { + return Expanded( + child: InkWell( + borderRadius: BorderRadius.circular(12), + onTap: onTap, + child: Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: color, borderRadius: BorderRadius.circular(12)), + child: Column( + children: [ + Text(value, + style: const TextStyle( + color: Colors.white, + fontSize: 24, + fontWeight: FontWeight.bold)), + const SizedBox(height: 5), + Text(label, + textAlign: TextAlign.center, + style: const TextStyle(color: Colors.white)), + ], + ), + ), + ), + ); + } +} diff --git a/lib/kader/data_balita.dart b/lib/kader/data_balita.dart new file mode 100644 index 0000000..44e23c0 --- /dev/null +++ b/lib/kader/data_balita.dart @@ -0,0 +1,589 @@ +import 'dart:async'; +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:http/http.dart' as http; + +import '../layout/main_layout.dart'; +import 'kader_drawer.dart'; +import '../pages/login_page.dart'; +import '../kader/crud_balita/tambah_balita.dart'; +import '../kader/crud_balita/edit_balita.dart'; +import '../kader/dashboard_kader.dart'; + +class DataBalitaPage extends StatefulWidget { + const DataBalitaPage({super.key}); + + @override + State createState() => _DataBalitaPageState(); +} + +class _DataBalitaPageState extends State { + List _data = []; + List _filteredData = []; + bool _isLoading = true; + + int _currentPage = 0; + final int _rowsPerPage = 5; + + final TextEditingController _searchC = TextEditingController(); + Timer? _debounce; + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addPostFrameCallback((_) { + _checkLogin(); + _fetchData(); + }); + _searchC.addListener(_onSearchChanged); + } + + @override + void dispose() { + _searchC.dispose(); + _debounce?.cancel(); + super.dispose(); + } + + String _formatJenisKelamin(String jk) { + if (jk.toLowerCase() == "p") return "Perempuan"; + if (jk.toLowerCase() == "l") return "Laki-laki"; + return jk; + } + + String _formatTempatTanggal(String? tempat, String? tanggal) { + String tempatLahir = (tempat == null || tempat.isEmpty) ? "-" : tempat; + String tanggalLahirFormatted = "-"; + + if (tanggal != null && tanggal.isNotEmpty && tanggal != "-") { + try { + final date = DateTime.parse(tanggal); + const bulanIndo = [ + "", + "Januari", + "Februari", + "Maret", + "April", + "Mei", + "Juni", + "Juli", + "Agustus", + "September", + "Oktober", + "November", + "Desember" + ]; + tanggalLahirFormatted = + "${date.day} ${bulanIndo[date.month]} ${date.year}"; + } catch (e) { + tanggalLahirFormatted = tanggal; + } + } + return "$tempatLahir, $tanggalLahirFormatted"; + } + + String _formatUsiaDariTanggal(String? tanggalLahir) { + if (tanggalLahir == null || tanggalLahir.isEmpty || tanggalLahir == "-") + return "-"; + try { + final lahir = DateTime.parse(tanggalLahir); + final sekarang = DateTime.now(); + int tahun = sekarang.year - lahir.year; + int bulan = sekarang.month - lahir.month; + int hari = sekarang.day - lahir.day; + + if (hari < 0) { + final prevMonth = DateTime(sekarang.year, sekarang.month, 0); + hari += prevMonth.day; + bulan--; + } + if (bulan < 0) { + bulan += 12; + tahun--; + } + return "$tahun thn $bulan bln $hari hr"; + } catch (e) { + return "-"; + } + } + + void _onSearchChanged() { + if (_debounce?.isActive ?? false) _debounce!.cancel(); + _debounce = Timer(const Duration(milliseconds: 400), () { + final keyword = _searchC.text.toLowerCase(); + setState(() { + _currentPage = 0; + _filteredData = _data.where((item) { + final nama = (item["nama"] ?? "").toString().toLowerCase(); + final nik = (item["nik_balita"] ?? "").toString().toLowerCase(); + final namaIbu = (item["nama_ibu"] ?? "").toString().toLowerCase(); + return nama.contains(keyword) || + nik.contains(keyword) || + namaIbu.contains(keyword); + }).toList(); + }); + }); + } + + Future _checkLogin() async { + final prefs = await SharedPreferences.getInstance(); + final isLogin = prefs.getBool('isLogin') ?? false; + if (!isLogin && mounted) { + Navigator.pushAndRemoveUntil( + context, + MaterialPageRoute(builder: (_) => const LoginPage(fromGuard: true)), + (route) => false, + ); + } + } + + Future _fetchData() async { + setState(() => _isLoading = true); + try { + final prefs = await SharedPreferences.getInstance(); + final rawDusunId = prefs.get('dusun_id'); + String dusunId = rawDusunId?.toString() ?? ""; + final url = Uri.parse( + "http://ta.myhost.id/E31230549/mposyandu_api/balita/get_balita.php?dusun_id=$dusunId"); + final response = await http.get(url); + final jsonData = json.decode(response.body); + if (jsonData["success"] == true) { + setState(() { + _data = jsonData["data"]; + _filteredData = _data; + _isLoading = false; + }); + } else { + setState(() { + _data = []; + _filteredData = []; + _isLoading = false; + }); + } + } catch (e) { + debugPrint("Error: $e"); + setState(() => _isLoading = false); + } + } + + Future _confirmDelete(String id) async { + final yes = await showDialog( + context: context, + builder: (_) => AlertDialog( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)), + title: Text("Konfirmasi", + style: + GoogleFonts.poppins(fontSize: 14, fontWeight: FontWeight.bold)), + content: Text("Hapus data balita ini?", + style: GoogleFonts.poppins(fontSize: 12)), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context, false), + child: Text("Batal", style: GoogleFonts.poppins(fontSize: 12))), + OutlinedButton( + onPressed: () => Navigator.pop(context, true), + style: OutlinedButton.styleFrom( + side: const BorderSide(color: Colors.red), + shape: const StadiumBorder()), + child: Text("Hapus", + style: GoogleFonts.poppins( + color: Colors.red, + fontSize: 12, + fontWeight: FontWeight.bold)), + ), + ], + ), + ); + if (yes == true) _deleteData(id); + } + + Future _deleteData(String id) async { + try { + final url = Uri.parse( + "http://ta.myhost.id/E31230549/mposyandu_api/balita/hapus_balita.php"); + final res = await http.post(url, body: {"id": id}); + final data = json.decode(res.body); + if (data["success"] == true) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar(SnackBar( + content: Text("Data dihapus", + style: GoogleFonts.poppins(fontSize: 12)))); + _fetchData(); + } + } catch (e) { + ScaffoldMessenger.of(context).showSnackBar(SnackBar( + content: + Text("Gagal: $e", style: GoogleFonts.poppins(fontSize: 12)))); + } + } + + List get _paginatedData { + final start = _currentPage * _rowsPerPage; + final end = start + _rowsPerPage; + if (start >= _filteredData.length) return []; + return _filteredData.sublist( + start, end > _filteredData.length ? _filteredData.length : end); + } + + @override + Widget build(BuildContext context) { + final totalPages = _filteredData.isEmpty + ? 1 + : (_filteredData.length / _rowsPerPage).ceil(); + + return PopScope( + canPop: false, + onPopInvokedWithResult: (didPop, result) async { + if (didPop) return; + Navigator.pushAndRemoveUntil( + context, + MaterialPageRoute(builder: (_) => const DashboardKaderPage()), + (route) => false); + }, + child: MainLayout( + title: "", + drawer: const KaderDrawer(), + body: Padding( + padding: const EdgeInsets.all(16), + child: Column( + children: [ + Text("Data Balita", + style: GoogleFonts.poppins( + fontSize: 18, fontWeight: FontWeight.w600)), + const SizedBox(height: 16), + Row( + children: [ + Expanded( + child: TextField( + controller: _searchC, + style: GoogleFonts.poppins(fontSize: 12), + decoration: InputDecoration( + hintText: "Cari Nama/NIK/Ibu...", + hintStyle: GoogleFonts.poppins(fontSize: 12), + prefixIcon: const Icon(Icons.search, size: 20), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10)), + contentPadding: const EdgeInsets.symmetric(vertical: 8), + ), + ), + ), + const SizedBox(width: 10), + OutlinedButton.icon( + onPressed: () async { + final result = await Navigator.push( + context, + MaterialPageRoute( + builder: (_) => const TambahBalitaPage())); + if (result == true) _fetchData(); + }, + icon: const Icon(Icons.add, + color: Colors.blueAccent, size: 18), + label: Text("Tambah", + style: GoogleFonts.poppins( + color: Colors.blueAccent, + fontSize: 12, + fontWeight: FontWeight.bold)), + style: OutlinedButton.styleFrom( + side: const BorderSide( + color: Colors.blueAccent, width: 1.5), + shape: const StadiumBorder(), + padding: const EdgeInsets.symmetric( + horizontal: 16, vertical: 10), + ), + ), + ], + ), + const SizedBox(height: 20), + Expanded( + child: _isLoading + ? const Center(child: CircularProgressIndicator()) + : _filteredData.isEmpty + ? Center( + child: Text("Tidak ada data balita", + style: GoogleFonts.poppins(fontSize: 12))) + : ListView.builder( + itemCount: _paginatedData.length, + itemBuilder: (context, index) { + final item = _paginatedData[index]; + String alamatLengkap = + "Desa ${item['nama_desa']}, Dusun ${item['nama_dusun']}, ${item['alamat_detail']}"; + String statusBalita = + (item["status"] ?? "belum lolos") + .toString() + .toLowerCase(); + bool isLolos = statusBalita == "lolos"; + + return Container( + margin: const EdgeInsets.only(bottom: 14), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12), + boxShadow: const [ + BoxShadow( + color: Colors.black12, + blurRadius: 6, + offset: Offset(0, 3)) + ], + ), + child: Column( + children: [ + Container( + width: double.infinity, + padding: const EdgeInsets.all(12), + decoration: const BoxDecoration( + color: Colors.blueAccent, + borderRadius: BorderRadius.vertical( + top: Radius.circular(12)), + ), + child: Row( + mainAxisAlignment: + MainAxisAlignment.spaceBetween, + children: [ + Expanded( + child: Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + Text(item["nama"] ?? "-", + style: GoogleFonts.poppins( + color: Colors.white, + fontWeight: + FontWeight.bold, + fontSize: 14)), + const SizedBox(height: 4), + _rowHeader( + "Ibu", item["nama_ibu"]), + _rowHeader( + "Ayah", item["nama_ayah"]), + ], + ), + ), + // VALIDASI STATUS (LABEL) + Container( + padding: const EdgeInsets.symmetric( + horizontal: 10, vertical: 4), + decoration: BoxDecoration( + color: isLolos + ? Colors.green + : Colors.red, + borderRadius: + BorderRadius.circular(20), + border: Border.all( + color: Colors.white, + width: 1), + ), + child: Text( + statusBalita.toUpperCase(), + style: GoogleFonts.poppins( + fontSize: 10, + color: Colors.white, + fontWeight: FontWeight.bold), + ), + ) + ], + ), + ), + Padding( + padding: const EdgeInsets.all(12), + child: Column( + children: [ + _rowHeaderContent( + "NIK Balita", item["nik_balita"], + isDark: true), + _rowHeaderContent( + "Alamat", alamatLengkap, + isDark: true), + _rowContent( + "Jenis Kelamin", + _formatJenisKelamin( + item["jenis_kelamin"] ?? + "-")), + _rowContent( + "Tempat Tgl Lahir", + _formatTempatTanggal( + item["tempat_lahir"], + item["tanggal_lahir"])), + _rowContent( + "Usia", + _formatUsiaDariTanggal( + item["tanggal_lahir"])), + _rowContent("Anak Ke", + item["anak_ke"]?.toString()), + _rowContent("Berat Lahir", + "${item["berat_lahir"] ?? "-"} Kg"), + _rowContent("Panjang Lahir", + "${item["panjang_lahir"] ?? "-"} Cm"), + _rowContent( + "Tgl Daftar", + _formatTempatTanggal("", + item["tanggal_daftar"]) + .split(", ")[1]), + const Divider(), + Row( + mainAxisAlignment: + MainAxisAlignment.end, + children: [ + _smallButton( + text: "Edit", + icon: Icons.edit, + color: Colors.orange, + onPressed: () async { + final result = + await Navigator.push( + context, + MaterialPageRoute( + builder: (_) => + EditBalitaPage( + data: + item))); + if (result == true) + _fetchData(); + }, + ), + const SizedBox(width: 8), + _smallButton( + text: "Hapus", + icon: Icons.delete, + color: Colors.red, + onPressed: () => _confirmDelete( + item["id"].toString()), + ), + ], + ) + ], + ), + ), + ], + ), + ); + }, + ), + ), + // Pagination + Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(vertical: 8), + decoration: BoxDecoration( + border: + Border(top: BorderSide(color: Colors.grey.shade200))), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text("Halaman ${_currentPage + 1} dari $totalPages", + style: GoogleFonts.poppins( + fontSize: 12, fontWeight: FontWeight.w500)), + Row( + children: [ + IconButton( + icon: const Icon(Icons.chevron_left), + onPressed: _currentPage == 0 + ? null + : () => setState(() => _currentPage--)), + IconButton( + icon: const Icon(Icons.chevron_right), + onPressed: _currentPage >= totalPages - 1 + ? null + : () => setState(() => _currentPage++)), + ], + ), + ], + ), + ), + ], + ), + ), + ), + ); + } + + Widget _rowHeader(String label, dynamic value) { + return Row( + children: [ + SizedBox( + width: 50, + child: Text(label, + style: + GoogleFonts.poppins(fontSize: 12, color: Colors.white))), + Text(": ", + style: GoogleFonts.poppins(fontSize: 12, color: Colors.white)), + Expanded( + child: Text("${value ?? '-'}", + style: GoogleFonts.poppins( + fontSize: 12, + color: Colors.white, + fontWeight: FontWeight.w500))), + ], + ); + } + + Widget _rowHeaderContent(String label, dynamic value, {bool isDark = false}) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 2), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: 110, + child: Text(label, + style: GoogleFonts.poppins( + fontSize: 12, + color: isDark ? Colors.black : Colors.white, + fontWeight: FontWeight.w600))), + Text(": ", + style: GoogleFonts.poppins( + fontSize: 12, color: isDark ? Colors.black : Colors.white)), + Expanded( + child: Text("${value ?? '-'}", + style: GoogleFonts.poppins( + fontSize: 12, + color: isDark ? Colors.black : Colors.white))), + ], + ), + ); + } + + Widget _rowContent(String label, dynamic value) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 2), + child: Row( + children: [ + SizedBox( + width: 110, + child: Text(label, + style: GoogleFonts.poppins( + fontSize: 12, + color: Colors.black, + fontWeight: FontWeight.w500))), + Text(": ", + style: + GoogleFonts.poppins(fontSize: 12, color: Colors.black)), + Expanded( + child: Text("${value ?? '-'}", + style: + GoogleFonts.poppins(fontSize: 12, color: Colors.black))), + ], + ), + ); + } + + Widget _smallButton( + {required String text, + required IconData icon, + required Color color, + required VoidCallback onPressed}) { + return OutlinedButton.icon( + onPressed: onPressed, + icon: Icon(icon, size: 14, color: color), + label: Text(text, + style: GoogleFonts.poppins( + fontSize: 12, fontWeight: FontWeight.bold, color: color)), + style: OutlinedButton.styleFrom( + side: BorderSide(color: color), + shape: const StadiumBorder(), + padding: const EdgeInsets.symmetric(horizontal: 12), + minimumSize: const Size(0, 32)), + ); + } +} diff --git a/lib/kader/data_ibu.dart b/lib/kader/data_ibu.dart new file mode 100644 index 0000000..646b804 --- /dev/null +++ b/lib/kader/data_ibu.dart @@ -0,0 +1,456 @@ +import 'dart:async'; +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:posyandu_care/kader/crud_ibu/edit_ibu.dart'; +import 'package:posyandu_care/kader/crud_ibu/tambah_ibu.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:http/http.dart' as http; + +import '../layout/main_layout.dart'; +import 'kader_drawer.dart'; +import '../pages/login_page.dart'; +import '../kader/dashboard_kader.dart'; + +class DataIbuPage extends StatefulWidget { + const DataIbuPage({super.key}); + + @override + State createState() => _DataIbuPageState(); +} + +class _DataIbuPageState extends State { + List _data = []; + List _filteredData = []; + + bool _isLoading = true; + int _currentPage = 0; + final int _rowsPerPage = 5; + final TextEditingController _searchC = TextEditingController(); + Timer? _debounce; + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addPostFrameCallback((_) { + _checkLogin(); + _fetchData(); + }); + _searchC.addListener(_onSearchChanged); + } + + @override + void dispose() { + _searchC.dispose(); + _debounce?.cancel(); + super.dispose(); + } + + // FORMAT TANGGAL INDONESIA + String formatTanggal(String? tanggal) { + if (tanggal == null || tanggal.isEmpty) return "-"; + try { + DateTime date = DateTime.parse(tanggal); + List bulan = [ + "", + "Januari", + "Februari", + "Maret", + "April", + "Mei", + "Juni", + "Juli", + "Agustus", + "September", + "Oktober", + "November", + "Desember" + ]; + return "${date.day} ${bulan[date.month]} ${date.year}"; + } catch (e) { + return tanggal; + } + } + + void _onSearchChanged() { + if (_debounce?.isActive ?? false) _debounce!.cancel(); + _debounce = Timer(const Duration(milliseconds: 400), () { + final keyword = _searchC.text.toLowerCase(); + setState(() { + _currentPage = 0; // Reset halaman ke 0 setiap kali user mengetik pencarian baru + _filteredData = _data.where((item) { + final nama = (item["nama"] ?? "").toString().toLowerCase(); + final nik = (item["nik"] ?? "").toString().toLowerCase(); + final namaSuami = (item["nama_suami"] ?? "").toString().toLowerCase(); + return nama.contains(keyword) || + nik.contains(keyword) || + namaSuami.contains(keyword); + }).toList(); + }); + }); + } + + Future _checkLogin() async { + final prefs = await SharedPreferences.getInstance(); + final isLogin = prefs.getBool('isLogin') ?? false; + + if (!isLogin && mounted) { + Navigator.pushAndRemoveUntil( + context, + MaterialPageRoute( + builder: (_) => const LoginPage(fromGuard: true), + ), + (route) => false, + ); + } + } + + Future _fetchData() async { + setState(() => _isLoading = true); + try { + final prefs = await SharedPreferences.getInstance(); + final rawDusunId = prefs.get('dusun_id'); + String dusunId = rawDusunId?.toString() ?? ""; + + final url = Uri.parse( + "http://ta.myhost.id/E31230549/mposyandu_api/ibu/get_ibu.php?dusun_id=$dusunId"); + + final response = await http.get(url); + final jsonData = json.decode(response.body); + + if (jsonData["success"] == true) { + setState(() { + _data = jsonData["data"]; + _filteredData = _data; + _isLoading = false; + }); + } else { + setState(() { + _data = []; + _filteredData = []; + _isLoading = false; + }); + } + } catch (e) { + debugPrint("ERROR GET IBU: $e"); + setState(() => _isLoading = false); + } + } + + Future _confirmDelete(String id) async { + final yes = await showDialog( + context: context, + builder: (_) => AlertDialog( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)), + title: Text("Konfirmasi Hapus", + style: + GoogleFonts.poppins(fontSize: 14, fontWeight: FontWeight.bold)), + content: Text( + "Data Ibu dan Akun Login terkait akan dihapus permanen. Lanjutkan?", + style: GoogleFonts.poppins(fontSize: 12)), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context, false), + child: Text("Batal", style: GoogleFonts.poppins(fontSize: 12))), + OutlinedButton( + style: OutlinedButton.styleFrom( + side: const BorderSide(color: Colors.red), + shape: const StadiumBorder(), + ), + onPressed: () => Navigator.pop(context, true), + child: Text("Hapus", + style: GoogleFonts.poppins( + color: Colors.red, + fontSize: 12, + fontWeight: FontWeight.bold)), + ), + ], + ), + ); + if (yes == true) _deleteData(id); + } + + Future _deleteData(String id) async { + try { + final url = Uri.parse( + "http://ta.myhost.id/E31230549/mposyandu_api/ibu/hapus_ibu.php"); + final response = await http.post(url, body: {"id": id}); + final data = json.decode(response.body); + + if (data["success"] == true && mounted) { + ScaffoldMessenger.of(context).showSnackBar(SnackBar( + content: Text("Data berhasil dihapus", + style: GoogleFonts.poppins(fontSize: 12)))); + _fetchData(); + } else { + throw Exception(data["message"]); + } + } catch (e) { + ScaffoldMessenger.of(context).showSnackBar(SnackBar( + content: Text("Gagal hapus: $e", + style: GoogleFonts.poppins(fontSize: 12)))); + } + } + + List get _paginatedData { + final start = _currentPage * _rowsPerPage; + final end = start + _rowsPerPage; + if (start >= _filteredData.length) return []; + return _filteredData.sublist( + start, end > _filteredData.length ? _filteredData.length : end); + } + + @override + Widget build(BuildContext context) { + final totalPages = _filteredData.isEmpty + ? 1 + : (_filteredData.length / _rowsPerPage).ceil(); + + return PopScope( + canPop: false, + onPopInvokedWithResult: (didPop, result) async { + if (didPop) return; + + Navigator.pushAndRemoveUntil( + context, + MaterialPageRoute( + builder: (_) => const DashboardKaderPage(), + ), + (route) => false, + ); + }, + child: MainLayout( + title: "", + drawer: const KaderDrawer(), + body: Padding( + padding: const EdgeInsets.all(16), + child: Column( + children: [ + Center( + child: Text( + "Data Ibu", + style: GoogleFonts.poppins( + fontSize: 18, fontWeight: FontWeight.bold), + ), + ), + const SizedBox(height: 20), + Row( + children: [ + Expanded( + child: TextField( + controller: _searchC, + style: GoogleFonts.poppins(fontSize: 12), + decoration: InputDecoration( + hintText: "Cari Nama/NIK/Nama Suami...", + hintStyle: GoogleFonts.poppins(fontSize: 12), + prefixIcon: const Icon(Icons.search, size: 20), + contentPadding: + const EdgeInsets.symmetric(vertical: 10), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10)), + ), + ), + ), + const SizedBox(width: 10), + OutlinedButton.icon( + onPressed: () async { + await Navigator.push( + context, + MaterialPageRoute( + builder: (_) => const TambahIbuPage())); + _fetchData(); + }, + icon: const Icon(Icons.add, + color: Colors.blueAccent, size: 18), + label: Text("Tambah", + style: GoogleFonts.poppins( + color: Colors.blueAccent, + fontSize: 12, + fontWeight: FontWeight.bold)), + style: OutlinedButton.styleFrom( + side: const BorderSide( + color: Colors.blueAccent, width: 1.5), + shape: const StadiumBorder(), + padding: const EdgeInsets.symmetric( + horizontal: 16, vertical: 10), + ), + ), + ], + ), + const SizedBox(height: 15), + Expanded( + child: _isLoading + ? const Center(child: CircularProgressIndicator()) + : _filteredData.isEmpty + ? Center( + child: Text( + "Tidak ada data ibu", + style: GoogleFonts.poppins( + fontSize: 12, + color: Colors.black, + ), + ), + ) + : ListView.builder( + itemCount: _paginatedData.length, + itemBuilder: (context, index) { + final item = _paginatedData[index]; + return Container( + margin: const EdgeInsets.only(bottom: 12), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12), + boxShadow: const [ + BoxShadow( + color: Colors.black12, + blurRadius: 8, + offset: Offset(0, 4)) + ], + ), + child: Padding( + padding: const EdgeInsets.all(14), + child: Column( + children: [ + _gridRow("No KK", item["no_kk"]), + _gridRow("NIK", item["nik"]), + _gridRow("Nama Ibu", item["nama"]), + _gridRow("Tempat, Tgl Lahir", + "${item["tempat_lahir"] ?? "-"}, ${formatTanggal(item["tanggal_lahir"])}"), + _gridRow( + "Gol. Darah", item["golongan_darah"]), + _gridRow("Agama", item["agama"]), + _gridRow("Desa", item["nama_desa"]), + _gridRow("Dusun", item["nama_dusun"]), + _gridRow("Alamat Detail", + item["alamat_detail"]), + _gridRow( + "Pendidikan", item["pendidikan"]), + _gridRow("Pekerjaan", item["pekerjaan"]), + _gridRow("Email", item["email"]), + _gridRow("No HP", item["no_hp"]), + _gridRow( + "Nama Suami", item["nama_suami"]), + const Divider(height: 25), + Row( + mainAxisAlignment: + MainAxisAlignment.end, + children: [ + _smallButton( + text: "Edit", + icon: Icons.edit, + color: Colors.orange, + onPressed: () async { + final result = + await Navigator.push( + context, + MaterialPageRoute( + builder: (_) => EditIbuPage( + data: item)), + ); + if (result == true) _fetchData(); + }, + ), + const SizedBox(width: 8), + _smallButton( + text: "Hapus", + icon: Icons.delete, + color: Colors.red, + onPressed: () => _confirmDelete( + item["id"].toString()), + ), + ], + ), + ], + ), + ), + ); + }, + ), + ), + Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(vertical: 8), + decoration: BoxDecoration( + border: + Border(top: BorderSide(color: Colors.grey.shade200))), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text("Halaman ${_currentPage + 1} dari $totalPages", + style: GoogleFonts.poppins( + fontSize: 12, fontWeight: FontWeight.w500)), + Row( + children: [ + IconButton( + icon: const Icon(Icons.chevron_left), + onPressed: _currentPage == 0 + ? null + : () => setState(() => _currentPage--), + ), + IconButton( + icon: const Icon(Icons.chevron_right), + onPressed: _currentPage >= totalPages - 1 + ? null + : () => setState(() => _currentPage++), + ), + ], + ), + ], + ), + ), + ], + ), + ), + ), + ); + } + + Widget _gridRow(String label, dynamic value) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 3), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: 120, + child: Text( + label, + style: GoogleFonts.poppins( + fontWeight: FontWeight.w600, + fontSize: 12, + color: Colors.black87), + ), + ), + Text(" : ", style: GoogleFonts.poppins(fontSize: 12)), + Expanded( + child: Text( + "${value ?? '-'}", + style: GoogleFonts.poppins(fontSize: 12, color: Colors.black), + ), + ), + ], + ), + ); + } + + Widget _smallButton({ + required String text, + required IconData icon, + required Color color, + required VoidCallback onPressed, + }) { + return OutlinedButton.icon( + onPressed: onPressed, + icon: Icon(icon, size: 14, color: color), + label: Text(text, + style: GoogleFonts.poppins( + fontSize: 12, fontWeight: FontWeight.bold, color: color)), + style: OutlinedButton.styleFrom( + side: BorderSide(color: color), + shape: const StadiumBorder(), + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 0), + minimumSize: const Size(0, 32), + ), + ); + } +} \ No newline at end of file diff --git a/lib/kader/data_kehadiran.dart b/lib/kader/data_kehadiran.dart new file mode 100644 index 0000000..b538a50 --- /dev/null +++ b/lib/kader/data_kehadiran.dart @@ -0,0 +1,565 @@ +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:http/http.dart' as http; + +import '../layout/main_layout.dart'; +import 'kader_drawer.dart'; +import '../pages/login_page.dart'; +import '../kader/crud_kehadiran/riwayat_kehadiran.dart'; +import '../kader/dashboard_kader.dart'; + +class DataKehadiranPosyanduPage extends StatefulWidget { + const DataKehadiranPosyanduPage({super.key}); + + @override + State createState() => + _DataKehadiranPosyanduPageState(); +} + +class _DataKehadiranPosyanduPageState extends State { + List> _data = []; + List> _filteredData = []; + bool _isLoading = true; + + int _currentPage = 0; + final int _rowsPerPage = 5; + + final Map _catatanController = {}; + final TextEditingController _searchController = TextEditingController(); + + int? _userId; + String? _dusunId; + + @override + void initState() { + super.initState(); + _initializeData(); + _searchController.addListener(_onSearch); + } + + Future _initializeData() async { + debugPrint("=== Memulai Inisialisasi Data ==="); + await _checkLogin(); + await _getUser(); + await _fetchData(); + } + + @override + void dispose() { + _searchController.dispose(); + _catatanController.forEach((_, c) => c.dispose()); + super.dispose(); + } + + String _formatTanggal(String? dateStr) { + if (dateStr == null || dateStr == "-" || dateStr.isEmpty) return "-"; + try { + DateTime dateTime = DateTime.parse(dateStr); + List months = [ + "Januari", + "Februari", + "Maret", + "April", + "Mei", + "Juni", + "Juli", + "Agustus", + "September", + "Oktober", + "November", + "Desember" + ]; + return "${dateTime.day} ${months[dateTime.month - 1]} ${dateTime.year}"; + } catch (e) { + return dateStr; + } + } + + Future _getUser() async { + try { + final prefs = await SharedPreferences.getInstance(); + String? idString = prefs.getString('id_user'); + dynamic rawDusunId = prefs.get('dusun_id'); + + if (mounted) { + setState(() { + _userId = int.tryParse(idString ?? ""); + _dusunId = rawDusunId?.toString(); + }); + } + } catch (e) { + debugPrint("DEBUG ERROR (SharedPrefs): $e"); + } + } + + void _onSearch() { + final query = _searchController.text.toLowerCase(); + setState(() { + _currentPage = 0; + _filteredData = _data.where((item) { + final nama = (item["nama_balita"] ?? "").toLowerCase(); + final ibu = (item["ibu_suami"] ?? "").toLowerCase(); + return nama.contains(query) || ibu.contains(query); + }).toList(); + }); + } + + Future _checkLogin() async { + final prefs = await SharedPreferences.getInstance(); + if (!(prefs.getBool('isLogin') ?? false)) { + if (!mounted) return; + Navigator.pushAndRemoveUntil( + context, + MaterialPageRoute(builder: (_) => const LoginPage(fromGuard: true)), + (route) => false); + } + } + + Future _fetchData() async { + if (_dusunId == null || _dusunId == "0" || _dusunId == "null") { + if (mounted) setState(() => _isLoading = false); + return; + } + + if (mounted) setState(() => _isLoading = true); + + try { + final url = + "http://ta.myhost.id/E31230549/mposyandu_api/kehadiran/get_kehadiran_balita.php?dusun_id=$_dusunId"; + final response = await http.get(Uri.parse(url)); + + if (response.statusCode == 200) { + final jsonData = json.decode(response.body); + if (jsonData["success"] == true) { + final List list = jsonData["data"] ?? []; + _data = list.map>((e) { + bool belumInput = + (e["status_hadir"] == "-" || e["status_hadir"] == null); + String idBalita = e["id_balita"].toString(); + _catatanController[idBalita] = TextEditingController( + text: (e["keterangan"] == "-" || e["keterangan"] == null) + ? "" + : e["keterangan"].toString()); + return { + ...e, + "isEditing": belumInput, + "sudahInput": !belumInput, + "status": belumInput ? null : e["status_hadir"].toString(), + }; + }).toList(); + _filteredData = List.from(_data); + } + } + } catch (e) { + debugPrint("ERROR FETCH: $e"); + } + if (mounted) setState(() => _isLoading = false); + } + + Future _saveData(Map item) async { + String idBalita = item["id_balita"].toString(); + try { + final response = await http.post( + Uri.parse( + "http://ta.myhost.id/E31230549/mposyandu_api/kehadiran/simpan_kehadiran_balita.php"), + body: { + "jadwal_id": item["id_jadwal"].toString(), + "balita_id": idBalita, + "status_hadir": item["status"] ?? "-", + "keterangan": _catatanController[idBalita]?.text ?? "", + "dicatat_oleh": _userId?.toString() ?? "0", + }, + ); + final result = json.decode(response.body); + return result["success"] == true; + } catch (e) { + return false; + } + } + + List> get _paginatedData { + final start = _currentPage * _rowsPerPage; + final end = (start + _rowsPerPage > _filteredData.length) + ? _filteredData.length + : start + _rowsPerPage; + return _filteredData.isEmpty ? [] : _filteredData.sublist(start, end); + } + + @override + Widget build(BuildContext context) { + final totalPages = _filteredData.isEmpty + ? 1 + : (_filteredData.length / _rowsPerPage).ceil(); + + return PopScope( + canPop: false, + onPopInvokedWithResult: (didPop, result) async { + if (didPop) return; + + Navigator.pushAndRemoveUntil( + context, + MaterialPageRoute( + builder: (_) => const DashboardKaderPage(), + ), + (route) => false, + ); + }, + child: MainLayout( + title: "", + drawer: const KaderDrawer(), + body: Padding( + padding: const EdgeInsets.all(16), + child: Column( + children: [ + Center( + child: Text("Data Kehadiran Posyandu", + style: GoogleFonts.poppins( + fontSize: 18, fontWeight: FontWeight.bold))), + const SizedBox(height: 14), + TextField( + controller: _searchController, + style: GoogleFonts.poppins(fontSize: 12), + decoration: InputDecoration( + hintText: "Cari nama balita / ibu...", + hintStyle: GoogleFonts.poppins(fontSize: 12), + prefixIcon: const Icon(Icons.search, size: 20), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10)), + isDense: true, + ), + ), + const SizedBox(height: 14), + Expanded( + child: _isLoading + ? const Center(child: CircularProgressIndicator()) + : ListView.builder( + itemCount: + _paginatedData.isEmpty ? 1 : _paginatedData.length, + itemBuilder: (context, index) { + if (_paginatedData.isEmpty) { + return Center( + child: Text("Data tidak ditemukan", + style: GoogleFonts.poppins(fontSize: 12))); + } + final item = _paginatedData[index]; + String idBalita = item["id_balita"].toString(); + bool isEditing = item["isEditing"] ?? false; + bool sudahInput = item["sudahInput"] ?? false; + + // LOGIKA STATUS LOLOS / BELUM LOLOS + String rawStatus = (item["status_balita"] ?? "") + .toString() + .toLowerCase(); + bool isLolos = rawStatus == "lolos"; + + // Warna Header (Hijau jika lolos, Merah jika belum lolos) + Color headerColor = isLolos + ? Colors.green.shade600 + : Colors.red.shade600; + + return Container( + margin: const EdgeInsets.only(bottom: 14), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(12), + color: Colors.white, + boxShadow: const [ + BoxShadow( + color: Colors.black12, + blurRadius: 8, + offset: Offset(0, 4)) + ], + ), + child: Column( + children: [ + Container( + width: double.infinity, + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: headerColor, + borderRadius: const BorderRadius.vertical( + top: Radius.circular(12))), + child: Row( + mainAxisAlignment: + MainAxisAlignment.spaceBetween, + children: [ + Expanded( + child: Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + Text(item["nama_balita"] ?? "-", + style: GoogleFonts.poppins( + color: Colors.white, + fontSize: 13, + fontWeight: + FontWeight.w600)), + Text( + "Nama Orang Tua: ${item["ibu_suami"] ?? "-"}", + style: GoogleFonts.poppins( + color: Colors.white, + fontSize: 11)), + ], + ), + ), + Container( + padding: const EdgeInsets.symmetric( + horizontal: 8, vertical: 4), + decoration: BoxDecoration( + color: + Colors.white.withOpacity(0.2), + borderRadius: + BorderRadius.circular(8), + border: Border.all( + color: Colors.white, + width: 0.5)), + child: Text( + isLolos ? "LOLOS" : "BELUM LOLOS", + style: GoogleFonts.poppins( + color: Colors.white, + fontSize: 10, + fontWeight: FontWeight.bold), + ), + ) + ], + ), + ), + Padding( + padding: const EdgeInsets.all(12), + child: Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + _row("Tanggal", + _formatTanggal(item["tanggal"])), + _row("Lokasi", item["lokasi"] ?? "-"), + _row("Jam", item["jam"] ?? "-"), + const SizedBox(height: 8), + Text("Status Kehadiran", + style: GoogleFonts.poppins( + fontWeight: FontWeight.w600, + fontSize: 12)), + Row( + children: [ + Radio( + value: "Hadir", + groupValue: item["status"], + onChanged: (isEditing && !isLolos) + ? (v) => setState( + () => item["status"] = v) + : null, + ), + Text("Hadir", + style: GoogleFonts.poppins( + fontSize: 12)), + Radio( + value: "Tidak Hadir", + groupValue: item["status"], + onChanged: (isEditing && !isLolos) + ? (v) => setState( + () => item["status"] = v) + : null, + ), + Text("Tidak Hadir", + style: GoogleFonts.poppins( + fontSize: 12)), + ], + ), + TextField( + controller: + _catatanController[idBalita], + enabled: isEditing && !isLolos, + style: + GoogleFonts.poppins(fontSize: 12), + maxLines: 2, + decoration: InputDecoration( + hintText: isLolos + ? "Terkunci (Lolos)" + : "Catatan...", + hintStyle: + GoogleFonts.poppins(fontSize: 12), + isDense: true, + border: OutlineInputBorder( + borderRadius: + BorderRadius.circular(8)), + filled: isLolos, + fillColor: isLolos + ? Colors.grey.shade100 + : Colors.transparent, + ), + ), + const SizedBox(height: 12), + Row( + children: [ + _smallButton( + icon: Icons.history, + text: "Riwayat", + onTap: () async { + await Navigator.push( + context, + MaterialPageRoute( + builder: (_) => + RiwayatKehadiranPage( + balitaId: + idBalita, + namaBalita: item[ + "nama_balita"]))); + _fetchData(); + }, + ), + _smallButton( + icon: Icons.edit, + text: "Edit", + onTap: (isLolos || + isEditing || + !sudahInput) + ? null + : () => setState(() => + item["isEditing"] = true), + ), + _smallButton( + icon: Icons.save, + text: "Simpan", + onTap: (isLolos || + !isEditing || + !sudahInput) + ? null + : () async { + final success = + await _saveData(item); + if (success) + setState(() => + item["isEditing"] = + false); + _showMsg(success + ? "Perubahan disimpan" + : "Gagal menyimpan"); + }, + ), + _smallButton( + icon: Icons.input, + text: "Input", + onTap: (isLolos || + sudahInput || + !isEditing) + ? null + : () async { + if (item["status"] == + null) { + _showMsg( + "Pilih status kehadiran dulu!"); + return; + } + final success = + await _saveData(item); + if (success) + setState(() { + item["isEditing"] = + false; + item["sudahInput"] = + true; + }); + _showMsg(success + ? "Data berhasil diinput" + : "Gagal input data"); + }, + ), + ], + ), + ], + ), + ), + ], + ), + ); + }, + ), + ), + // Pagination + Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(vertical: 8), + decoration: BoxDecoration( + border: + Border(top: BorderSide(color: Colors.grey.shade200))), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text("Halaman ${_currentPage + 1} dari $totalPages", + style: GoogleFonts.poppins( + fontSize: 12, fontWeight: FontWeight.w500)), + Row( + children: [ + IconButton( + icon: const Icon(Icons.chevron_left), + onPressed: _currentPage == 0 + ? null + : () => setState(() => _currentPage--), + ), + IconButton( + icon: const Icon(Icons.chevron_right), + onPressed: _currentPage >= totalPages - 1 + ? null + : () => setState(() => _currentPage++), + ), + ], + ), + ], + ), + ), + ], + ), + ), + ), + ); + } + + void _showMsg(String msg) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(msg, style: GoogleFonts.poppins(fontSize: 12)))); + } + + Widget _row(String label, String value) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 2), + child: Row( + children: [ + SizedBox( + width: 100, + child: Text(label, + style: GoogleFonts.poppins( + fontSize: 12, fontWeight: FontWeight.w600))), + Expanded( + child: + Text(": $value", style: GoogleFonts.poppins(fontSize: 12))), + ], + ), + ); + } + + Widget _smallButton( + {required IconData icon, + required String text, + required VoidCallback? onTap}) { + Color color = onTap == null ? Colors.grey : Colors.blueAccent; + return Expanded( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 2), + child: OutlinedButton.icon( + onPressed: onTap, + icon: Icon(icon, size: 14, color: color), + label: Text(text, + style: GoogleFonts.poppins( + fontSize: 9, fontWeight: FontWeight.bold, color: color)), + style: OutlinedButton.styleFrom( + side: BorderSide(color: color, width: 1), + shape: const StadiumBorder(), + padding: EdgeInsets.zero, + minimumSize: const Size(0, 32), + ), + ), + ), + ); + } +} diff --git a/lib/kader/data_kehamilan.dart b/lib/kader/data_kehamilan.dart new file mode 100644 index 0000000..8eda79e --- /dev/null +++ b/lib/kader/data_kehamilan.dart @@ -0,0 +1,479 @@ +import 'dart:async'; +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:http/http.dart' as http; + +import '../layout/main_layout.dart'; +import 'kader_drawer.dart'; +import '../pages/login_page.dart'; +import 'crud_ibu_hamil/tambah_ibu_hamil.dart'; +import 'crud_ibu_hamil/edit_ibu_hamil.dart'; +import '../kader/dashboard_kader.dart'; + +class DataIbuHamilPage extends StatefulWidget { + const DataIbuHamilPage({super.key}); + + @override + State createState() => _DataIbuHamilPageState(); +} + +class _DataIbuHamilPageState extends State { + List _data = []; + List _filteredData = []; + bool _isLoading = true; + + int _currentPage = 0; + final int _rowsPerPage = 5; + + final TextEditingController _searchC = TextEditingController(); + Timer? _debounce; + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addPostFrameCallback((_) { + _checkLogin(); + _fetchData(); + }); + _searchC.addListener(_onSearchChanged); + } + + @override + void dispose() { + _searchC.dispose(); + _debounce?.cancel(); + super.dispose(); + } + + // Fungsi untuk menghitung usia kehamilan berdasarkan HPHT + String _hitungUsiaKehamilan(String? hphtString) { + if (hphtString == null || + hphtString.isEmpty || + hphtString == "-" || + hphtString == "0000-00-00") return "-"; + + try { + DateTime hpht = DateTime.parse(hphtString); + DateTime sekarang = DateTime.now(); + + // Hitung selisih hari + int totalHari = sekarang.difference(hpht).inDays; + + if (totalHari < 0) return "Belum Hamil"; + + int minggu = totalHari ~/ 7; + int sisaHari = totalHari % 7; + + if (minggu >= 42) return "Sudah Waktunya Lahir"; + + return "$minggu Minggu $sisaHari Hari"; + } catch (e) { + return "-"; + } + } + + // Fungsi Helper untuk menentukan warna berdasarkan status + Color _getStatusColor(String status) { + switch (status.toLowerCase()) { + case 'keguguran': + return Colors.red; + case 'melahirkan': + return Colors.blue; + case 'aktif': + default: + return Colors.green; + } + } + + String _formatTanggalIndo(String? tanggal) { + if (tanggal == null || + tanggal.isEmpty || + tanggal == "-" || + tanggal == "0000-00-00") return "-"; + try { + DateTime dt = DateTime.parse(tanggal); + List bulanIndo = [ + "", + "Januari", + "Februari", + "Maret", + "April", + "Mei", + "Juni", + "Juli", + "Agustus", + "September", + "Oktober", + "November", + "Desember" + ]; + return "${dt.day.toString().padLeft(2, '0')} ${bulanIndo[dt.month]} ${dt.year}"; + } catch (e) { + return tanggal; + } + } + + void _onSearchChanged() { + if (_debounce?.isActive ?? false) _debounce!.cancel(); + _debounce = Timer(const Duration(milliseconds: 400), () { + final keyword = _searchC.text.toLowerCase(); + setState(() { + _currentPage = 0; + _filteredData = _data.where((item) { + final namaIbu = (item["nama_ibu"] ?? "").toString().toLowerCase(); + final status = (item["status"] ?? "").toString().toLowerCase(); + return namaIbu.contains(keyword) || status.contains(keyword); + }).toList(); + }); + }); + } + + Future _checkLogin() async { + final prefs = await SharedPreferences.getInstance(); + final isLogin = prefs.getBool('isLogin') ?? false; + if (!isLogin) { + if (!mounted) return; + Navigator.pushAndRemoveUntil( + context, + MaterialPageRoute(builder: (_) => const LoginPage(fromGuard: true)), + (route) => false, + ); + } + } + + Future _fetchData() async { + setState(() => _isLoading = true); + try { + final prefs = await SharedPreferences.getInstance(); + final rawDusunId = prefs.get('dusun_id'); + String dusunId = rawDusunId?.toString() ?? ""; + final url = Uri.parse( + "http://ta.myhost.id/E31230549/mposyandu_api/ibu_hamil/get_ibu_hamil.php?dusun_id=$dusunId"); + final response = await http.get(url); + final jsonData = json.decode(response.body); + if (jsonData["success"] == true) { + setState(() { + _data = jsonData["data"]; + _filteredData = _data; + _isLoading = false; + }); + } else { + setState(() { + _data = []; + _filteredData = []; + _isLoading = false; + }); + } + } catch (e) { + debugPrint("ERROR GET IBU HAMIL: $e"); + setState(() => _isLoading = false); + } + } + + Future _deleteData(String id) async { + try { + final url = Uri.parse( + "http://ta.myhost.id/E31230549/mposyandu_api/ibu_hamil/hapus_ibu_hamil.php"); + final response = await http.post(url, body: {"id": id}); + final data = json.decode(response.body); + if (data["success"] == true) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text("Data berhasil dihapus"))); + _fetchData(); + } + } catch (e) { + debugPrint("Gagal hapus: $e"); + } + } + + List get _paginatedData { + final start = _currentPage * _rowsPerPage; + final end = start + _rowsPerPage; + if (start >= _filteredData.length) return []; + return _filteredData.sublist( + start, end > _filteredData.length ? _filteredData.length : end); + } + + @override + Widget build(BuildContext context) { + final totalPages = _filteredData.isEmpty + ? 1 + : (_filteredData.length / _rowsPerPage).ceil(); + + return PopScope( + canPop: false, + onPopInvokedWithResult: (didPop, result) { + if (didPop) return; + Navigator.pushAndRemoveUntil( + context, + MaterialPageRoute(builder: (_) => const DashboardKaderPage()), + (route) => false, + ); + }, + child: MainLayout( + title: "", + drawer: const KaderDrawer(), + body: Padding( + padding: const EdgeInsets.all(16), + child: Column( + children: [ + Center( + child: Text("Data Ibu Hamil", + style: GoogleFonts.poppins( + fontSize: 18, fontWeight: FontWeight.bold)), + ), + const SizedBox(height: 16), + Row( + children: [ + Expanded( + child: TextField( + controller: _searchC, + decoration: InputDecoration( + hintText: "Cari nama...", + prefixIcon: const Icon(Icons.search), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10)), + ), + ), + ), + const SizedBox(width: 10), + OutlinedButton.icon( + onPressed: () async { + await Navigator.push( + context, + MaterialPageRoute( + builder: (_) => const TambahIbuHamilPage())); + _fetchData(); + }, + icon: const Icon(Icons.add, size: 18), + label: const Text("Tambah"), + style: OutlinedButton.styleFrom( + foregroundColor: Colors.blue, + side: const BorderSide(color: Colors.blue), + shape: const StadiumBorder(), + ), + ), + ], + ), + const SizedBox(height: 20), + Expanded( + child: _isLoading + ? const Center(child: CircularProgressIndicator()) + : _filteredData.isEmpty + ? Center( + child: Text( + "Tidak Ada Data Ibu Hamil", + style: GoogleFonts.poppins( + fontSize: 16, + color: Colors.black, + fontWeight: FontWeight.w500, + ), + ), + ) + : ListView.builder( + itemCount: _paginatedData.length, + itemBuilder: (context, index) { + final item = _paginatedData[index]; + final String status = item["status"] ?? "aktif"; + + Color headerColor = _getStatusColor(status); + + return Container( + margin: const EdgeInsets.only(bottom: 14), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12), + boxShadow: const [ + BoxShadow( + color: Colors.black12, blurRadius: 6) + ], + ), + child: Column( + children: [ + Container( + width: double.infinity, + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: headerColor, + borderRadius: const BorderRadius.only( + topLeft: Radius.circular(12), + topRight: Radius.circular(12)), + ), + child: Row( + mainAxisAlignment: + MainAxisAlignment.spaceBetween, + children: [ + Text(item["nama_ibu"] ?? "-", + style: GoogleFonts.poppins( + fontSize: 14, + fontWeight: FontWeight.bold, + color: Colors.white)), + Text(status.toUpperCase(), + style: GoogleFonts.poppins( + fontSize: 10, + fontWeight: FontWeight.w800, + color: Colors.white)), + ], + ), + ), + Padding( + padding: const EdgeInsets.all(12), + child: Column( + children: [ + _row("Nama Suami", + item["nama_suami"] ?? "-"), + _row("HPHT", + _formatTanggalIndo(item["hpht"])), + // MENAMPILKAN USIA KEHAMILAN YANG DIHITUNG OTOMATIS + _row( + "Usia Kehamilan", + _hitungUsiaKehamilan( + item["hpht"])), + _row("HPL", + _formatTanggalIndo(item["hpl"])), + _row( + "Persalinan Sblmnya", + _formatTanggalIndo(item[ + "tanggal_persalinan_sebelumnya"])), + _row( + "Gravida (G)", + item["gravida"]?.toString() ?? + "-"), + _row("Para (P)", + item["para"]?.toString() ?? "-"), + _row( + "Abortus (A)", + item["abortus"]?.toString() ?? + "-"), + _row("Hidup", + item["hidup"]?.toString() ?? "-"), + _row("Pembiayaan", + item["pembiayaan"] ?? "-"), + const Divider(), + Row( + mainAxisAlignment: + MainAxisAlignment.end, + children: [ + _smallButton( + text: "Edit", + icon: Icons.edit, + color: Colors.orange, + onPressed: () async { + final res = await Navigator.push( + context, + MaterialPageRoute( + builder: (_) => + EditIbuHamilPage( + data: item))); + if (res == true) _fetchData(); + }, + ), + const SizedBox(width: 8), + _smallButton( + text: "Hapus", + icon: Icons.delete, + color: Colors.red, + onPressed: () => + _showDeleteDialog( + item["id"].toString()), + ), + ], + ) + ], + ), + ) + ], + ), + ); + }, + ), + ), + if (_filteredData.isNotEmpty) _buildPagination(totalPages), + ], + ), + ), + ), + ); + } + + void _showDeleteDialog(String id) { + showDialog( + context: context, + builder: (_) => AlertDialog( + title: const Text("Hapus Data?"), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text("Batal")), + TextButton( + onPressed: () { + Navigator.pop(context); + _deleteData(id); + }, + child: const Text("Hapus", style: TextStyle(color: Colors.red))), + ], + ), + ); + } + + Widget _buildPagination(int totalPages) { + return Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text("Hal ${_currentPage + 1} dari $totalPages", + style: GoogleFonts.poppins(fontSize: 12)), + Row( + children: [ + IconButton( + icon: const Icon(Icons.chevron_left), + onPressed: _currentPage == 0 + ? null + : () => setState(() => _currentPage--)), + IconButton( + icon: const Icon(Icons.chevron_right), + onPressed: _currentPage >= totalPages - 1 + ? null + : () => setState(() => _currentPage++)), + ], + ), + ], + ); + } + + Widget _smallButton( + {required String text, + required IconData icon, + required Color color, + required VoidCallback onPressed}) { + return OutlinedButton.icon( + onPressed: onPressed, + icon: Icon(icon, size: 14, color: color), + label: Text(text, + style: GoogleFonts.poppins( + fontSize: 11, fontWeight: FontWeight.bold, color: color)), + style: OutlinedButton.styleFrom( + side: BorderSide(color: color), shape: const StadiumBorder()), + ); + } + + Widget _row(String label, String value) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 2), + child: Row( + children: [ + SizedBox( + width: 130, + child: Text(label, + style: GoogleFonts.poppins( + fontSize: 12, fontWeight: FontWeight.w600))), + const Text(" : "), + Expanded( + child: Text(value, style: GoogleFonts.poppins(fontSize: 12))), + ], + ), + ); + } +} diff --git a/lib/kader/data_pemeriksaan.dart b/lib/kader/data_pemeriksaan.dart new file mode 100644 index 0000000..5f9f579 --- /dev/null +++ b/lib/kader/data_pemeriksaan.dart @@ -0,0 +1,649 @@ +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:http/http.dart' as http; +import 'dart:convert'; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../layout/main_layout.dart'; +import 'kader_drawer.dart'; +import '../pages/login_page.dart'; +import '../kader/crud_pemeriksaan/tambah_pemeriksaan.dart'; +import '../kader/crud_pemeriksaan/riwayat_pemeriksaan_balita.dart'; +import '../kader/dashboard_kader.dart'; + +class DataPemeriksaanBalitaPage extends StatefulWidget { + const DataPemeriksaanBalitaPage({super.key}); + + @override + State createState() => + _DataPemeriksaanBalitaPageState(); +} + +class _DataPemeriksaanBalitaPageState extends State { + List> _dataBalita = []; + List> _allDataBalita = []; + + bool _loading = true; + bool _checkingLogin = true; + String? _dusunId; + + int _currentPage = 0; + final int _rowsPerPage = 5; + + String _formatTanggalIndo(String? tanggal) { + if (tanggal == null || tanggal.isEmpty || tanggal == "-") return "-"; + try { + DateTime dt = DateTime.parse(tanggal); + List bulanIndo = [ + "", + "Januari", + "Februari", + "Maret", + "April", + "Mei", + "Juni", + "Juli", + "Agustus", + "September", + "Oktober", + "November", + "Desember" + ]; + String hari = dt.day.toString().padLeft(2, '0'); + String bulan = bulanIndo[dt.month]; + String tahun = dt.year.toString(); + return "$hari $bulan $tahun"; + } catch (e) { + return tanggal; + } + } + + String hitungUsia(String tanggalLahir) { + try { + DateTime lahir = DateTime.parse(tanggalLahir); + DateTime now = DateTime.now(); + int tahun = now.year - lahir.year; + int bulan = now.month - lahir.month; + int hari = now.day - lahir.day; + if (hari < 0) { + bulan -= 1; + hari += DateTime(now.year, now.month, 0).day; + } + if (bulan < 0) { + tahun -= 1; + bulan += 12; + } + return "$tahun thn $bulan bln $hari hr"; + } catch (e) { + return "-"; + } + } + + @override + void initState() { + super.initState(); + _checkLogin(); + } + + Future _checkLogin() async { + try { + final prefs = await SharedPreferences.getInstance(); + final isLogin = prefs.getBool('isLogin') ?? false; + + if (!isLogin) { + if (!mounted) return; + Navigator.pushReplacement( + context, + MaterialPageRoute(builder: (_) => const LoginPage()), + ); + return; + } + + dynamic rawDusunId = prefs.get('dusun_id'); + + if (mounted) { + setState(() { + _dusunId = rawDusunId?.toString(); + _checkingLogin = false; + }); + } + + _fetchDataBalita(); + } catch (e) { + debugPrint("Error Check Login: $e"); + if (mounted) setState(() => _checkingLogin = false); + } + } + + Future _fetchDataBalita() async { + if (_dusunId == null || _dusunId == "null" || _dusunId == "0") { + setState(() => _loading = false); + return; + } + + setState(() => _loading = true); + + final url = Uri.parse( + 'http://ta.myhost.id/E31230549/mposyandu_api/pemeriksaan_balita/get_pemeriksaan_balita.php?dusun_id=$_dusunId', + ); + + try { + final response = await http.get(url).timeout(const Duration(seconds: 10)); + if (response.statusCode == 200) { + final jsonData = json.decode(response.body); + if (jsonData["success"] == true) { + final List> data = + List>.from(jsonData["data"]); + setState(() { + for (var item in data) { + item["jk_formatted"] = item["jenis_kelamin"] == "L" + ? "Laki-Laki" + : (item["jenis_kelamin"] == "P" ? "Perempuan" : "-"); + + item["ibu_suami"] = + "${item["nama_ibu"] ?? '-'} (${item["nama_suami"] ?? '-'})"; + + if (item["tanggal_lahir"] != null && + item["tanggal_lahir"].toString().isNotEmpty && + item["tanggal_lahir"] != "-") { + item["usia_formatted"] = + hitungUsia(item["tanggal_lahir"].toString()); + item["tgl_lahir_indo"] = + _formatTanggalIndo(item["tanggal_lahir"].toString()); + } else { + item["usia_formatted"] = "-"; + item["tgl_lahir_indo"] = "-"; + } + + item["bb_formatted"] = "${item["bb"] ?? '-'} kg"; + item["tb_formatted"] = "${item["tb"] ?? '-'} cm"; + item["lk_formatted"] = "${item["lk"] ?? '-'} cm"; + } + _allDataBalita = data; + _dataBalita = data; + _loading = false; + }); + } else { + setState(() { + _dataBalita = []; + _loading = false; + }); + } + } else { + setState(() => _loading = false); + } + } catch (e) { + debugPrint("ERROR FETCH: $e"); + setState(() => _loading = false); + } + } + + List> get _paginatedData { + if (_dataBalita.isEmpty) return []; + final start = _currentPage * _rowsPerPage; + final end = start + _rowsPerPage; + if (start >= _dataBalita.length) return []; + return _dataBalita.sublist( + start, + end > _dataBalita.length ? _dataBalita.length : end, + ); + } + + @override + Widget build(BuildContext context) { + if (_checkingLogin) { + return const Scaffold( + body: Center(child: CircularProgressIndicator()), + ); + } + + final totalPages = + _dataBalita.isEmpty ? 1 : (_dataBalita.length / _rowsPerPage).ceil(); + + return PopScope( + canPop: false, + onPopInvokedWithResult: (didPop, result) async { + if (didPop) return; + Navigator.pushAndRemoveUntil( + context, + MaterialPageRoute(builder: (_) => const DashboardKaderPage()), + (route) => false, + ); + }, + child: MainLayout( + title: "", + drawer: const KaderDrawer(), + body: _loading + ? const Center(child: CircularProgressIndicator()) + : Padding( + padding: const EdgeInsets.all(16), + child: Column( + children: [ + Center( + child: Text( + "Data Pemeriksaan Balita", + style: GoogleFonts.poppins( + fontSize: 18, + fontWeight: FontWeight.bold, + color: Colors.black87, + ), + ), + ), + const SizedBox(height: 12), + TextField( + style: GoogleFonts.poppins(fontSize: 12), + decoration: InputDecoration( + hintText: "Cari nama balita...", + hintStyle: GoogleFonts.poppins(fontSize: 12), + prefixIcon: const Icon(Icons.search, size: 20), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + ), + contentPadding: const EdgeInsets.symmetric(vertical: 8), + ), + onChanged: (value) { + setState(() { + _dataBalita = _allDataBalita + .where((b) => (b['nama_balita'] ?? '') + .toLowerCase() + .contains(value.toLowerCase())) + .toList(); + _currentPage = 0; + }); + }, + ), + const SizedBox(height: 15), + Expanded( + child: _dataBalita.isEmpty + ? Center( + child: Text( + "Tidak ada data pemeriksaan", + style: GoogleFonts.poppins(fontSize: 12), + ), + ) + : ListView.builder( + itemCount: _paginatedData.length, + itemBuilder: (context, index) { + final balita = _paginatedData[index]; + bool isLolos = balita["status"] == 'lolos'; + String? statusHadir = balita["status_hadir"]; + + return Container( + margin: + const EdgeInsets.symmetric(vertical: 8), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(14), + boxShadow: const [ + BoxShadow( + color: Colors.black12, + blurRadius: 8, + offset: Offset(0, 4), + ), + ], + ), + child: Column( + children: [ + Container( + width: double.infinity, + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: isLolos + ? Colors.green + : Colors.blueAccent, + borderRadius: + const BorderRadius.vertical( + top: Radius.circular(14), + ), + ), + child: Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: + MainAxisAlignment + .spaceBetween, + children: [ + Expanded( + child: Text( + balita["nama_balita"] ?? + "-", + style: GoogleFonts.poppins( + color: Colors.white, + fontWeight: + FontWeight.bold, + fontSize: 14, + ), + ), + ), + Row( + children: [ + // Badge Status Hadir (Hanya jika belum Lolos) + if (!isLolos && + statusHadir != null && + statusHadir != "-") + Container( + margin: const EdgeInsets + .only(right: 5), + padding: + const EdgeInsets + .symmetric( + horizontal: 8, + vertical: 2), + decoration: + BoxDecoration( + color: statusHadir == + 'Hadir' + ? Colors.green + : Colors.red, + borderRadius: + BorderRadius + .circular(10), + border: Border.all( + color: + Colors.white, + width: 1), + ), + child: Text( + statusHadir + .toUpperCase(), + style: GoogleFonts + .poppins( + fontSize: 10, + fontWeight: + FontWeight.bold, + color: Colors.white, + ), + ), + ), + // Badge Lolos + if (isLolos) + Container( + padding: + const EdgeInsets + .symmetric( + horizontal: 8, + vertical: 2), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: + BorderRadius + .circular( + 10)), + child: Text("LOLOS", + style: GoogleFonts + .poppins( + fontSize: + 10, + fontWeight: + FontWeight + .bold, + color: Colors + .green)), + ), + ], + ) + ], + ), + const SizedBox(height: 6), + _rowWhite("Orang Tua", + balita["ibu_suami"]), + _rowWhite("Jenis Kelamin", + balita["jk_formatted"]), + _rowWhite("Tgl Lahir", + balita["tgl_lahir_indo"]), + _rowWhite("Usia", + balita["usia_formatted"]), + _rowWhite( + "Desa", balita["nama_desa"]), + _rowWhite( + "Dusun", balita["nama_dusun"]), + _rowWhite("Alamat", + balita["alamat_detail"]), + ], + ), + ), + Container( + width: double.infinity, + padding: const EdgeInsets.all(12), + child: Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + Text( + "Riwayat Pemeriksaan Terakhir", + style: GoogleFonts.poppins( + fontWeight: FontWeight.bold, + fontSize: 12, + color: Colors.black87, + ), + ), + const Divider(), + _riwayatList(balita), + const SizedBox(height: 12), + Row( + children: [ + Expanded( + child: OutlinedButton.icon( + onPressed: () async { + if (isLolos) { + ScaffoldMessenger.of( + context) + .showSnackBar( + const SnackBar( + content: Text( + "Balita ini sudah lolos pemeriksaan, penginputan dinonaktifkan."), + backgroundColor: + Colors.orange, + ), + ); + return; + } + await Navigator.push( + context, + MaterialPageRoute( + builder: (_) => + TambahPemeriksaanBalitaPage( + balita: + balita), + ), + ); + _fetchDataBalita(); + }, + icon: const Icon(Icons.add, + size: 16), + label: const Text("Input"), + style: OutlinedButton + .styleFrom( + foregroundColor: isLolos + ? Colors.grey + : Colors.blue, + side: BorderSide( + color: isLolos + ? Colors.grey + : Colors.blue, + width: 1.5), + shape: + const StadiumBorder(), + textStyle: + GoogleFonts.poppins( + fontSize: 12, + fontWeight: + FontWeight + .bold), + padding: const EdgeInsets + .symmetric( + vertical: 10), + ), + ), + ), + const SizedBox(width: 10), + Expanded( + child: OutlinedButton.icon( + onPressed: () async { + await Navigator.push( + context, + MaterialPageRoute( + builder: (_) => + RiwayatPemeriksaanBalitaPage( + idBalita: + int.tryParse( + balita["id_balita"].toString()) ?? + 0), + ), + ); + _fetchDataBalita(); + }, + icon: const Icon( + Icons.history, + size: 16), + label: + const Text("Riwayat"), + style: OutlinedButton + .styleFrom( + foregroundColor: + Colors.deepPurple, + side: const BorderSide( + color: + Colors.deepPurple, + width: 1.5), + shape: + const StadiumBorder(), + textStyle: + GoogleFonts.poppins( + fontSize: 12, + fontWeight: + FontWeight + .bold), + padding: const EdgeInsets + .symmetric( + vertical: 10), + ), + ), + ), + ], + ), + ], + ), + ), + ], + ), + ); + }, + ), + ), + // PAGINATION + Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(vertical: 10), + decoration: BoxDecoration( + border: Border( + top: BorderSide(color: Colors.grey.shade200))), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text("Halaman ${_currentPage + 1} dari $totalPages", + style: GoogleFonts.poppins(fontSize: 12)), + Row( + children: [ + IconButton( + icon: + const Icon(Icons.chevron_left, size: 20), + onPressed: _currentPage == 0 + ? null + : () => setState(() => _currentPage--)), + IconButton( + icon: + const Icon(Icons.chevron_right, size: 20), + onPressed: _currentPage >= totalPages - 1 + ? null + : () => setState(() => _currentPage++)), + ], + ), + ], + ), + ), + ], + ), + ), + ), + ); + } + + Widget _rowWhite(String label, dynamic value) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 2), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: 110, + child: Text( + label, + style: GoogleFonts.poppins( + fontSize: 12, + fontWeight: FontWeight.w600, + color: Colors.white), + ), + ), + const Text(" : ", + style: + TextStyle(color: Colors.white, fontWeight: FontWeight.bold)), + Expanded( + child: Text( + "${value ?? '-'}", + style: GoogleFonts.poppins( + fontSize: 12, + color: Colors.white, + fontWeight: FontWeight.w400), + ), + ), + ], + ), + ); + } + + Widget _riwayatList(Map balita) { + final items = { + "Tgl Periksa": _formatTanggalIndo(balita["tanggal_pemeriksaan"]), + "Berat Badan": balita["bb_formatted"], + "Tinggi Badan": balita["tb_formatted"], + "Lingkar Kepala": balita["lk_formatted"], + "Imunisasi": balita["imunisasi"], + "Vitamin A": balita["vitamin_a"], + "PMT": balita["pmt"], + "Catatan": balita["catatan"], + }; + + return Column( + children: items.entries.map((entry) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 2), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: 110, + child: Text( + entry.key, + style: GoogleFonts.poppins( + fontSize: 12, + fontWeight: FontWeight.w600, + color: Colors.black87), + ), + ), + const Text(" : ", style: TextStyle(fontWeight: FontWeight.bold)), + Expanded( + child: Text( + "${entry.value ?? '-'}", + style: GoogleFonts.poppins(fontSize: 12, color: Colors.black), + ), + ), + ], + ), + ); + }).toList(), + ); + } +} diff --git a/lib/kader/kader_drawer.dart b/lib/kader/kader_drawer.dart new file mode 100644 index 0000000..963855a --- /dev/null +++ b/lib/kader/kader_drawer.dart @@ -0,0 +1,271 @@ +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import '../layout/main_layout.dart'; + +class KaderDrawer extends StatefulWidget { + const KaderDrawer({super.key}); + + @override + State createState() => _KaderDrawerState(); +} + +class _KaderDrawerState extends State { + String? fotoUser; + String namaUser = "Kader"; + + @override + void initState() { + super.initState(); + _loadUserData(); + } + + // Fungsi untuk mengambil data foto dan nama dari SharedPreferences + Future _loadUserData() async { + final prefs = await SharedPreferences.getInstance(); + setState(() { + fotoUser = prefs.getString('foto'); + namaUser = prefs.getString('nama') ?? "Kader"; + }); + } + + @override + Widget build(BuildContext context) { + return Drawer( + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.only( + topRight: Radius.circular(20), + bottomRight: Radius.circular(20), + ), + ), + child: Column( + children: [ + // ================= HEADER ================= + Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(vertical: 40), + decoration: const BoxDecoration( + color: MainLayout.mainColor, + borderRadius: BorderRadius.only( + topRight: Radius.circular(20), + ), + ), + child: InkWell( + onTap: () { + Navigator.pushReplacementNamed(context, '/profile-kader'); + }, + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + CircleAvatar( + radius: 40, + backgroundColor: Colors.white, + child: CircleAvatar( + radius: 37, + backgroundColor: Colors.blue.shade100, + backgroundImage: (fotoUser != null && + fotoUser!.isNotEmpty) + ? NetworkImage( + "http://ta.myhost.id/E31230549/mposyandu_api/uploads/$fotoUser") + : null, + child: (fotoUser == null || fotoUser!.isEmpty) + ? const Icon( + Icons.person, + size: 40, + color: MainLayout.mainColor, + ) + : null, + ), + ), + const SizedBox(height: 12), + Text( + namaUser, + style: GoogleFonts.poppins( + color: Colors.white, + fontSize: 16, + fontWeight: FontWeight.bold, + ), + ), + Text( + "Lihat Profil", + style: GoogleFonts.poppins( + color: Colors.white70, + fontSize: 12, + ), + ), + ], + ), + ), + ), + + // ================= MENU ================= + Expanded( + child: ListView( + padding: EdgeInsets.zero, + children: [ + _drawerItem( + context, + icon: Icons.home, + text: "Home", + route: '/dashboard-kader', + ), + Theme( + // Menghilangkan garis pemisah otomatis pada ExpansionTile + data: Theme.of(context) + .copyWith(dividerColor: Colors.transparent), + child: ExpansionTile( + shape: const Border(), // Menghilangkan border saat expanded + leading: const Icon( + Icons.folder, + color: MainLayout.mainColor, + ), + title: Text( + "Pendaftaran", + style: GoogleFonts.poppins( + color: Colors.black, + fontWeight: FontWeight.w500, + fontSize: 14, + ), + ), + children: [ + _subDrawerItem( + context, + icon: Icons.woman, + text: "Daftar Data Ibu", + route: '/data-ibu', + ), + _subDrawerItem( + context, + icon: Icons.pregnant_woman, + text: "Daftar Data Ibu Hamil", + route: '/data-kehamilan', + ), + _subDrawerItem( + context, + icon: Icons.child_care, + text: "Daftar Data Balita", + route: '/data-balita', + ), + ], + ), + ), + _drawerItem( + context, + icon: Icons.people, + text: "Kehadiran Posyandu", + route: '/data-kehadiran-posyandu', + ), + _drawerItem( + context, + icon: Icons.add_circle, + text: "Pemeriksaan Posyandu", + route: '/data-pemeriksaan-balita', + ), + ], + ), + ), + + // LOGOUT + ListTile( + leading: const Icon( + Icons.logout, + color: MainLayout.mainColor, + ), + title: Text( + "Logout", + style: GoogleFonts.poppins( + color: Colors.black, + fontWeight: FontWeight.w500, + fontSize: 14, + ), + ), + onTap: () => _logout(context), + ), + + const SizedBox(height: 10), + ], + ), + ); + } + + // ================= LOGOUT FUNCTION ================= + static Future _logout(BuildContext context) async { + final prefs = await SharedPreferences.getInstance(); + + await prefs.remove('isLogin'); + await prefs.remove('id_user'); + await prefs.remove('role'); + await prefs.remove('nama'); + await prefs.remove('email'); + await prefs.remove('no_hp'); + await prefs.remove('password'); + await prefs.remove('foto'); + await prefs.remove('desa_id'); + await prefs.remove('dusun_id'); + await prefs.remove('nama_desa'); + await prefs.remove('nama_dusun'); + + if (!context.mounted) return; + + Navigator.pushNamedAndRemoveUntil( + context, + '/login', + (route) => false, + ); + } + + // ================= DRAWER ITEM ================= + Widget _drawerItem( + BuildContext context, { + required IconData icon, + required String text, + required String route, + }) { + return ListTile( + leading: Icon( + icon, + color: MainLayout.mainColor, + ), + title: Text( + text, + style: GoogleFonts.poppins( + color: Colors.black, + fontWeight: FontWeight.w500, + fontSize: 14, + ), + ), + onTap: () { + Navigator.pushReplacementNamed(context, route); + }, + ); + } + + // ================= SUB MENU ================= + Widget _subDrawerItem( + BuildContext context, { + required IconData icon, + required String text, + required String route, + }) { + return Padding( + padding: const EdgeInsets.only(left: 30), + child: ListTile( + leading: Icon( + icon, + color: MainLayout.mainColor, + size: 20, + ), + title: Text( + text, + style: GoogleFonts.poppins( + color: Colors.black, + fontSize: 13, + ), + ), + onTap: () { + Navigator.pushReplacementNamed(context, route); + }, + ), + ); + } +} diff --git a/lib/kader/profile_kader.dart b/lib/kader/profile_kader.dart new file mode 100644 index 0000000..ee6d07e --- /dev/null +++ b/lib/kader/profile_kader.dart @@ -0,0 +1,482 @@ +import 'dart:io'; +import 'dart:convert'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:image_picker/image_picker.dart'; +import 'package:http/http.dart' as http; +import '../pages/login_page.dart'; +import '../kader/dashboard_kader.dart'; + +class ProfileKaderPage extends StatefulWidget { + const ProfileKaderPage({super.key}); + + @override + State createState() => _ProfileKaderPageState(); +} + +class _ProfileKaderPageState extends State { + final TextEditingController namaC = TextEditingController(); + final TextEditingController emailC = TextEditingController(); + final TextEditingController passwordC = TextEditingController(); + final TextEditingController roleC = TextEditingController(); + final TextEditingController desaIdC = TextEditingController(); + final TextEditingController dusuIdC = TextEditingController(); + final TextEditingController noHpC = TextEditingController(); + final TextEditingController statusC = TextEditingController(); + + String? idUser; + String? fotoUser; + XFile? _pickedFile; + bool _obscurePassword = true; + bool isEditMode = false; + + @override + void initState() { + super.initState(); + _loadUserData(); + } + + @override + void dispose() { + namaC.dispose(); + emailC.dispose(); + passwordC.dispose(); + roleC.dispose(); + desaIdC.dispose(); + dusuIdC.dispose(); + noHpC.dispose(); + statusC.dispose(); + super.dispose(); + } + + Future _loadUserData() async { + final prefs = await SharedPreferences.getInstance(); + final isLogin = prefs.getBool('isLogin') ?? false; + + if (!isLogin) { + if (!mounted) return; + Navigator.pushAndRemoveUntil( + context, + MaterialPageRoute(builder: (_) => const LoginPage(fromGuard: true)), + (route) => false, + ); + return; + } + + setState(() { + idUser = prefs.getString('id_user') ?? ""; + namaC.text = prefs.getString('nama') ?? ""; + emailC.text = prefs.getString('email') ?? ""; + passwordC.text = prefs.getString('password') ?? ""; + roleC.text = (prefs.getString('role') ?? "Kader").toLowerCase(); + desaIdC.text = prefs.getString('nama_desa') ?? "-"; + dusuIdC.text = prefs.getString('nama_dusun') ?? "-"; + + String savedNoHp = prefs.getString('no_hp') ?? ""; + noHpC.text = (savedNoHp.isEmpty || savedNoHp == "-") ? "-" : savedNoHp; + + statusC.text = prefs.getString('status_aktif') ?? "Aktif"; + fotoUser = prefs.getString('foto'); + }); + } + + void _backToDashboard() { + Navigator.pushAndRemoveUntil( + context, + MaterialPageRoute(builder: (context) => const DashboardKaderPage()), + (route) => false, + ); + } + + void _showEditWarning() { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text("Klik tombol edit di bawah untuk mengubah foto."), + backgroundColor: Colors.red, + ), + ); + } + + Future _pickImage() async { + if (!isEditMode) { + _showEditWarning(); + return; + } + final ImagePicker picker = ImagePicker(); + final XFile? image = await picker.pickImage(source: ImageSource.gallery); + + if (image != null) { + setState(() { + _pickedFile = image; + }); + } + } + + void _removeImage() { + if (!isEditMode) { + _showEditWarning(); + return; + } + setState(() { + _pickedFile = null; + fotoUser = ""; + }); + } + + void _enableEdit() { + setState(() { + isEditMode = true; + }); + } + + bool _validatePassword(String value) { + String pattern = r'^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6}$'; + RegExp regExp = RegExp(pattern); + return regExp.hasMatch(value); + } + + bool _validateNoHp(String value) { + String pattern = r'^[0-9]{10,13}$'; + RegExp regExp = RegExp(pattern); + return regExp.hasMatch(value); + } + + void _saveProfile() async { + if (!isEditMode) return; + + if (!_validateNoHp(noHpC.text)) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text("No. HP harus berupa angka dan berjumlah 10-13 digit!"), + backgroundColor: Colors.red, + ), + ); + return; + } + + if (!_validatePassword(passwordC.text)) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text("Password harus 6 digit (kombinasi huruf & angka)!"), + backgroundColor: Colors.red, + ), + ); + return; + } + + try { + var request = http.MultipartRequest( + 'POST', + Uri.parse( + "http://ta.myhost.id/E31230549/mposyandu_api/users/update_profile_kader.php"), + ); + + request.fields['id_user'] = idUser ?? ""; + request.fields['nama'] = namaC.text; + request.fields['email'] = emailC.text; + request.fields['password'] = passwordC.text; + request.fields['no_hp'] = noHpC.text; + request.fields['foto_lama'] = fotoUser ?? ""; + + if (_pickedFile != null) { + Uint8List data = await _pickedFile!.readAsBytes(); + request.files.add(http.MultipartFile.fromBytes( + 'foto', + data, + filename: _pickedFile!.name, + )); + } + + var response = await request.send(); + var responseData = await response.stream.bytesToString(); + var result = json.decode(responseData); + + if (result['status'] == 'success') { + final prefs = await SharedPreferences.getInstance(); + + await prefs.setString('nama', namaC.text); + await prefs.setString('email', emailC.text); + await prefs.setString('password', passwordC.text); + await prefs.setString('no_hp', noHpC.text); + + String newFoto = result['foto'] ?? fotoUser; + await prefs.setString('foto', newFoto); + + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text("Profil berhasil diperbarui")), + ); + + setState(() { + fotoUser = newFoto; + isEditMode = false; + _pickedFile = null; + }); + } else { + throw result['message']; + } + } catch (e) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text("Gagal menyimpan: $e")), + ); + } + } + + @override + Widget build(BuildContext context) { + bool hasPhoto = + _pickedFile != null || (fotoUser != null && fotoUser!.isNotEmpty); + + return PopScope( + canPop: false, + onPopInvokedWithResult: (didPop, result) { + if (didPop) return; + _backToDashboard(); + }, + child: Scaffold( + backgroundColor: const Color(0xfff4f6fb), + appBar: AppBar( + backgroundColor: Colors.blue, + elevation: 0, + leading: IconButton( + icon: const Icon(Icons.arrow_back, color: Colors.white), + onPressed: _backToDashboard, + ), + title: Text("", + style: GoogleFonts.poppins(color: Colors.white, fontSize: 18)), + ), + body: SingleChildScrollView( + child: Column( + children: [ + Container( + width: double.infinity, + decoration: const BoxDecoration( + color: Colors.blue, + borderRadius: BorderRadius.only( + bottomLeft: Radius.circular(30), + bottomRight: Radius.circular(30), + ), + ), + padding: const EdgeInsets.only(bottom: 30), + child: Column( + children: [ + Stack( + children: [ + CircleAvatar( + key: ValueKey(fotoUser), // Mengatasi lag update foto + radius: 65, + backgroundColor: Colors.white, + child: CircleAvatar( + radius: 60, + backgroundColor: Colors.blue.shade100, + backgroundImage: _pickedFile != null + ? (kIsWeb + ? NetworkImage(_pickedFile!.path) + : FileImage(File(_pickedFile!.path)) + as ImageProvider) + : (fotoUser != null && fotoUser!.isNotEmpty) + ? NetworkImage( + "http://ta.myhost.id/E31230549/mposyandu_api/uploads/$fotoUser?t=${DateTime.now().millisecondsSinceEpoch}") + : null, + child: !hasPhoto + ? const Icon(Icons.person, + size: 60, color: Colors.blue) + : null, + ), + ), + Positioned( + bottom: 0, + right: hasPhoto ? 40 : 0, + child: GestureDetector( + onTap: _pickImage, + child: const CircleAvatar( + radius: 18, + backgroundColor: Colors.black, + child: Icon(Icons.camera_alt, + color: Colors.white, size: 18), + ), + ), + ), + if (hasPhoto) + Positioned( + bottom: 0, + right: 0, + child: GestureDetector( + onTap: _removeImage, + child: const CircleAvatar( + radius: 18, + backgroundColor: Colors.red, + child: Icon(Icons.delete, + color: Colors.white, size: 18), + ), + ), + ), + ], + ), + const SizedBox(height: 12), + Text( + namaC.text, + style: GoogleFonts.poppins( + fontSize: 18, + fontWeight: FontWeight.bold, + color: Colors.white), + ), + ], + ), + ), + Padding( + padding: const EdgeInsets.all(20), + child: Column( + children: [ + Card( + color: Colors.white, + elevation: 2, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(15)), + child: Padding( + padding: const EdgeInsets.all(20), + child: Column( + children: [ + _buildField("Nama Lengkap", namaC), + _buildField("Email", emailC), + _buildPasswordField( + "Password (6 Digit Huruf & Angka)", passwordC), + _buildField("Role User", roleC, isReadOnly: true), + Row( + children: [ + Expanded( + child: _buildField("Nama Desa", desaIdC, + isReadOnly: true)), + const SizedBox(width: 10), + Expanded( + child: _buildField("Nama Dusun", dusuIdC, + isReadOnly: true)), + ], + ), + _buildField("No.HP", noHpC, isNumber: true), + _buildField("Status", statusC, isReadOnly: true), + ], + ), + ), + ), + const SizedBox(height: 30), + Row( + children: [ + Expanded( + child: _buildActionButton( + label: "Edit Profil", + color: Colors.orange, + onTap: _enableEdit, + ), + ), + const SizedBox(width: 15), + Expanded( + child: _buildActionButton( + label: "Simpan", + color: Colors.blue, + onTap: _saveProfile, + ), + ), + ], + ), + ], + ), + ), + ], + ), + ), + ), + ); + } + + Widget _buildField(String label, TextEditingController controller, + {bool isReadOnly = false, bool isNumber = false}) { + return Padding( + padding: const EdgeInsets.only(bottom: 15), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(label, + style: GoogleFonts.poppins( + fontSize: 12, + fontWeight: FontWeight.w600, + color: Colors.grey[600])), + const SizedBox(height: 5), + TextField( + controller: controller, + readOnly: isReadOnly || !isEditMode, + keyboardType: isNumber ? TextInputType.phone : TextInputType.text, + style: GoogleFonts.poppins(fontSize: 14), + decoration: InputDecoration( + filled: true, + fillColor: + (isReadOnly || !isEditMode) ? Colors.grey[100] : Colors.white, + contentPadding: + const EdgeInsets.symmetric(horizontal: 12, vertical: 12), + border: + OutlineInputBorder(borderRadius: BorderRadius.circular(8)), + ), + ), + ], + ), + ); + } + + Widget _buildPasswordField(String label, TextEditingController controller) { + return Padding( + padding: const EdgeInsets.only(bottom: 15), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(label, + style: GoogleFonts.poppins( + fontSize: 12, + fontWeight: FontWeight.w600, + color: Colors.grey[600])), + const SizedBox(height: 5), + TextField( + controller: controller, + obscureText: _obscurePassword, + readOnly: !isEditMode, + maxLength: 6, + style: GoogleFonts.poppins(fontSize: 14), + decoration: InputDecoration( + counterText: "", + filled: true, + fillColor: !isEditMode ? Colors.grey[100] : Colors.white, + suffixIcon: IconButton( + icon: Icon( + _obscurePassword ? Icons.visibility_off : Icons.visibility), + onPressed: () => + setState(() => _obscurePassword = !_obscurePassword), + ), + border: + OutlineInputBorder(borderRadius: BorderRadius.circular(8)), + ), + ), + ], + ), + ); + } + + Widget _buildActionButton( + {required String label, + required Color color, + required VoidCallback onTap}) { + return OutlinedButton( + onPressed: onTap, + style: OutlinedButton.styleFrom( + foregroundColor: color, + side: BorderSide(color: color, width: 1.5), + padding: const EdgeInsets.symmetric(vertical: 15), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)), + backgroundColor: Colors.white, + ), + child: Text(label, + style: + GoogleFonts.poppins(fontWeight: FontWeight.bold, fontSize: 14)), + ); + } +} diff --git a/lib/layout/main_layout.dart b/lib/layout/main_layout.dart new file mode 100644 index 0000000..5bc35c5 --- /dev/null +++ b/lib/layout/main_layout.dart @@ -0,0 +1,43 @@ +import 'package:flutter/material.dart'; + +class MainLayout extends StatelessWidget { + final Widget body; + final String title; + final Widget drawer; + + const MainLayout({ + super.key, + required this.body, + required this.title, + required this.drawer, + }); + + static const Color mainColor = Colors.blue; + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: Colors.white, + + // Drawer sekarang fleksibel + drawer: drawer, + + // ================= APPBAR ================= + appBar: AppBar( + backgroundColor: mainColor, + elevation: 0, + title: Text( + title, + style: const TextStyle(color: Colors.white), + ), + iconTheme: const IconThemeData( + color: Colors.white, + size: 28, + ), + ), + + // ================= BODY ================= + body: body, + ); + } +} diff --git a/lib/main.dart b/lib/main.dart new file mode 100644 index 0000000..c92fac9 --- /dev/null +++ b/lib/main.dart @@ -0,0 +1,158 @@ +import 'package:flutter/material.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +// pages umum +import 'pages/login_page.dart'; +import 'pages/register_page.dart'; +import 'pages/landing_page.dart'; + +// dashboard berdasarkan role +import 'kader/dashboard_kader.dart'; +import 'bidan/dashboard_bidan.dart'; +import 'ibu/dashboard_ibu.dart'; + +//route admin +import 'pages/profile_admin.dart'; + +//route menu kader +import 'kader/data_kehamilan.dart'; +import 'kader/data_balita.dart'; +import 'kader/data_pemeriksaan.dart'; +import 'kader/data_kehadiran.dart'; +import 'kader/profile_kader.dart'; +import 'kader/data_ibu.dart'; + +//route menu bidan +import 'bidan/periksa_kehamilan.dart'; +import 'bidan/data_gizi_balita.dart'; +import 'bidan/imunisasi.dart'; +import 'bidan/jadwal_posyandu.dart'; +import 'bidan/jadwal_anc.dart'; +import 'bidan/edukasi.dart'; +import 'bidan/laporan.dart'; +import 'bidan/profile_bidan.dart'; + +//route menu ibu +import 'ibu/pemeriksaan_anc.dart'; +import 'ibu/pemeriksaan_balita.dart'; +import 'ibu/crud_grafik/grafik_anak_bb_usia.dart'; +import 'ibu/crud_grafik/grafik_anak_tb_usia.dart'; +import 'ibu/crud_grafik/grafik_anak_bb_tb.dart'; +import 'ibu/crud_edukasi/edukasi_balita.dart'; +import 'ibu/crud_edukasi/edukasi_ibu_hamil.dart'; +import 'ibu/profile_ibu.dart'; + +//route petugas +import 'pages/petugas.dart'; +import 'pages/dashboard_admin.dart'; + +//route desa +import 'pages/data_desa.dart'; + +//route dusun +import 'pages/data_dusun.dart'; + +void main() async { + // 1. Pastikan inisialisasi Flutter sudah siap sebelum memanggil SharedPreferences + WidgetsFlutterBinding.ensureInitialized(); + + // 2. Akses SharedPreferences untuk mengecek status login + final prefs = await SharedPreferences.getInstance(); + + // 3. Ambil data 'isLogin' dan 'role' (ini harus sesuai dengan kunci yang disimpan di LoginPage) + bool isLogin = prefs.getBool("isLogin") ?? false; + String role = prefs.getString("role") ?? ""; + + // 4. Tentukan halaman pertama yang muncul saat aplikasi dibuka + String initialRoute = '/'; // Default ke Landing Page + + if (isLogin) { + // Jika sudah pernah login, arahkan ke dashboard sesuai role yang tersimpan + switch (role.toLowerCase()) { + case "admin": + initialRoute = '/dashboard-admin'; + break; + case "kader": + initialRoute = '/dashboard-kader'; + break; + case "bidan": + initialRoute = '/dashboard-bidan'; + break; + case "ibu": + initialRoute = '/dashboard-ibu'; + break; + default: + initialRoute = '/'; + } + } + + runApp(MyApp(initialRoute: initialRoute)); +} + +class MyApp extends StatelessWidget { + final String initialRoute; + const MyApp({super.key, required this.initialRoute}); + + @override + Widget build(BuildContext context) { + return MaterialApp( + debugShowCheckedModeBanner: false, + title: 'm-Posyandu', // Nama aplikasi diperbarui + + // Menggunakan rute awal dinamis hasil pengecekan SharedPreferences + initialRoute: initialRoute, + + routes: { + // --- PAGES UMUM --- + '/': (context) => const LandingPage(), + '/login': (context) { + final args = ModalRoute.of(context)?.settings.arguments as bool?; + return LoginPage(fromGuard: args ?? false); + }, + '/register': (context) => RegisterPage(), + + // --- DASHBOARD BERDASARKAN ROLE --- + '/dashboard-admin': (context) => const DashboardAdminPage(), + '/dashboard-kader': (context) => const DashboardKaderPage(), + '/dashboard-bidan': (context) => const DashboardBidanPage(), + '/dashboard-ibu': (context) => const DashboardIbuPage(), + + // --- ROUTE ADMIN --- + '/profile-admin': (context) => const ProfileAdminPage(), + '/data-petugas': (context) => DataPetugasPage(), + '/data-desa': (context) => DataDesaPage(), + '/data-dusun': (context) => DataDusunPage(), + + // --- ROUTE MENU KADER --- + '/data-ibu': (context) => const DataIbuPage(), + '/data-kehamilan': (context) => const DataIbuHamilPage(), + '/data-balita': (context) => const DataBalitaPage(), + '/data-pemeriksaan-balita': (context) => + const DataPemeriksaanBalitaPage(), + '/data-kehadiran-posyandu': (context) => + const DataKehadiranPosyanduPage(), + '/profile-kader': (context) => const ProfileKaderPage(), + + // --- ROUTE MENU BIDAN --- + '/periksa-kehamilan': (context) => const DataPemeriksaanKehamilanPage(), + '/data-gizi-balita': (context) => const DataGiziBalitaPage(), + '/imunisasi': (context) => const DataImunisasiPage(), + '/jadwal-posyandu': (context) => const DataJadwalPosyanduPage(), + '/jadwal-anc': (context) => const JadwalAncPage(), + '/edukasi': (context) => const DataEdukasiPage(), + '/profile-bidan': (context) => const ProfileBidanPage(), + '/laporan': (context) => const DataLaporanPage(), + + // --- ROUTE MENU IBU --- + '/pemeriksaan-anc': (context) => const PemeriksaanANCPage(), + '/pemeriksaan-balita': (context) => const PemeriksaanBalitaIbuPage(), + '/grafik-bb-u': (context) => const GrafikAnakBBUsiaPage(), + '/grafik-tb-u': (context) => const GrafikAnakTBUPage(), + '/grafik-bb-tb': (context) => const GrafikAnakBBTBPage(), + '/edukasi-balita': (context) => const EdukasiBalitaPage(), + '/edukasi-hamil': (context) => const EdukasiHamilPage(), + '/profile-ibu': (context) => const ProfileIbuPage(), + }, + ); + } +} diff --git a/lib/pages/dashboard_admin.dart b/lib/pages/dashboard_admin.dart new file mode 100644 index 0000000..2a93eb2 --- /dev/null +++ b/lib/pages/dashboard_admin.dart @@ -0,0 +1,210 @@ +import 'dart:convert'; +import 'dart:io'; // Tambahkan ini +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; // Tambahkan ini untuk SystemNavigator.pop +import 'package:http/http.dart' as http; +import 'package:google_fonts/google_fonts.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../layout/main_layout.dart'; +import '../pages/petugas_drawer.dart'; +import '../pages/login_page.dart'; + +class DashboardAdminPage extends StatefulWidget { + const DashboardAdminPage({super.key}); + + @override + State createState() => _DashboardAdminPageState(); +} + +class _DashboardAdminPageState extends State { + bool _isAuthorized = false; + bool _isLoading = true; + String userName = "Loading..."; + + int jumlahKader = 0; + int jumlahBidan = 0; + int jumlahDesa = 0; + int jumlahDusun = 0; + + final String dashboardUrl = + "http://ta.myhost.id/E31230549/mposyandu_api/dashboard_admin.php"; + + @override + void initState() { + super.initState(); + _initPage(); + } + + Future _initPage() async { + final prefs = await SharedPreferences.getInstance(); + final isLogin = prefs.getBool("isLogin") ?? false; + + if (!isLogin) { + if (!mounted) return; + Navigator.pushAndRemoveUntil( + context, + MaterialPageRoute(builder: (_) => const LoginPage(fromGuard: true)), + (route) => false, + ); + return; + } + + setState(() { + _isAuthorized = true; + String? savedName = prefs.getString('nama'); + userName = (savedName == null || savedName.isEmpty) ? "Admin" : savedName; + }); + + await fetchDashboard(); + } + + Future fetchDashboard() async { + if (!_isAuthorized) return; + try { + final response = await http.get(Uri.parse(dashboardUrl)); + if (response.statusCode == 200) { + final data = json.decode(response.body); + if (data["success"] == true) { + if (mounted) { + setState(() { + jumlahKader = data["jumlah_kader"] ?? 0; + jumlahBidan = data["jumlah_bidan"] ?? 0; + jumlahDesa = data["jumlah_desa"] ?? 0; + jumlahDusun = data["jumlah_dusun"] ?? 0; + _isLoading = false; + }); + } + } + } + } catch (e) { + debugPrint("ERROR DASHBOARD: $e"); + if (mounted) setState(() => _isLoading = false); + } + } + + @override + Widget build(BuildContext context) { + // Logika Responsif + double screenWidth = MediaQuery.of(context).size.width; + + // Jika lebar layar > 700px (Desktop/Tablet), gunakan 4 kolom. Jika tidak (HP), 2 kolom. + int crossAxisCount = screenWidth > 700 ? 4 : 2; + + // Mengatur rasio tinggi kartu agar tetap proporsional + double aspectRatio = screenWidth > 700 ? 1.5 : 1.1; + + // Membungkus dengan PopScope agar ketika klik back button aplikasi keluar + return PopScope( + canPop: false, // Menahan aksi "back" standar navigator + onPopInvokedWithResult: (didPop, result) { + if (didPop) return; + // Keluar dari aplikasi secara total + if (Platform.isAndroid) { + SystemNavigator.pop(); + } else if (Platform.isIOS) { + exit(0); + } + }, + child: MainLayout( + title: " ", + drawer: const DrawerPetugas(), + body: RefreshIndicator( + onRefresh: fetchDashboard, + child: _isLoading + ? const Center(child: CircularProgressIndicator()) + : SingleChildScrollView( + physics: const AlwaysScrollableScrollPhysics(), + padding: + const EdgeInsets.symmetric(horizontal: 20, vertical: 25), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // HEADER AREA + RichText( + text: TextSpan( + children: [ + TextSpan( + text: 'Selamat Datang Admin\n', + style: GoogleFonts.poppins( + fontSize: 16, + fontWeight: FontWeight.w500, + color: Colors.black54), + ), + TextSpan( + text: userName, + style: GoogleFonts.poppins( + fontSize: 22, + fontWeight: FontWeight.w700, + color: const Color(0xFF1385E2)), + ), + ], + ), + ), + const SizedBox(height: 25), + + // GRID AREA (Dinamis berdasarkan perangkat) + GridView.count( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + crossAxisCount: crossAxisCount, + crossAxisSpacing: 15, + mainAxisSpacing: 15, + childAspectRatio: aspectRatio, + children: [ + _card( + "Kader", jumlahKader, Icons.groups, Colors.blue), + _card("Bidan", jumlahBidan, Icons.medical_services, + Colors.green), + _card("Desa", jumlahDesa, Icons.location_city, + Colors.orange), + _card("Dusun", jumlahDusun, Icons.map, Colors.purple), + ], + ), + ], + ), + ), + ), + ), + ); + } + + Widget _card(String title, int val, IconData icon, Color color) { + return Container( + decoration: BoxDecoration( + color: color, + borderRadius: BorderRadius.circular(15), + boxShadow: [ + BoxShadow( + color: color.withOpacity(0.3), + blurRadius: 10, + offset: const Offset(0, 5), + ) + ], + ), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(icon, color: Colors.white, size: 28), + const SizedBox(height: 8), + Text( + val.toString(), + style: const TextStyle( + color: Colors.white, + fontSize: 20, + fontWeight: FontWeight.bold, + ), + ), + Text( + title, + style: const TextStyle( + color: Colors.white70, + fontSize: 12, + letterSpacing: 0.5, + ), + ), + ], + ), + ); + } +} diff --git a/lib/pages/data_desa.dart b/lib/pages/data_desa.dart new file mode 100644 index 0000000..ca25042 --- /dev/null +++ b/lib/pages/data_desa.dart @@ -0,0 +1,272 @@ +import 'dart:async'; +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:http/http.dart' as http; +import 'package:google_fonts/google_fonts.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../layout/main_layout.dart'; +import '../pages/petugas_drawer.dart'; +import '../pages/login_page.dart'; +import '../pages/tambah_desa.dart'; +import '../pages/edit_desa.dart'; + +class DataDesaPage extends StatefulWidget { + const DataDesaPage({super.key}); + + @override + State createState() => _DataDesaPageState(); +} + +class _DataDesaPageState extends State { + final TextEditingController _searchController = TextEditingController(); + Timer? _debounce; + + int _rowsPerPage = 10; + int _currentPage = 0; + int _totalData = 0; + + List> _allData = []; + bool _isLoading = false; + bool _isAuthorized = false; + + final String baseUrl = "http://ta.myhost.id/E31230549/mposyandu_api/desa/get_desa.php"; + final String deleteUrl = "http://ta.myhost.id/E31230549/mposyandu_api/desa/delete_desa.php"; + + @override + void initState() { + super.initState(); + checkLogin(); + } + + @override + void dispose() { + _debounce?.cancel(); + _searchController.dispose(); + super.dispose(); + } + + Future checkLogin() async { + final prefs = await SharedPreferences.getInstance(); + final isLogin = prefs.getBool("isLogin") ?? false; + + if (!isLogin) { + if (!mounted) return; + Navigator.pushAndRemoveUntil( + context, + MaterialPageRoute(builder: (_) => const LoginPage(fromGuard: true)), + (route) => false, + ); + return; + } + + setState(() => _isAuthorized = true); + await fetchDesa(); + } + + Future fetchDesa() async { + if (!_isAuthorized || !mounted) return; + setState(() => _isLoading = true); + + try { + final url = Uri.parse(baseUrl).replace(queryParameters: { + "page": (_currentPage + 1).toString(), + "limit": _rowsPerPage.toString(), + "search": _searchController.text.trim(), + }); + + final response = await http.get(url); + if (response.statusCode == 200) { + final decoded = json.decode(response.body); + if (decoded["success"] == true) { + setState(() { + _allData = List>.from(decoded["data"] ?? []); + _totalData = decoded["total"] ?? 0; + }); + } + } + } catch (e) { + debugPrint("ERROR FETCH DESA: $e"); + } finally { + if (mounted) setState(() => _isLoading = false); + } + } + + Future _deleteDesa(String id) async { + final confirm = await showDialog( + context: context, + builder: (context) => AlertDialog( + title: Text("Konfirmasi", style: GoogleFonts.poppins(fontSize: 14, fontWeight: FontWeight.bold)), + content: Text("Yakin ingin menghapus desa ini?", style: GoogleFonts.poppins(fontSize: 13)), + actions: [ + TextButton(onPressed: () => Navigator.pop(context, false), child: const Text("Batal")), + ElevatedButton( + onPressed: () => Navigator.pop(context, true), + style: ElevatedButton.styleFrom(backgroundColor: Colors.red), + child: const Text("Hapus", style: TextStyle(color: Colors.white)), + ), + ], + ), + ); + + if (confirm != true) return; + + try { + final res = await http.post(Uri.parse(deleteUrl), body: {"id": id}); + if (json.decode(res.body)["success"] == true) { + fetchDesa(); + } + } catch (e) { + debugPrint("Delete error: $e"); + } + } + + @override + Widget build(BuildContext context) { + int totalPages = (_totalData / _rowsPerPage).ceil(); + if (totalPages == 0) totalPages = 1; + + return MainLayout( + title: "", + drawer: const DrawerPetugas(), + body: Padding( + padding: const EdgeInsets.all(16), + child: Column( + children: [ + // Judul Halaman + Text("Data Desa", style: GoogleFonts.poppins(fontSize: 18, fontWeight: FontWeight.bold)), + const SizedBox(height: 16), + + // Search + Tambah + Row( + children: [ + Expanded( + child: TextField( + controller: _searchController, + style: GoogleFonts.poppins(fontSize: 13), + decoration: InputDecoration( + hintText: "Cari nama desa...", + prefixIcon: const Icon(Icons.search, size: 20), + border: OutlineInputBorder(borderRadius: BorderRadius.circular(10)), + contentPadding: const EdgeInsets.symmetric(horizontal: 10), + ), + onChanged: (v) { + _debounce?.cancel(); + _debounce = Timer(const Duration(milliseconds: 500), () { + _currentPage = 0; + fetchDesa(); + }); + }, + ), + ), + const SizedBox(width: 8), + ElevatedButton( + onPressed: () async { + final res = await Navigator.push(context, MaterialPageRoute(builder: (_) => const TambahDesaPage())); + if (res == true) fetchDesa(); + }, + style: ElevatedButton.styleFrom( + backgroundColor: Colors.blue, + padding: const EdgeInsets.all(12), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)), + ), + child: const Icon(Icons.add, color: Colors.white), + ) + ], + ), + const SizedBox(height: 16), + + // Card List Area + Expanded( + child: _isLoading + ? const Center(child: CircularProgressIndicator()) + : _allData.isEmpty + ? const Center(child: Text("Data tidak ditemukan")) + : ListView.builder( + itemCount: _allData.length, + itemBuilder: (context, index) { + final item = _allData[index]; + return Card( + elevation: 0, + margin: const EdgeInsets.only(bottom: 12), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + side: BorderSide(color: Colors.grey.shade300, width: 1), + ), + child: Padding( + padding: const EdgeInsets.all(16), + child: Row( + children: [ + // Konten (Nama Desa) + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text("Nama Desa", style: GoogleFonts.poppins(fontSize: 10, color: Colors.grey)), + Text(item["nama_desa"] ?? "", + style: GoogleFonts.poppins(fontWeight: FontWeight.bold, fontSize: 15)), + ], + ), + ), + + // Tombol Aksi (Edit & Hapus) + _actionButton(Icons.edit, Colors.orange, () async { + final res = await Navigator.push(context, + MaterialPageRoute(builder: (_) => EditDesaPage(data: item))); + if (res == true) fetchDesa(); + }), + const SizedBox(width: 8), + _actionButton(Icons.delete, Colors.red, () => _deleteDesa(item["id"].toString())), + ], + ), + ), + ); + }, + ), + ), + + // Pagination Area + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text("Halaman ${_currentPage + 1} dari $totalPages", style: GoogleFonts.poppins(fontSize: 12)), + Row( + children: [ + IconButton( + icon: const Icon(Icons.chevron_left), + onPressed: _currentPage == 0 ? null : () { setState(() => _currentPage--); fetchDesa(); }, + ), + IconButton( + icon: const Icon(Icons.chevron_right), + onPressed: _currentPage >= totalPages - 1 ? null : () { setState(() => _currentPage++); fetchDesa(); }, + ), + ], + ) + ], + ) + ], + ), + ), + ); + } + + // Widget Tombol Aksi dengan Border + Widget _actionButton(IconData icon, Color color, VoidCallback onTap) { + return Material( + color: Colors.transparent, + child: InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(8), + child: Container( + padding: const EdgeInsets.all(8), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(8), + border: Border.all(color: color, width: 1.5), + ), + child: Icon(icon, color: color, size: 18), + ), + ), + ); + } +} \ No newline at end of file diff --git a/lib/pages/data_dusun.dart b/lib/pages/data_dusun.dart new file mode 100644 index 0000000..a073e25 --- /dev/null +++ b/lib/pages/data_dusun.dart @@ -0,0 +1,313 @@ +import 'dart:async'; +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:http/http.dart' as http; +import 'package:google_fonts/google_fonts.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../layout/main_layout.dart'; +import '../pages/petugas_drawer.dart'; +import '../pages/login_page.dart'; +import '../pages/tambah_dusun.dart'; +import '../pages/edit_dusun.dart'; + +class DataDusunPage extends StatefulWidget { + const DataDusunPage({super.key}); + + @override + State createState() => _DataDusunPageState(); +} + +class _DataDusunPageState extends State { + final TextEditingController _searchController = TextEditingController(); + Timer? _debounce; + + int _rowsPerPage = 10; + int _currentPage = 0; + int _totalData = 0; + + List> _allData = []; + bool _isLoading = false; + bool _isAuthorized = false; + + final String baseUrl = "http://ta.myhost.id/E31230549/mposyandu_api/dusun/get_dusun.php"; + final String deleteUrl = + "http://ta.myhost.id/E31230549/mposyandu_api/dusun/delete_dusun.php"; + + @override + void initState() { + super.initState(); + checkLogin(); + } + + @override + void dispose() { + _debounce?.cancel(); + _searchController.dispose(); + super.dispose(); + } + + Future checkLogin() async { + final prefs = await SharedPreferences.getInstance(); + final isLogin = prefs.getBool("isLogin") ?? false; + + if (!isLogin) { + if (!mounted) return; + Navigator.pushAndRemoveUntil( + context, + MaterialPageRoute(builder: (_) => const LoginPage(fromGuard: true)), + (route) => false, + ); + return; + } + + setState(() => _isAuthorized = true); + await fetchDusun(); + } + + Future fetchDusun() async { + if (!_isAuthorized || !mounted) return; + setState(() => _isLoading = true); + + try { + final url = Uri.parse(baseUrl).replace(queryParameters: { + "page": (_currentPage + 1).toString(), + "limit": _rowsPerPage.toString(), + "search": _searchController.text.trim(), + }); + + final response = await http.get(url); + if (response.statusCode == 200) { + final decoded = json.decode(response.body); + if (decoded["success"] == true) { + setState(() { + _allData = List>.from(decoded["data"] ?? []); + _totalData = decoded["total"] ?? 0; + }); + } + } + } catch (e) { + debugPrint("ERROR FETCH DUSUN: $e"); + } finally { + if (mounted) setState(() => _isLoading = false); + } + } + + Future _deleteDusun(String id) async { + final confirm = await showDialog( + context: context, + builder: (context) => AlertDialog( + title: Text("Konfirmasi", + style: + GoogleFonts.poppins(fontSize: 14, fontWeight: FontWeight.bold)), + content: Text("Yakin ingin menghapus dusun ini?", + style: GoogleFonts.poppins(fontSize: 13)), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context, false), + child: const Text("Batal")), + ElevatedButton( + onPressed: () => Navigator.pop(context, true), + style: ElevatedButton.styleFrom(backgroundColor: Colors.red), + child: const Text("Hapus", style: TextStyle(color: Colors.white)), + ), + ], + ), + ); + + if (confirm != true) return; + + try { + final res = await http.post(Uri.parse(deleteUrl), body: {"id": id}); + if (json.decode(res.body)["success"] == true) { + fetchDusun(); + } + } catch (e) { + debugPrint("Delete error: $e"); + } + } + + @override + Widget build(BuildContext context) { + int totalPages = (_totalData / _rowsPerPage).ceil(); + if (totalPages == 0) totalPages = 1; + + return MainLayout( + title: "", + drawer: const DrawerPetugas(), + body: Padding( + padding: const EdgeInsets.all(16), + child: Column( + children: [ + // Judul Halaman + Text("Data Dusun", + style: GoogleFonts.poppins( + fontSize: 18, fontWeight: FontWeight.bold)), + const SizedBox(height: 16), + + // Search + Tambah + Row( + children: [ + Expanded( + child: TextField( + controller: _searchController, + style: GoogleFonts.poppins(fontSize: 13), + decoration: InputDecoration( + hintText: "Cari nama dusun...", + prefixIcon: const Icon(Icons.search, size: 20), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10)), + contentPadding: + const EdgeInsets.symmetric(horizontal: 10), + ), + onChanged: (v) { + _debounce?.cancel(); + _debounce = Timer(const Duration(milliseconds: 500), () { + _currentPage = 0; + fetchDusun(); + }); + }, + ), + ), + const SizedBox(width: 8), + ElevatedButton( + onPressed: () async { + final res = await Navigator.push( + context, + MaterialPageRoute( + builder: (_) => const TambahDusunPage())); + if (res == true) fetchDusun(); + }, + style: ElevatedButton.styleFrom( + backgroundColor: Colors.blue, + padding: const EdgeInsets.all(12), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10)), + ), + child: const Icon(Icons.add, color: Colors.white), + ) + ], + ), + const SizedBox(height: 16), + + // Card List Area + Expanded( + child: _isLoading + ? const Center(child: CircularProgressIndicator()) + : _allData.isEmpty + ? const Center(child: Text("Data tidak ditemukan")) + : ListView.builder( + itemCount: _allData.length, + itemBuilder: (context, index) { + final item = _allData[index]; + return Card( + elevation: 0, + margin: const EdgeInsets.only(bottom: 12), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + side: BorderSide( + color: Colors.grey.shade300, width: 1), + ), + child: Padding( + padding: const EdgeInsets.all(16), + child: Row( + children: [ + // Konten Dusun + Expanded( + child: Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + Text("Nama Dusun", + style: GoogleFonts.poppins( + fontSize: 10, + color: Colors.grey)), + Text(item["nama_dusun"] ?? "", + style: GoogleFonts.poppins( + fontWeight: FontWeight.bold, + fontSize: 15)), + const SizedBox(height: 4), + ], + ), + ), + + // Tombol Aksi (Edit & Hapus) + _actionButton(Icons.edit, Colors.orange, + () async { + final res = await Navigator.push( + context, + MaterialPageRoute( + builder: (_) => + EditDusunPage(data: item))); + if (res == true) fetchDusun(); + }), + const SizedBox(width: 8), + _actionButton( + Icons.delete, + Colors.red, + () => _deleteDusun( + item["id"].toString())), + ], + ), + ), + ); + }, + ), + ), + + // Pagination Area + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text("Halaman ${_currentPage + 1} dari $totalPages", + style: GoogleFonts.poppins(fontSize: 12)), + Row( + children: [ + IconButton( + icon: const Icon(Icons.chevron_left), + onPressed: _currentPage == 0 + ? null + : () { + setState(() => _currentPage--); + fetchDusun(); + }, + ), + IconButton( + icon: const Icon(Icons.chevron_right), + onPressed: _currentPage >= totalPages - 1 + ? null + : () { + setState(() => _currentPage++); + fetchDusun(); + }, + ), + ], + ) + ], + ) + ], + ), + ), + ); + } + + // Widget Tombol Aksi dengan Border sesuai gaya Petugas/Desa + Widget _actionButton(IconData icon, Color color, VoidCallback onTap) { + return Material( + color: Colors.transparent, + child: InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(8), + child: Container( + padding: const EdgeInsets.all(8), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(8), + border: Border.all(color: color, width: 1.5), + ), + child: Icon(icon, color: color, size: 18), + ), + ), + ); + } +} diff --git a/lib/pages/edit_desa.dart b/lib/pages/edit_desa.dart new file mode 100644 index 0000000..650f587 --- /dev/null +++ b/lib/pages/edit_desa.dart @@ -0,0 +1,180 @@ +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:http/http.dart' as http; + +class EditDesaPage extends StatefulWidget { + final Map data; // data dari tabel + + const EditDesaPage({super.key, required this.data}); + + @override + State createState() => _EditDesaPageState(); +} + +class _EditDesaPageState extends State { + final _nama = TextEditingController(); + bool _loading = false; + + // Sesuaikan URL API Update kamu + final String url = "http://ta.myhost.id/E31230549/mposyandu_api/desa/update_desa.php"; + + @override + void initState() { + super.initState(); + // PERBAIKAN: Menggunakan "nama_desa" sesuai dengan output JSON dari API kamu + _nama.text = widget.data["nama_desa"] ?? ""; + } + + Future _update() async { + if (_nama.text.trim().isEmpty) { + _snack("Nama desa wajib diisi"); + return; + } + + setState(() => _loading = true); + + try { + final res = await http.post( + Uri.parse(url), + headers: { + "Content-Type": "application/x-www-form-urlencoded", + }, + body: { + "id": widget.data["id"].toString(), + "nama": _nama.text.trim(), + }, + ).timeout(const Duration(seconds: 15)); + + final data = json.decode(res.body); + + if (!mounted) return; + + if (data["success"] == true) { + _snack("Berhasil update"); + Navigator.pop(context, true); + } else { + _snack(data["message"] ?? "Gagal update"); + } + } catch (e) { + if (mounted) _snack("Error koneksi"); + } finally { + if (mounted) setState(() => _loading = false); + } + } + + void _snack(String msg) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text( + msg, + style: GoogleFonts.poppins(fontSize: 12), + ), + ), + ); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: const Color(0xfff5f6fa), + appBar: AppBar( + leading: const BackButton(color: Colors.white), + title: Text( + "", + style: GoogleFonts.poppins( + color: Colors.white, + fontSize: 14, // Ukuran sedikit lebih besar untuk AppBar + fontWeight: FontWeight.w600, + ), + ), + backgroundColor: Colors.blue, + ), + body: Center( + child: SingleChildScrollView( + child: Container( + width: 500, + margin: const EdgeInsets.all(16), + padding: const EdgeInsets.all(24), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + boxShadow: const [ + BoxShadow(color: Colors.black12, blurRadius: 12) + ], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // PERBAIKAN: ID Desa dihapus sesuai permintaan + _label("Nama Desa"), + _input(_nama), + + const SizedBox(height: 24), + + // ================= BUTTON (WHITE WITH ORANGE BORDER) ================= + SizedBox( + width: double.infinity, + child: OutlinedButton( + onPressed: _loading ? null : _update, + style: OutlinedButton.styleFrom( + backgroundColor: Colors.white, // Background Putih + side: const BorderSide( + color: Colors.orange, width: 1.5), // Garis Orange + padding: const EdgeInsets.symmetric(vertical: 14), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10), + ), + ), + child: _loading + ? const SizedBox( + height: 20, + width: 20, + child: CircularProgressIndicator( + color: Colors.orange, strokeWidth: 2), + ) + : Text( + "Simpan Perubahan", + style: GoogleFonts.poppins( + color: Colors.orange, // Teks Orange + fontWeight: FontWeight.bold, + fontSize: 12, + ), + ), + ), + ), + ], + ), + ), + ), + ), + ); + } + + Widget _label(String t) => Padding( + padding: const EdgeInsets.only(bottom: 6), + child: Text( + t, + style: GoogleFonts.poppins( + fontWeight: FontWeight.w600, + fontSize: 12, + ), + ), + ); + + Widget _input(TextEditingController c) => TextField( + controller: c, + style: GoogleFonts.poppins(fontSize: 12), + decoration: InputDecoration( + hintText: "Masukkan nama desa...", + hintStyle: GoogleFonts.poppins(fontSize: 12, color: Colors.grey), + contentPadding: + const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + border: OutlineInputBorder(borderRadius: BorderRadius.circular(10)), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: const BorderSide(color: Colors.blue, width: 1.5), + ), + ), + ); +} diff --git a/lib/pages/edit_dusun.dart b/lib/pages/edit_dusun.dart new file mode 100644 index 0000000..8c506a0 --- /dev/null +++ b/lib/pages/edit_dusun.dart @@ -0,0 +1,129 @@ +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:http/http.dart' as http; + +class EditDusunPage extends StatefulWidget { + final Map data; + const EditDusunPage({super.key, required this.data}); + + @override + State createState() => _EditDusunPageState(); +} + +class _EditDusunPageState extends State { + final _namaDusun = TextEditingController(); + bool _loading = false; + final String url = "http://ta.myhost.id/E31230549/mposyandu_api/dusun/update_dusun.php"; + + @override + void initState() { + super.initState(); + _namaDusun.text = widget.data["nama_dusun"] ?? ""; + } + + Future _update() async { + if (_namaDusun.text.trim().isEmpty) { + _snack("Nama dusun wajib diisi"); + return; + } + setState(() => _loading = true); + try { + final res = await http.post( + Uri.parse(url), + body: { + "id": widget.data["id"].toString(), + "desa_id": widget.data["desa_id"] + .toString(), // Tetap kirim ID dari data awal + "nama_dusun": _namaDusun.text.trim(), + }, + ); + final data = json.decode(res.body); + if (data["success"] == true) { + _snack("Berhasil update"); + Navigator.pop(context, true); + } + } catch (e) { + _snack("Error koneksi"); + } finally { + if (mounted) setState(() => _loading = false); + } + } + + void _snack(String msg) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(msg, style: GoogleFonts.poppins(fontSize: 12)))); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: const Color(0xfff5f6fa), + appBar: AppBar( + leading: const BackButton(color: Colors.white), + title: Text("", + style: GoogleFonts.poppins(color: Colors.white, fontSize: 14)), + backgroundColor: Colors.blue, + ), + body: Center( + child: Container( + width: 500, + margin: const EdgeInsets.all(16), + padding: const EdgeInsets.all(24), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + boxShadow: const [BoxShadow(color: Colors.black12, blurRadius: 12)], + ), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _label("Nama Dusun"), + TextField( + controller: _namaDusun, + style: GoogleFonts.poppins(fontSize: 12), + decoration: InputDecoration( + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10)), + ), + ), + const SizedBox(height: 24), + SizedBox( + width: double.infinity, + child: OutlinedButton( + onPressed: _loading ? null : _update, + style: OutlinedButton.styleFrom( + backgroundColor: Colors.white, + side: const BorderSide(color: Colors.orange, width: 1.5), + padding: const EdgeInsets.symmetric(vertical: 14), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10)), + ), + child: _loading + ? const SizedBox( + width: 20, + height: 20, + child: CircularProgressIndicator( + color: Colors.orange, strokeWidth: 2)) + : Text("Simpan Perubahan", + style: GoogleFonts.poppins( + color: Colors.orange, + fontWeight: FontWeight.bold, + fontSize: 12)), + ), + ), + ], + ), + ), + ), + ); + } + + Widget _label(String t) => Padding( + padding: const EdgeInsets.only(bottom: 6), + child: Text(t, + style: + GoogleFonts.poppins(fontWeight: FontWeight.w600, fontSize: 12)), + ); +} diff --git a/lib/pages/edit_petugas.dart b/lib/pages/edit_petugas.dart new file mode 100644 index 0000000..2184fb8 --- /dev/null +++ b/lib/pages/edit_petugas.dart @@ -0,0 +1,395 @@ +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:http/http.dart' as http; + +class EditPetugasPage extends StatefulWidget { + final Map data; + + const EditPetugasPage({super.key, required this.data}); + + @override + State createState() => _EditPetugasPageState(); +} + +class _EditPetugasPageState extends State { + final _nama = TextEditingController(); + final _email = TextEditingController(); + final _noHp = TextEditingController(); + + String? _role; + String? _desaId; + String? _dusunId; + + // State untuk menampung pesan error validasi + String? _errNama, _errEmail, _errNoHp; + + bool _loading = false; + List> desaList = []; + List> dusunList = []; + + final String url = + "http://ta.myhost.id/E31230549/mposyandu_api/petugas/update_petugas.php"; + final String desaUrl = "http://ta.myhost.id/E31230549/mposyandu_api/desa/get_desa.php"; + final String dusunUrl = "http://ta.myhost.id/E31230549/mposyandu_api/dusun/get_dusun.php"; + + @override + void initState() { + super.initState(); + + _nama.text = widget.data["nama"]?.toString() ?? ""; + _email.text = widget.data["email"]?.toString() ?? ""; + _noHp.text = widget.data["no_hp"]?.toString() ?? ""; + _role = widget.data["role"]?.toString(); + + _desaId = (widget.data["desa_id"] == null || + widget.data["desa_id"].toString() == "0") + ? null + : widget.data["desa_id"].toString(); + + _dusunId = (widget.data["dusun_id"] == null || + widget.data["dusun_id"].toString() == "0") + ? null + : widget.data["dusun_id"].toString(); + + _initData(); + } + + Future _initData() async { + setState(() => _loading = true); + await _fetchDesa(); + if (_desaId != null && _desaId != "") { + await _fetchDusun(_desaId!); + } + setState(() => _loading = false); + } + + Future _fetchDesa() async { + try { + final res = await http.get(Uri.parse(desaUrl)); + if (res.statusCode == 200) { + final jsonData = json.decode(res.body); + if (jsonData["success"] == true) { + setState(() { + desaList = List>.from(jsonData["data"]); + }); + } + } + } catch (e) { + debugPrint("ERROR DESA: $e"); + } + } + + Future _fetchDusun(String dId) async { + try { + final res = await http.get(Uri.parse("$dusunUrl?desa_id=$dId")); + if (res.statusCode == 200) { + final jsonData = json.decode(res.body); + if (jsonData["success"] == true) { + setState(() { + dusunList = List>.from(jsonData["data"]); + }); + } + } + } catch (e) { + debugPrint("ERROR DUSUN: $e"); + } + } + + // Fungsi validasi sebelum melakukan update data + bool _isValid() { + setState(() { + // 1. Validasi Nama + _errNama = _nama.text.trim().isEmpty ? "Nama tidak boleh kosong" : null; + + // 2. Validasi Email + final emailRegex = RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$'); + if (_email.text.trim().isEmpty) { + _errEmail = "Email tidak boleh kosong"; + } else if (!emailRegex.hasMatch(_email.text.trim())) { + _errEmail = "Format email salah (misal: nama@email.com)"; + } else { + _errEmail = null; + } + + // 3. Validasi No HP (Wajib berada di rentang 10 sampai 13 digit) + final noHpLength = _noHp.text.trim().length; + if (_noHp.text.trim().isEmpty) { + _errNoHp = "Nomor HP tidak boleh kosong"; + } else if (noHpLength < 10 || noHpLength > 13) { + _errNoHp = "No HP harus berjumlah 10-13 digit"; + } else { + _errNoHp = null; + } + }); + + return _errNama == null && _errEmail == null && _errNoHp == null; + } + + Future _update() async { + if (!_isValid()) return; // Batalkan proses jika input tidak lolos validasi + + setState(() => _loading = true); + try { + final res = await http.post( + Uri.parse(url), + body: { + "id": widget.data["id"].toString(), + "nama": _nama.text.trim(), + "email": _email.text.trim(), + "no_hp": _noHp.text.trim(), + "role": _role ?? "", + "desa_id": _role == "kader" ? (_desaId ?? "") : "", + "dusun_id": _role == "kader" ? (_dusunId ?? "") : "", + }, + ); + final data = json.decode(res.body); + if (data["success"] == true) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text("Berhasil update", + style: GoogleFonts.poppins(fontSize: 12))), + ); + Navigator.pop(context, true); + } + } else { + _showSimpleError(data["message"] ?? "Gagal update data"); + } + } catch (e) { + debugPrint("Update Error: $e"); + _showSimpleError("Terjadi kesalahan jaringan"); + } finally { + if (mounted) setState(() => _loading = false); + } + } + + void _showSimpleError(String msg) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(msg, style: GoogleFonts.poppins(fontSize: 12)))); + } + + @override + Widget build(BuildContext context) { + final bool isKader = _role == "kader"; + final bool isAdmin = widget.data["role"] == "admin"; + + return Scaffold( + backgroundColor: const Color(0xfff5f6fa), + appBar: AppBar( + leading: const BackButton(color: Colors.white), + title: Text("", + style: GoogleFonts.poppins(color: Colors.white, fontSize: 16)), + backgroundColor: Colors.blue, + ), + body: Center( + child: SingleChildScrollView( + child: Column( + children: [ + Text( + "Edit Data Petugas", + style: GoogleFonts.poppins( + fontSize: 18, + fontWeight: FontWeight.bold, + color: Colors.black, + ), + ), + const SizedBox(height: 16), + Container( + width: 500, + margin: const EdgeInsets.symmetric(horizontal: 16), + padding: const EdgeInsets.all(24), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + boxShadow: const [ + BoxShadow(color: Colors.black12, blurRadius: 12) + ], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _label("Nama Lengkap"), + _input(_nama, error: _errNama), + const SizedBox(height: 16), + _label("Email"), + _input(_email, error: _errEmail, type: TextInputType.emailAddress), + const SizedBox(height: 16), + _label("Role"), + _dropdown( + value: _role, + items: const [ + {"id": "admin", "nama": "admin"}, + {"id": "kader", "nama": "kader"}, + {"id": "bidan", "nama": "bidan"} + ], + onChanged: isAdmin + ? null + : (v) { + setState(() { + _role = v; + if (_role != "kader") { + _desaId = null; + _dusunId = null; + } + }); + }, + disabled: isAdmin, + ), + const SizedBox(height: 16), + _label("Desa"), + _dropdown( + value: isKader ? _desaId : null, + items: desaList + .map((e) => { + "id": e["id"].toString(), + "nama": e["nama_desa"] + }) + .toList(), + onChanged: isKader + ? (v) { + setState(() { + _desaId = v; + _dusunId = null; + dusunList = []; + }); + if (v != null) _fetchDusun(v); + } + : null, + disabled: !isKader, + hint: _loading ? "Memuat desa..." : "Pilih Desa", + ), + const SizedBox(height: 16), + _label("Dusun"), + _dropdown( + value: isKader ? _dusunId : null, + items: dusunList + .map((e) => { + "id": e["id"].toString(), + "nama": e["nama_dusun"] + }) + .toList(), + onChanged: + isKader ? (v) => setState(() => _dusunId = v) : null, + disabled: !isKader, + hint: _loading ? "Memuat dusun..." : "Pilih Dusun", + ), + const SizedBox(height: 16), + _label("No HP"), + _input(_noHp, + error: _errNoHp, + type: TextInputType.number, + limit: 13, + isNumberOnly: true), + const SizedBox(height: 32), + SizedBox( + width: double.infinity, + child: OutlinedButton( + onPressed: _loading ? null : _update, + style: OutlinedButton.styleFrom( + backgroundColor: Colors.white, + side: + const BorderSide(color: Colors.orange, width: 2), + padding: const EdgeInsets.symmetric(vertical: 16), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10)), + ), + child: _loading + ? const SizedBox( + height: 15, + width: 15, + child: CircularProgressIndicator( + strokeWidth: 2, color: Colors.orange)) + : Text("Simpan Perubahan", + style: GoogleFonts.poppins( + color: Colors.orange, + fontWeight: FontWeight.bold, + fontSize: 12)), + ), + ), + ], + ), + ), + const SizedBox(height: 20), + ], + ), + ), + ), + ); + } + + Widget _label(String t) => Padding( + padding: const EdgeInsets.only(bottom: 6), + child: Text(t, + style: + GoogleFonts.poppins(fontWeight: FontWeight.w600, fontSize: 12)), + ); + + Widget _input( + TextEditingController c, { + String? error, + TextInputType type = TextInputType.text, + int? limit, + bool isNumberOnly = false, + }) => + TextField( + controller: c, + maxLength: limit, + keyboardType: type, + inputFormatters: isNumberOnly ? [FilteringTextInputFormatter.digitsOnly] : null, + style: GoogleFonts.poppins(fontSize: 12), + decoration: InputDecoration( + errorText: error, + errorStyle: GoogleFonts.poppins(color: Colors.red, fontSize: 10), + contentPadding: + const EdgeInsets.symmetric(horizontal: 12, vertical: 12), + border: OutlineInputBorder(borderRadius: BorderRadius.circular(10)), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: const BorderSide(color: Colors.grey)), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: const BorderSide(color: Colors.orange, width: 2)), + ).copyWith(counterText: ""), + ); + + Widget _dropdown({ + required String? value, + required List> items, + required Function(String?)? onChanged, + bool disabled = false, + String hint = "Pilih", + }) { + String? validValue; + if (value != null) { + for (var item in items) { + if (item["id"].toString() == value.toString()) { + validValue = item["id"].toString(); + break; + } + } + } + + return DropdownButtonFormField( + isExpanded: true, + value: validValue, + hint: Text(hint, style: GoogleFonts.poppins(fontSize: 12)), + style: GoogleFonts.poppins( + fontSize: 12, color: disabled ? Colors.grey : Colors.black), + decoration: InputDecoration( + filled: disabled, + fillColor: disabled ? Colors.grey[200] : Colors.white, + contentPadding: const EdgeInsets.symmetric(horizontal: 12), + border: OutlineInputBorder(borderRadius: BorderRadius.circular(10)), + ), + items: items.map((e) { + return DropdownMenuItem( + value: e["id"].toString(), + child: Text(e["nama"].toString(), overflow: TextOverflow.ellipsis), + ); + }).toList(), + onChanged: onChanged, + ); + } +} \ No newline at end of file diff --git a/lib/pages/landing_page.dart b/lib/pages/landing_page.dart new file mode 100644 index 0000000..7a95b03 --- /dev/null +++ b/lib/pages/landing_page.dart @@ -0,0 +1,119 @@ +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; + +class LandingPage extends StatelessWidget { + const LandingPage({super.key}); + + @override + Widget build(BuildContext context) { + return Theme( + data: Theme.of(context).copyWith( + textTheme: GoogleFonts.poppinsTextTheme( + Theme.of(context).textTheme, + ), + ), + child: Scaffold( + backgroundColor: Colors.white, + body: SafeArea( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 24), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const SizedBox(height: 32), + + // ===== JUDUL ===== + Center( + child: Text( + 'M-Posyandu', + style: GoogleFonts.poppins( + fontSize: 22, + fontWeight: FontWeight.w700, + letterSpacing: 1, + ), + ), + ), + + const SizedBox(height: 24), + + // ===== ILUSTRASI ===== + Center( + child: Image.asset( + 'assets/images/logoo.webp', + height: 230, + fit: BoxFit.contain, + ), + ), + + const SizedBox(height: 35), + + // ===== HEADER ===== + Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + 'Selamat Datang di M-Posyandu', + style: GoogleFonts.poppins( + fontSize: 18, + fontWeight: FontWeight.w600, + ), + ), + const SizedBox(width: 6), + const Icon( + Icons.favorite, + color: Colors.blue, + size: 20, + ), + ], + ), + + const SizedBox(height: 6), + + // ===== DESKRIPSI ===== + Text( + 'Bersama M-Posyandu mari pantau kesehatan dan tumbuh kembang anak serta ' + 'kelola jadwal posyandu dalam satu genggaman', + style: GoogleFonts.nunito( + fontSize: 12, + color: const Color.fromARGB(255, 109, 108, 108), + height: 1.4, + ), + ), + + const SizedBox(height: 60), + + // ===== BUTTON LANJUT ===== + SizedBox( + width: double.infinity, + height: 50, + child: ElevatedButton( + onPressed: () { + Navigator.pushNamed(context, '/login'); + }, + style: ElevatedButton.styleFrom( + elevation: 3, + backgroundColor: const Color.fromARGB(255, 19, 133, 226), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(14), + ), + ), + child: Text( + 'Lanjut', + style: GoogleFonts.poppins( + color: Colors.white, + fontSize: 16, + fontWeight: FontWeight.w700, + ), + ), + ), + ), + + const SizedBox(height: 30), + ], + ), + ), + ), + ), + ); + } +} diff --git a/lib/pages/login_page.dart b/lib/pages/login_page.dart new file mode 100644 index 0000000..587654a --- /dev/null +++ b/lib/pages/login_page.dart @@ -0,0 +1,516 @@ +import 'dart:convert'; +import 'dart:developer'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:http/http.dart' as http; +import 'package:shared_preferences/shared_preferences.dart'; + +class LoginPage extends StatefulWidget { + final bool fromGuard; + + const LoginPage({ + super.key, + this.fromGuard = false, + }); + + @override + State createState() => _LoginPageState(); +} + +class _LoginPageState extends State { + final TextEditingController _emailController = TextEditingController(); + final TextEditingController _passwordController = TextEditingController(); + + final TextEditingController _forgotEmailController = TextEditingController(); + final TextEditingController _otpController = TextEditingController(); + final TextEditingController _newPasswordController = TextEditingController(); + + bool _isPasswordHidden = true; + bool _isNewPasswordHidden = true; + bool _isLoading = false; + + String? _loginErrorMessage; + String? _dialogErrorMessage; + + // Sesuaikan baseUrl jika menggunakan HP fisik (gunakan IP Laptop) + static const String baseUrl = "http://ta.myhost.id/E31230549/mposyandu_api"; + + final String loginUrl = "$baseUrl/login.php"; + final String forgotPasswordUrl = "$baseUrl/forgot_password.php"; + final String resetPasswordUrl = "$baseUrl/reset_password.php"; + + @override + void initState() { + super.initState(); + if (widget.fromGuard) { + _loginErrorMessage = "Anda harus login terlebih dahulu"; + } + } + + // ================= LOGIN FUNCTION (PERBAIKAN LOGIKA NIK & SHOWDIALOG) ================= + Future _login() async { + final email = _emailController.text.trim(); + final password = _passwordController.text.trim(); + + setState(() => _loginErrorMessage = null); + + if (email.isEmpty || password.isEmpty) { + setState(() => _loginErrorMessage = "Email dan password wajib diisi"); + return; + } + + setState(() => _isLoading = true); + + try { + log("Memulai proses login untuk: $email"); + + final response = await http.post( + Uri.parse(loginUrl), + body: {"email": email, "password": password}, + ).timeout(const Duration(seconds: 10)); + + log("Response Server: ${response.body}"); + + if (response.statusCode == 200) { + final data = json.decode(response.body); + + if (data["success"] == true) { + final prefs = await SharedPreferences.getInstance(); + final Map user = data["user"]; + + // 1. Simpan Status Login + await prefs.setBool("isLogin", true); + + // 2. Simpan password yang diketik untuk pengecekan showDialog di Dashboard Ibu + await prefs.setString("last_entered_password", password); + + // 3. Simpan semua data user secara dinamis + List> saves = []; + user.forEach((key, value) { + saves.add(prefs.setString(key, value?.toString() ?? "")); + }); + + // 4. Pastikan id_user tersimpan (Dashboard sering mencari key ini) + if (user.containsKey("id")) { + saves.add(prefs.setString("id_user", user["id"].toString())); + } + + // 5. Pastikan NIK tersimpan (Penting untuk perbandingan password default) + if (user.containsKey("nik")) { + saves.add(prefs.setString("nik", user["nik"].toString())); + } + + await Future.wait(saves); + + if (!mounted) return; + + String role = user["role"] ?? ""; + switch (role.toLowerCase()) { + case "admin": + Navigator.pushReplacementNamed(context, '/dashboard-admin'); + break; + case "kader": + Navigator.pushReplacementNamed(context, '/dashboard-kader'); + break; + case "bidan": + Navigator.pushReplacementNamed(context, '/dashboard-bidan'); + break; + case "ibu": + Navigator.pushReplacementNamed(context, '/dashboard-ibu'); + break; + default: + setState(() => _loginErrorMessage = "Role tidak dikenali"); + } + } else { + setState(() => _loginErrorMessage = data["message"] ?? "Login gagal"); + } + } else { + setState( + () => _loginErrorMessage = "Server error: ${response.statusCode}"); + } + } catch (e) { + log("Error Login: $e"); + setState(() => _loginErrorMessage = "Gagal terhubung ke server."); + } finally { + if (mounted) setState(() => _isLoading = false); + } + } + + // ================= FORGOT PASSWORD FUNCTIONS (TETAP SAMA) ================= + + Future _sendOtp(StateSetter setDialogState) async { + final email = _forgotEmailController.text.trim(); + setDialogState(() => _dialogErrorMessage = null); + + if (email.isEmpty) { + setDialogState(() => _dialogErrorMessage = "Masukkan email Anda"); + return; + } + + _showLoadingDialog(); + + try { + final response = await http.post( + Uri.parse(forgotPasswordUrl), + body: {"email": email}, + ).timeout(const Duration(seconds: 20)); + + if (!mounted) return; + Navigator.pop(context); + + final data = json.decode(response.body); + if (data["success"] == true) { + Navigator.pop(context); + _showOtpDialog(); + } else { + setDialogState(() => + _dialogErrorMessage = data["message"] ?? "Email tidak ditemukan"); + } + } catch (e) { + if (mounted) Navigator.pop(context); + setDialogState( + () => _dialogErrorMessage = "Kesalahan koneksi: Gagal mengirim OTP"); + } + } + + Future _resetPassword(StateSetter setDialogState) async { + final email = _forgotEmailController.text.trim(); + final otp = _otpController.text.trim(); + final newPass = _newPasswordController.text.trim(); + + setDialogState(() => _dialogErrorMessage = null); + + if (otp.isEmpty || newPass.isEmpty) { + setDialogState(() => _dialogErrorMessage = "Lengkapi semua field"); + return; + } + + final hasLetter = RegExp(r'[a-zA-Z]').hasMatch(newPass); + final hasDigit = RegExp(r'[0-9]').hasMatch(newPass); + + if (newPass.length != 6 || !hasLetter || !hasDigit) { + setDialogState( + () => _dialogErrorMessage = "Gunakan 6 karakter (huruf & angka)"); + return; + } + + _showLoadingDialog(); + + try { + final response = await http.post( + Uri.parse(resetPasswordUrl), + body: { + "email": email, + "otp": otp, + "new_password": newPass, + }, + ).timeout(const Duration(seconds: 15)); + + if (!mounted) return; + Navigator.pop(context); + + final data = json.decode(response.body); + if (data["success"] == true) { + Navigator.pop(context); + _showMessage("Password berhasil direset!"); + _clearForgotControllers(); + } else { + setDialogState( + () => _dialogErrorMessage = data["message"] ?? "OTP salah"); + } + } catch (e) { + if (mounted) Navigator.pop(context); + setDialogState(() => _dialogErrorMessage = "Gagal mereset password"); + } + } + + // ================= DIALOGS & UI HELPERS (TETAP SAMA) ================= + + void _showForgotPasswordDialog() { + _dialogErrorMessage = null; + showDialog( + context: context, + builder: (context) => StatefulBuilder(builder: (context, setDialogState) { + return AlertDialog( + backgroundColor: Colors.white, + surfaceTintColor: Colors.white, + shape: + RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)), + title: Text("Lupa Password", + style: GoogleFonts.poppins( + fontWeight: FontWeight.bold, color: Colors.black)), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + TextField( + controller: _forgotEmailController, + decoration: InputDecoration( + hintText: "Email terdaftar", + prefixIcon: const Icon(Icons.email, color: Colors.blue), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10)), + ), + keyboardType: TextInputType.emailAddress, + ), + if (_dialogErrorMessage != null) + Padding( + padding: const EdgeInsets.only(top: 8, left: 4), + child: Text(_dialogErrorMessage!, + style: + GoogleFonts.poppins(color: Colors.red, fontSize: 12)), + ), + ], + ), + actions: [ + OutlinedButton( + onPressed: () => Navigator.pop(context), + style: OutlinedButton.styleFrom( + side: const BorderSide(color: Colors.red), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(8)), + ), + child: + Text("Batal", style: GoogleFonts.poppins(color: Colors.red)), + ), + OutlinedButton( + onPressed: () => _sendOtp(setDialogState), + style: OutlinedButton.styleFrom( + side: const BorderSide(color: Colors.blue), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(8)), + ), + child: Text("Kirim OTP", + style: GoogleFonts.poppins(color: Colors.blue)), + ), + ], + ); + }), + ); + } + + void _showOtpDialog() { + _dialogErrorMessage = null; + showDialog( + context: context, + barrierDismissible: false, + builder: (context) => StatefulBuilder( + builder: (context, setDialogState) { + return AlertDialog( + backgroundColor: Colors.white, + surfaceTintColor: Colors.white, + shape: + RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)), + title: Text("Verifikasi OTP", + style: GoogleFonts.poppins( + fontWeight: FontWeight.bold, color: Colors.black)), + content: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text("Masukkan kode OTP dan password baru", + style: GoogleFonts.poppins(fontSize: 12)), + const SizedBox(height: 15), + TextField( + controller: _otpController, + decoration: InputDecoration( + labelText: "Kode OTP", + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10))), + keyboardType: TextInputType.number, + ), + const SizedBox(height: 15), + TextField( + controller: _newPasswordController, + obscureText: _isNewPasswordHidden, + inputFormatters: [ + LengthLimitingTextInputFormatter(6), + FilteringTextInputFormatter.allow(RegExp(r'[a-zA-Z0-9]')), + ], + decoration: InputDecoration( + labelText: "Password Baru (6 Karakter)", + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10)), + suffixIcon: IconButton( + icon: Icon(_isNewPasswordHidden + ? Icons.visibility + : Icons.visibility_off), + onPressed: () => setDialogState( + () => _isNewPasswordHidden = !_isNewPasswordHidden), + ), + ), + ), + if (_dialogErrorMessage != null) + Padding( + padding: const EdgeInsets.only(top: 8, left: 4), + child: Text(_dialogErrorMessage!, + style: GoogleFonts.poppins( + color: Colors.red, fontSize: 12)), + ), + ], + ), + ), + actions: [ + OutlinedButton( + onPressed: () => Navigator.pop(context), + style: OutlinedButton.styleFrom( + side: const BorderSide(color: Colors.red), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(8)), + ), + child: Text("Batal", + style: GoogleFonts.poppins(color: Colors.red)), + ), + OutlinedButton( + onPressed: () => _resetPassword(setDialogState), + style: OutlinedButton.styleFrom( + side: const BorderSide(color: Colors.blue), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(8)), + ), + child: Text("Simpan", + style: GoogleFonts.poppins(color: Colors.blue)), + ), + ], + ); + }, + ), + ); + } + + void _showLoadingDialog() { + showDialog( + context: context, + barrierDismissible: false, + builder: (context) => const Center(child: CircularProgressIndicator()), + ); + } + + void _showMessage(String msg) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(msg, style: GoogleFonts.poppins()), + backgroundColor: Colors.green, + behavior: SnackBarBehavior.floating, + ), + ); + } + + void _clearForgotControllers() { + _forgotEmailController.clear(); + _otpController.clear(); + _newPasswordController.clear(); + _isNewPasswordHidden = true; + _dialogErrorMessage = null; + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: Colors.white, + body: SafeArea( + child: Center( + child: SingleChildScrollView( + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + children: [ + const SizedBox(height: 20), + Text("M-Posyandu", + style: GoogleFonts.poppins( + fontSize: 26, fontWeight: FontWeight.w700)), + const SizedBox(height: 30), + SizedBox( + width: 300, + child: Image.asset("assets/images/logoo.webp", + fit: BoxFit.contain, + errorBuilder: (c, e, s) => + const Icon(Icons.image, size: 100)), + ), + const SizedBox(height: 30), + Align( + alignment: Alignment.centerLeft, + child: Text("Selamat Datang Ayo Login Sekarang", + style: GoogleFonts.poppins( + fontSize: 18, fontWeight: FontWeight.w600)), + ), + const SizedBox(height: 20), + TextField( + controller: _emailController, + decoration: InputDecoration( + labelText: "Email", + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(15)), + ), + keyboardType: TextInputType.emailAddress, + ), + const SizedBox(height: 15), + TextField( + controller: _passwordController, + obscureText: _isPasswordHidden, + decoration: InputDecoration( + labelText: "Password", + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(15)), + suffixIcon: IconButton( + icon: Icon(_isPasswordHidden + ? Icons.visibility + : Icons.visibility_off), + onPressed: () => setState( + () => _isPasswordHidden = !_isPasswordHidden), + ), + ), + ), + if (_loginErrorMessage != null) + Align( + alignment: Alignment.centerLeft, + child: Padding( + padding: const EdgeInsets.only(top: 8, left: 4), + child: Text(_loginErrorMessage!, + style: GoogleFonts.poppins( + color: Colors.red, + fontSize: 13, + fontWeight: FontWeight.w500)), + ), + ), + Align( + alignment: Alignment.centerRight, + child: TextButton( + onPressed: _showForgotPasswordDialog, + child: Text("Lupa Password?", + style: GoogleFonts.poppins( + color: Colors.blue, fontWeight: FontWeight.w500)), + ), + ), + const SizedBox(height: 10), + SizedBox( + width: double.infinity, + height: 50, + child: ElevatedButton( + onPressed: _isLoading ? null : _login, + style: ElevatedButton.styleFrom( + backgroundColor: Colors.blue, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10)), + ), + child: _isLoading + ? const CircularProgressIndicator(color: Colors.white) + : Text("LOGIN", + style: GoogleFonts.poppins( + color: Colors.white, + fontSize: 16, + fontWeight: FontWeight.w600)), + ), + ), + ], + ), + ), + ), + ), + ), + ); + } +} diff --git a/lib/pages/petugas.dart b/lib/pages/petugas.dart new file mode 100644 index 0000000..a20fa80 --- /dev/null +++ b/lib/pages/petugas.dart @@ -0,0 +1,371 @@ +import 'dart:async'; +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:http/http.dart' as http; +import 'package:google_fonts/google_fonts.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../layout/main_layout.dart'; +import '../pages/petugas_drawer.dart'; +import '../pages/login_page.dart'; +import '../pages/tambah_petugas.dart'; +import '../pages/edit_petugas.dart'; + +class DataPetugasPage extends StatefulWidget { + const DataPetugasPage({super.key}); + + @override + State createState() => _DataPetugasPageState(); +} + +class _DataPetugasPageState extends State { + final TextEditingController _searchController = TextEditingController(); + Timer? _debounce; + + int _rowsPerPage = 10; + int _currentPage = 0; + int _totalData = 0; + + List> _allData = []; + bool _isLoading = false; + bool _isAuthorized = false; + + final String baseUrl = "http://ta.myhost.id/E31230549/mposyandu_api/petugas/get_users.php"; + final String deleteUrl = + "http://ta.myhost.id/E31230549/mposyandu_api/petugas/delete_petugas.php"; + + @override + void initState() { + super.initState(); + checkLogin(); + } + + @override + void dispose() { + _debounce?.cancel(); + _searchController.dispose(); + super.dispose(); + } + + Future checkLogin() async { + final prefs = await SharedPreferences.getInstance(); + final isLogin = prefs.getBool("isLogin") ?? false; + if (!isLogin) { + if (!mounted) return; + Navigator.pushAndRemoveUntil( + context, + MaterialPageRoute(builder: (_) => const LoginPage(fromGuard: true)), + (route) => false, + ); + return; + } + setState(() => _isAuthorized = true); + await fetchUsers(); + } + + Future fetchUsers() async { + if (!_isAuthorized || !mounted) return; + setState(() => _isLoading = true); + try { + final url = Uri.parse(baseUrl).replace(queryParameters: { + "page": (_currentPage + 1).toString(), + "limit": _rowsPerPage.toString(), + "search": _searchController.text.trim(), + }); + final response = await http.get(url); + if (response.statusCode == 200) { + final decoded = json.decode(response.body); + if (decoded["success"] == true) { + setState(() { + _allData = List>.from(decoded["data"] ?? []); + _totalData = decoded["total"] ?? 0; + }); + } + } + } catch (e) { + debugPrint("ERROR FETCH: $e"); + } finally { + if (mounted) setState(() => _isLoading = false); + } + } + + // --- LOGIKA SEMBUNYIKAN DESA/DUSUN BERDASARKAN ROLE --- + void _showDetailDialog(Map data) { + // Ambil role dan ubah ke lowercase agar pengecekan lebih akurat + String role = (data["role"] ?? "").toString().toLowerCase(); + bool isStaff = role == "admin" || role == "bidan"; + + showDialog( + context: context, + builder: (context) => AlertDialog( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)), + title: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text("Detail Petugas", + style: GoogleFonts.poppins( + fontWeight: FontWeight.bold, fontSize: 16)), + IconButton( + icon: const Icon(Icons.close, color: Colors.red), + onPressed: () => Navigator.pop(context)), + ], + ), + content: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _detailItem("Email", data["email"]), + + // Tampilkan Desa & Dusun HANYA jika role BUKAN admin/bidan + if (!isStaff) ...[ + _detailItem("Desa", data["nama_desa"]), + _detailItem("Dusun", data["nama_dusun"]), + ], + + _detailItem("No HP", data["no_hp"]), + ], + ), + ), + ), + ); + } + + Widget _detailItem(String label, dynamic value) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 6), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(label, + style: + GoogleFonts.poppins(fontSize: 10, color: Colors.grey[600])), + const SizedBox(height: 2), + Text(value?.toString() ?? "-", + style: GoogleFonts.poppins( + fontSize: 13, + fontWeight: FontWeight.w500, + color: Colors.black87)), + const Divider(thickness: 0.5), + ], + ), + ); + } + + Future _deletePetugas(String id) async { + final confirm = await showDialog( + context: context, + builder: (context) => AlertDialog( + title: Text("Konfirmasi", + style: + GoogleFonts.poppins(fontSize: 14, fontWeight: FontWeight.bold)), + content: const Text("Yakin ingin menghapus petugas ini?"), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context, false), + child: const Text("Batal")), + ElevatedButton( + onPressed: () => Navigator.pop(context, true), + style: ElevatedButton.styleFrom(backgroundColor: Colors.red), + child: const Text("Hapus", style: TextStyle(color: Colors.white)), + ), + ], + ), + ); + if (confirm != true) return; + try { + final res = await http.post(Uri.parse(deleteUrl), body: {"id": id}); + if (json.decode(res.body)["success"]) fetchUsers(); + } catch (e) { + debugPrint("Delete error: $e"); + } + } + + @override + Widget build(BuildContext context) { + int totalPages = (_totalData / _rowsPerPage).ceil(); + if (totalPages == 0) totalPages = 1; + + return MainLayout( + title: "", + drawer: const DrawerPetugas(), + body: Padding( + padding: const EdgeInsets.all(16), + child: Column( + children: [ + Text("Data Petugas", + style: GoogleFonts.poppins( + fontSize: 18, fontWeight: FontWeight.bold)), + const SizedBox(height: 16), + Row( + children: [ + Expanded( + child: TextField( + controller: _searchController, + style: GoogleFonts.poppins(fontSize: 13), + decoration: InputDecoration( + hintText: "Cari nama...", + prefixIcon: const Icon(Icons.search, size: 20), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10)), + contentPadding: + const EdgeInsets.symmetric(horizontal: 10), + ), + onChanged: (v) { + _debounce?.cancel(); + _debounce = Timer(const Duration(milliseconds: 500), () { + _currentPage = 0; + fetchUsers(); + }); + }, + ), + ), + const SizedBox(width: 8), + ElevatedButton( + onPressed: () async { + final res = await Navigator.push( + context, + MaterialPageRoute( + builder: (_) => const TambahPetugasPage())); + if (res == true) fetchUsers(); + }, + style: ElevatedButton.styleFrom( + backgroundColor: Colors.blue, + padding: const EdgeInsets.all(12), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10)), + ), + child: const Icon(Icons.add, color: Colors.white), + ) + ], + ), + const SizedBox(height: 16), + Expanded( + child: _isLoading + ? const Center(child: CircularProgressIndicator()) + : _allData.isEmpty + ? const Center(child: Text("Data tidak ditemukan")) + : ListView.builder( + itemCount: _allData.length, + itemBuilder: (context, index) { + final item = _allData[index]; + return Card( + elevation: 0, + margin: const EdgeInsets.only(bottom: 12), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + side: BorderSide( + color: Colors.grey.shade300, width: 1), + ), + child: Padding( + padding: const EdgeInsets.all(12), + child: Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + Text(item["nama"] ?? "", + style: GoogleFonts.poppins( + fontWeight: FontWeight.bold, + fontSize: 14)), + const SizedBox(height: 4), + Container( + padding: const EdgeInsets.symmetric( + horizontal: 8, vertical: 2), + decoration: BoxDecoration( + color: + Colors.blue.withOpacity(0.1), + borderRadius: + BorderRadius.circular(6), + ), + child: Text(item["role"] ?? "", + style: GoogleFonts.poppins( + fontSize: 11, + color: Colors.blue, + fontWeight: + FontWeight.w600)), + ), + ], + ), + ), + _actionButton(Icons.visibility, Colors.blue, + () => _showDetailDialog(item)), + const SizedBox(width: 8), + _actionButton(Icons.edit, Colors.orange, + () async { + final res = await Navigator.push( + context, + MaterialPageRoute( + builder: (_) => + EditPetugasPage(data: item))); + if (res == true) fetchUsers(); + }), + const SizedBox(width: 8), + _actionButton( + Icons.delete, + Colors.red, + () => _deletePetugas( + item["id"].toString())), + ], + ), + ), + ); + }, + ), + ), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text("Halaman ${_currentPage + 1} dari $totalPages", + style: GoogleFonts.poppins(fontSize: 12)), + Row( + children: [ + IconButton( + icon: const Icon(Icons.chevron_left), + onPressed: _currentPage == 0 + ? null + : () { + setState(() => _currentPage--); + fetchUsers(); + }, + ), + IconButton( + icon: const Icon(Icons.chevron_right), + onPressed: _currentPage >= totalPages - 1 + ? null + : () { + setState(() => _currentPage++); + fetchUsers(); + }, + ), + ], + ) + ], + ) + ], + ), + ), + ); + } + + Widget _actionButton(IconData icon, Color color, VoidCallback onTap) { + return Material( + color: Colors.transparent, + child: InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(8), + child: Container( + padding: const EdgeInsets.all(8), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(8), + border: Border.all(color: color, width: 1.5), + ), + child: Icon(icon, color: color, size: 18), + ), + ), + ); + } +} diff --git a/lib/pages/petugas_drawer.dart b/lib/pages/petugas_drawer.dart new file mode 100644 index 0000000..5a73576 --- /dev/null +++ b/lib/pages/petugas_drawer.dart @@ -0,0 +1,184 @@ +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +class DrawerPetugas extends StatefulWidget { + const DrawerPetugas({super.key}); + + @override + State createState() => _DrawerPetugasState(); +} + +class _DrawerPetugasState extends State { + static const Color mainColor = Colors.blue; + String? fotoUser; + String namaUser = "Admin"; + + @override + void initState() { + super.initState(); + _loadUserData(); + } + + // Fungsi untuk mengambil data dari SharedPreferences + Future _loadUserData() async { + final prefs = await SharedPreferences.getInstance(); + setState(() { + fotoUser = prefs.getString('foto'); + namaUser = prefs.getString('nama') ?? "Admin"; + }); + } + + @override + Widget build(BuildContext context) { + return Drawer( + child: Column( + children: [ + // ===== HEADER ===== + Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(vertical: 40), + decoration: const BoxDecoration( + color: mainColor, + ), + child: InkWell( + onTap: () { + Navigator.pop(context); // Tutup drawer + Navigator.pushNamed( + context, '/profile-admin'); // Pindah ke profil + }, + child: Column( + children: [ + CircleAvatar( + radius: 40, + backgroundColor: Colors.white, + child: CircleAvatar( + radius: 37, + backgroundColor: Colors.blue.shade100, + backgroundImage: (fotoUser != null && + fotoUser!.isNotEmpty) + ? NetworkImage( + "http://ta.myhost.id/E31230549/mposyandu_api/uploads/$fotoUser") + : null, + child: (fotoUser == null || fotoUser!.isEmpty) + ? const Icon( + Icons.person, + size: 40, + color: mainColor, + ) + : null, + ), + ), + const SizedBox(height: 10), + Text( + namaUser, + style: GoogleFonts.poppins( + color: Colors.white, + fontSize: 16, + fontWeight: FontWeight.normal, // DIUBAH KE NORMAL + ), + ), + Text( + "Lihat Profil", + style: GoogleFonts.poppins( + color: Colors.white70, + fontSize: 12, + decoration: + TextDecoration.none, // GARIS BAWAH DIHAPUS DISINI + ), + ), + ], + ), + ), + ), + + // ===== MENU ===== + Expanded( + child: ListView( + padding: EdgeInsets.zero, + children: [ + _buildMenuItem( + context, + icon: Icons.dashboard, + title: "Dashboard", + route: '/dashboard-admin', + ), + _buildMenuItem( + context, + icon: Icons.people, + title: "Petugas", + route: '/data-petugas', + ), + _buildMenuItem( + context, + icon: Icons.location_city, + title: "Desa", + route: '/data-desa', + ), + _buildMenuItem( + context, + icon: Icons.map, + title: "Dusun", + route: '/data-dusun', + ), + ], + ), + ), + + // ===== LOGOUT ===== + const Divider(), + SafeArea( + child: ListTile( + leading: const Icon(Icons.logout, color: mainColor), + title: Text( + "Logout", + style: GoogleFonts.poppins( + fontWeight: FontWeight.normal, // DIUBAH KE NORMAL + color: Colors.black, + ), + ), + onTap: () => _logout(context), + ), + ), + ], + ), + ); + } + + // Helper Widget untuk Menu agar kode lebih bersih + Widget _buildMenuItem(BuildContext context, + {required IconData icon, required String title, required String route}) { + return ListTile( + leading: Icon(icon, color: mainColor), + title: Text( + title, + style: GoogleFonts.poppins( + fontWeight: FontWeight.normal, // DIUBAH KE NORMAL + fontSize: 14, + ), + ), + onTap: () { + Navigator.pop(context); + Navigator.pushNamed(context, route); + }, + ); + } + + // ===== FUNCTION LOGOUT ===== + Future _logout(BuildContext context) async { + final prefs = await SharedPreferences.getInstance(); + + await prefs.remove("isLogin"); + await prefs.remove("role"); + await prefs.remove("nama"); + await prefs.remove("foto"); + + if (!context.mounted) return; + + Navigator.pushNamedAndRemoveUntil( + context, + '/login', + (route) => false, + ); + } +} diff --git a/lib/pages/profile_admin.dart b/lib/pages/profile_admin.dart new file mode 100644 index 0000000..ffebbf9 --- /dev/null +++ b/lib/pages/profile_admin.dart @@ -0,0 +1,484 @@ +import 'dart:io'; +import 'dart:convert'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:image_picker/image_picker.dart'; +import 'package:http/http.dart' as http; +import '../pages/login_page.dart'; +import '../pages/dashboard_admin.dart'; + +class ProfileAdminPage extends StatefulWidget { + const ProfileAdminPage({super.key}); + + @override + State createState() => _ProfileKaderPageState(); +} + +class _ProfileKaderPageState extends State { + final TextEditingController namaC = TextEditingController(); + final TextEditingController emailC = TextEditingController(); + final TextEditingController passwordC = TextEditingController(); + final TextEditingController roleC = TextEditingController(); + final TextEditingController desaIdC = TextEditingController(); + final TextEditingController dusuIdC = TextEditingController(); + final TextEditingController noHpC = TextEditingController(); + final TextEditingController statusC = TextEditingController(); + + String? idUser; + String? fotoUser; + XFile? _pickedFile; + bool _obscurePassword = true; + bool isEditMode = false; + + @override + void initState() { + super.initState(); + _loadUserData(); + } + + @override + void dispose() { + namaC.dispose(); + emailC.dispose(); + passwordC.dispose(); + roleC.dispose(); + desaIdC.dispose(); + dusuIdC.dispose(); + noHpC.dispose(); + statusC.dispose(); + super.dispose(); + } + + Future _loadUserData() async { + final prefs = await SharedPreferences.getInstance(); + final isLogin = prefs.getBool('isLogin') ?? false; + + if (!isLogin) { + if (!mounted) return; + Navigator.pushAndRemoveUntil( + context, + MaterialPageRoute(builder: (_) => const LoginPage(fromGuard: true)), + (route) => false, + ); + return; + } + + setState(() { + idUser = prefs.getString('id_user') ?? ""; + namaC.text = prefs.getString('nama') ?? ""; + emailC.text = prefs.getString('email') ?? ""; + passwordC.text = prefs.getString('password') ?? ""; + roleC.text = (prefs.getString('role') ?? "Kader").toLowerCase(); + desaIdC.text = prefs.getString('nama_desa') ?? "-"; + dusuIdC.text = prefs.getString('nama_dusun') ?? "-"; + + String savedNoHp = prefs.getString('no_hp') ?? ""; + noHpC.text = (savedNoHp.isEmpty || savedNoHp == "-") ? "-" : savedNoHp; + + statusC.text = prefs.getString('status_aktif') ?? "Aktif"; + fotoUser = prefs.getString('foto'); + }); + } + + // Fungsi untuk menampilkan SnackBar Peringatan + void _showEditWarning() { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text("Klik tombol edit di bawah untuk mengubah foto."), + backgroundColor: Colors.red, + duration: Duration(seconds: 2), + ), + ); + } + + Future _pickImage() async { + // Jika belum mode edit, tampilkan snackbar dan hentikan fungsi + if (!isEditMode) { + _showEditWarning(); + return; + } + + final ImagePicker picker = ImagePicker(); + final XFile? image = await picker.pickImage(source: ImageSource.gallery); + + if (image != null) { + setState(() { + _pickedFile = image; + }); + } + } + + void _removeImage() { + // Jika belum mode edit, tampilkan snackbar dan hentikan fungsi + if (!isEditMode) { + _showEditWarning(); + return; + } + + setState(() { + _pickedFile = null; + fotoUser = ""; + }); + } + + void _enableEdit() { + setState(() { + isEditMode = true; + }); + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text("Mode edit diaktifkan"), + backgroundColor: Colors.orange, + ), + ); + } + + bool _validatePassword(String value) { + String pattern = r'^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6}$'; + RegExp regExp = RegExp(pattern); + return regExp.hasMatch(value); + } + + bool _validateNoHp(String value) { + String pattern = r'^[0-9]{10,13}$'; + RegExp regExp = RegExp(pattern); + return regExp.hasMatch(value); + } + + void _saveProfile() async { + if (!isEditMode) return; + + if (!_validateNoHp(noHpC.text)) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text("No. HP harus berupa angka dan berjumlah 10-13 digit!"), + backgroundColor: Colors.red, + ), + ); + return; + } + + if (!_validatePassword(passwordC.text)) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text("Password harus 6 digit (kombinasi huruf & angka)!"), + backgroundColor: Colors.red, + ), + ); + return; + } + + try { + var request = http.MultipartRequest( + 'POST', + Uri.parse( + "http://ta.myhost.id/E31230549/mposyandu_api/users/update_profile_kader.php"), + ); + + request.fields['id_user'] = idUser ?? ""; + request.fields['nama'] = namaC.text; + request.fields['email'] = emailC.text; + request.fields['password'] = passwordC.text; + request.fields['no_hp'] = noHpC.text; + request.fields['foto_lama'] = fotoUser ?? ""; + + if (_pickedFile != null) { + Uint8List data = await _pickedFile!.readAsBytes(); + request.files.add(http.MultipartFile.fromBytes( + 'foto', + data, + filename: _pickedFile!.name, + )); + } + + var response = await request.send(); + var responseData = await response.stream.bytesToString(); + var result = json.decode(responseData); + + if (result['status'] == 'success') { + final prefs = await SharedPreferences.getInstance(); + + await prefs.setString('nama', namaC.text); + await prefs.setString('email', emailC.text); + await prefs.setString('password', passwordC.text); + await prefs.setString('no_hp', noHpC.text); + + if (result['foto'] != null) { + await prefs.setString('foto', result['foto']); + setState(() { + fotoUser = result['foto']; + }); + } + + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text("Profil berhasil diperbarui"), + backgroundColor: Colors.green), + ); + + setState(() { + isEditMode = false; + _pickedFile = null; + }); + } else { + throw result['message']; + } + } catch (e) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text("Gagal menyimpan: $e"), backgroundColor: Colors.red), + ); + } + } + + @override + Widget build(BuildContext context) { + bool hasPhoto = + _pickedFile != null || (fotoUser != null && fotoUser!.isNotEmpty); + + return Scaffold( + backgroundColor: const Color(0xfff4f6fb), + appBar: AppBar( + backgroundColor: Colors.blue, + elevation: 0, + leading: IconButton( + icon: const Icon(Icons.arrow_back, color: Colors.white), + onPressed: () { + Navigator.pushAndRemoveUntil( + context, + MaterialPageRoute( + builder: (context) => const DashboardAdminPage()), + (route) => false, + ); + }, + ), + title: Text("", + style: GoogleFonts.poppins(color: Colors.white, fontSize: 18)), + ), + body: SingleChildScrollView( + child: Column( + children: [ + Container( + width: double.infinity, + decoration: const BoxDecoration( + color: Colors.blue, + borderRadius: BorderRadius.only( + bottomLeft: Radius.circular(30), + bottomRight: Radius.circular(30), + ), + ), + padding: const EdgeInsets.only(bottom: 30), + child: Column( + children: [ + Stack( + children: [ + CircleAvatar( + radius: 65, + backgroundColor: Colors.white, + child: CircleAvatar( + radius: 60, + backgroundColor: Colors.blue.shade100, + backgroundImage: _pickedFile != null + ? (kIsWeb + ? NetworkImage(_pickedFile!.path) + : FileImage(File(_pickedFile!.path)) + as ImageProvider) + : (fotoUser != null && fotoUser!.isNotEmpty) + ? NetworkImage( + "http://ta.myhost.id/E31230549/mposyandu_api/uploads/$fotoUser") + : null, + child: !hasPhoto + ? const Icon(Icons.person, + size: 60, color: Colors.blue) + : null, + ), + ), + Positioned( + bottom: 0, + right: hasPhoto ? 40 : 0, + child: GestureDetector( + onTap: + _pickImage, // Sekarang diproteksi di dalam fungsi + child: CircleAvatar( + radius: 18, + backgroundColor: isEditMode + ? Colors.black + : Colors.grey.shade700, + child: const Icon(Icons.camera_alt, + color: Colors.white, size: 18), + ), + ), + ), + if (hasPhoto) + Positioned( + bottom: 0, + right: 0, + child: GestureDetector( + onTap: + _removeImage, // Sekarang diproteksi di dalam fungsi + child: const CircleAvatar( + radius: 18, + backgroundColor: Colors.red, + child: Icon(Icons.delete, + color: Colors.white, size: 18), + ), + ), + ), + ], + ), + const SizedBox(height: 12), + Text( + namaC.text, + style: GoogleFonts.poppins( + fontSize: 18, + fontWeight: FontWeight.bold, + color: Colors.white), + ), + ], + ), + ), + Padding( + padding: const EdgeInsets.all(20), + child: Column( + children: [ + Card( + color: Colors.white, + elevation: 2, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(15)), + child: Padding( + padding: const EdgeInsets.all(20), + child: Column( + children: [ + _buildField("Nama Lengkap", namaC), + _buildField("Email", emailC), + _buildPasswordField( + "Password (6 Digit Huruf & Angka)", passwordC), + _buildField("Role User", roleC, isReadOnly: true), + _buildField("No.HP", noHpC, isNumber: true), + _buildField("Status", statusC, isReadOnly: true), + ], + ), + ), + ), + const SizedBox(height: 30), + Row( + children: [ + Expanded( + child: _buildActionButton( + label: "Edit Profil", + color: isEditMode ? Colors.grey : Colors.orange, + onTap: isEditMode ? () {} : _enableEdit, + ), + ), + const SizedBox(width: 15), + Expanded( + child: _buildActionButton( + label: "Simpan", + color: Colors.blue, + onTap: _saveProfile, + ), + ), + ], + ), + ], + ), + ), + ], + ), + ), + ); + } + + Widget _buildField(String label, TextEditingController controller, + {bool isReadOnly = false, bool isNumber = false}) { + return Padding( + padding: const EdgeInsets.only(bottom: 15), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(label, + style: GoogleFonts.poppins( + fontSize: 12, + fontWeight: FontWeight.w600, + color: Colors.grey[600])), + const SizedBox(height: 5), + TextField( + controller: controller, + readOnly: isReadOnly || !isEditMode, + keyboardType: isNumber ? TextInputType.phone : TextInputType.text, + style: GoogleFonts.poppins(fontSize: 14), + decoration: InputDecoration( + filled: true, + fillColor: + (isReadOnly || !isEditMode) ? Colors.grey[50] : Colors.white, + contentPadding: + const EdgeInsets.symmetric(horizontal: 12, vertical: 12), + border: + OutlineInputBorder(borderRadius: BorderRadius.circular(8)), + ), + ), + ], + ), + ); + } + + Widget _buildPasswordField(String label, TextEditingController controller) { + return Padding( + padding: const EdgeInsets.only(bottom: 15), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(label, + style: GoogleFonts.poppins( + fontSize: 12, + fontWeight: FontWeight.w600, + color: Colors.grey[600])), + const SizedBox(height: 5), + TextField( + controller: controller, + obscureText: _obscurePassword, + readOnly: !isEditMode, + maxLength: 6, + style: GoogleFonts.poppins(fontSize: 14), + decoration: InputDecoration( + counterText: "", + filled: true, + fillColor: !isEditMode ? Colors.grey[50] : Colors.white, + suffixIcon: IconButton( + icon: Icon( + _obscurePassword ? Icons.visibility_off : Icons.visibility), + onPressed: () => + setState(() => _obscurePassword = !_obscurePassword), + ), + border: + OutlineInputBorder(borderRadius: BorderRadius.circular(8)), + ), + ), + ], + ), + ); + } + + Widget _buildActionButton( + {required String label, + required Color color, + required VoidCallback onTap}) { + return OutlinedButton( + onPressed: onTap, + style: OutlinedButton.styleFrom( + foregroundColor: color, + side: BorderSide(color: color, width: 1.5), + padding: const EdgeInsets.symmetric(vertical: 15), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)), + backgroundColor: Colors.white, + ), + child: Text(label, + style: + GoogleFonts.poppins(fontWeight: FontWeight.bold, fontSize: 14)), + ); + } +} diff --git a/lib/pages/register_page.dart b/lib/pages/register_page.dart new file mode 100644 index 0000000..26253e6 --- /dev/null +++ b/lib/pages/register_page.dart @@ -0,0 +1,302 @@ +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:http/http.dart' as http; + +import 'login_page.dart'; + +class RegisterPage extends StatefulWidget { + const RegisterPage({super.key}); + + @override + State createState() => _RegisterPageState(); +} + +class _RegisterPageState extends State { + // ================= CONTROLLER ================= + final TextEditingController namaController = TextEditingController(); + final TextEditingController emailController = TextEditingController(); + final TextEditingController noHpController = TextEditingController(); + final TextEditingController passwordController = TextEditingController(); + final TextEditingController nikController = TextEditingController(); + + // ================= DROPDOWN DATA ================= + List desaList = []; + List dusunList = []; + + String? selectedDesaId; + String? selectedDusunId; + + final String baseUrl = "http://ta.myhost.id/E31230549/mposyandu_api"; + + // ================= INIT ================= + @override + void initState() { + super.initState(); + fetchDesa(); + } + + // ================= FETCH DESA ================= + Future fetchDesa() async { + try { + var url = Uri.parse("$baseUrl/desa/get_desa.php"); + var response = await http.get(url); + + debugPrint("DESA RAW: ${response.body}"); + + var jsonData = json.decode(response.body); + + if (mounted) { + setState(() { + desaList = jsonData["data"] ?? []; + }); + } + } catch (e) { + debugPrint("ERROR DESA: $e"); + } + } + + // ================= FETCH DUSUN (FIXED) ================= + Future fetchDusun(String desaId) async { + try { + debugPrint("FETCH DUSUN desa_id: $desaId"); + + var url = Uri.parse("$baseUrl/dusun/get_dusun.php?desa_id=$desaId"); + var response = await http.get(url); + + debugPrint("DUSUN RAW: ${response.body}"); + + var jsonData = json.decode(response.body); + + // ✅ samakan pola dengan desa + safe parsing + List tempList = []; + + if (jsonData is Map && jsonData["data"] != null) { + tempList = jsonData["data"]; + } else if (jsonData is List) { + // kalau API langsung return array + tempList = jsonData; + } + + if (mounted) { + setState(() { + dusunList = tempList; + selectedDusunId = null; + }); + } + + debugPrint("DUSUN COUNT: ${dusunList.length}"); + } catch (e) { + debugPrint("ERROR DUSUN: $e"); + } + } + + // ================= REGISTER ================= + Future registerUser() async { + if (namaController.text.isEmpty || + emailController.text.isEmpty || + passwordController.text.isEmpty || + noHpController.text.isEmpty || + selectedDesaId == null || + selectedDusunId == null) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text("Data wajib belum lengkap")), + ); + return; + } + + try { + var url = Uri.parse("$baseUrl/register.php"); + + var response = await http.post(url, body: { + "nama": namaController.text, + "email": emailController.text, + "password": passwordController.text, + "no_hp": noHpController.text, + "nik": nikController.text, + "desa_id": selectedDesaId, + "dusun_id": selectedDusunId, + "role": "ibu", + }); + + debugPrint("REGISTER RESPONSE: ${response.body}"); + + var data = json.decode(response.body); + + if (data["success"] == true) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text("Registrasi berhasil, silakan login")), + ); + + Navigator.pushReplacement( + context, + MaterialPageRoute(builder: (_) => const LoginPage()), + ); + } else { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(data["message"] ?? "Gagal daftar")), + ); + } + } catch (e) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text("Error: $e")), + ); + } + } + + // ================= UI ================= + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: Colors.white, + appBar: AppBar( + backgroundColor: const Color.fromARGB(255, 19, 133, 226), + elevation: 0, + iconTheme: const IconThemeData(color: Colors.white), + title: Text( + "", + style: GoogleFonts.poppins( + color: Colors.white, + fontWeight: FontWeight.w600, + ), + ), + ), + body: SafeArea( + child: SingleChildScrollView( + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + children: [ + Text( + "M-Posyandu", + style: GoogleFonts.poppins( + fontSize: 26, + fontWeight: FontWeight.w700, + ), + ), + const SizedBox(height: 20), + inputField("Nama Lengkap", namaController), + inputField("Email", emailController), + inputField("NIK", nikController), + inputField("No HP", noHpController), + inputField("Password", passwordController, isPassword: true), + dropdownDesa(), + dropdownDusun(), + const SizedBox(height: 25), + SizedBox( + width: double.infinity, + height: 50, + child: ElevatedButton( + onPressed: registerUser, + style: ElevatedButton.styleFrom( + backgroundColor: + const Color.fromARGB(255, 19, 133, 226), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(15), + ), + ), + child: Text( + "DAFTAR", + style: GoogleFonts.poppins( + color: Colors.white, + fontSize: 16, + fontWeight: FontWeight.w600, + ), + ), + ), + ), + ], + ), + ), + ), + ), + ); + } + + // ================= DROPDOWN DESA ================= + Widget dropdownDesa() { + return Padding( + padding: const EdgeInsets.only(bottom: 15), + child: DropdownButtonFormField( + value: selectedDesaId, + isExpanded: true, + decoration: InputDecoration( + labelText: "Desa", + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(15), + ), + ), + hint: const Text("Pilih Desa"), + items: desaList.map>((item) { + return DropdownMenuItem( + value: item['id'].toString(), + child: Text(item['nama_desa'] ?? '-'), + ); + }).toList(), + onChanged: (value) { + setState(() { + selectedDesaId = value; + selectedDusunId = null; + dusunList = []; + }); + + if (value != null) { + fetchDusun(value); + } + }, + ), + ); + } + + // ================= DROPDOWN DUSUN (FIXED) ================= + Widget dropdownDusun() { + return Padding( + padding: const EdgeInsets.only(bottom: 15), + child: DropdownButtonFormField( + value: selectedDusunId, + isExpanded: true, + decoration: InputDecoration( + labelText: "Dusun", + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(15), + ), + ), + hint: const Text("Pilih Dusun"), + + // penting: disable kalau belum ada data + onChanged: dusunList.isEmpty + ? null + : (value) { + setState(() { + selectedDusunId = value; + }); + }, + + items: dusunList.map>((item) { + return DropdownMenuItem( + value: item['id'].toString(), + child: Text(item['nama_dusun'] ?? '-'), + ); + }).toList(), + ), + ); + } +} + +// ================= INPUT FIELD ================= +Widget inputField(String label, TextEditingController controller, + {bool isPassword = false}) { + return Padding( + padding: const EdgeInsets.only(bottom: 15), + child: TextField( + controller: controller, + obscureText: isPassword, + decoration: InputDecoration( + labelText: label, + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(15), + ), + ), + ), + ); +} \ No newline at end of file diff --git a/lib/pages/tambah_desa.dart b/lib/pages/tambah_desa.dart new file mode 100644 index 0000000..c2c22d6 --- /dev/null +++ b/lib/pages/tambah_desa.dart @@ -0,0 +1,184 @@ +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:http/http.dart' as http; + +class TambahDesaPage extends StatefulWidget { + const TambahDesaPage({super.key}); + + @override + State createState() => _TambahDesaPageState(); +} + +class _TambahDesaPageState extends State { + final _nama = TextEditingController(); + bool _loading = false; + + final String url = "http://ta.myhost.id/E31230549/mposyandu_api/desa/tambah_desa.php"; + + bool _isValid() { + if (_nama.text.isEmpty) { + _snack("Nama desa wajib diisi"); + return false; + } + return true; + } + + Future _simpan() async { + if (!_isValid()) return; + + setState(() => _loading = true); + + try { + final res = await http.post( + Uri.parse(url), + headers: { + "Content-Type": "application/x-www-form-urlencoded", + }, + body: { + "nama": _nama.text, + }, + ).timeout(const Duration(seconds: 15)); + + if (!mounted) return; + + if (res.statusCode == 200 && res.body.isNotEmpty) { + final data = json.decode(res.body); + + if (data["success"] == true) { + _snack("Berhasil tambah desa"); + Navigator.pop(context, true); + } else { + _snack(data["message"] ?? "Gagal"); + } + } else { + _snack("Server error"); + } + } catch (e) { + debugPrint("POST ERROR: $e"); + if (mounted) _snack("Error koneksi"); + } finally { + if (mounted) setState(() => _loading = false); + } + } + + void _snack(String msg) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text( + msg, + style: GoogleFonts.poppins(fontSize: 12), + ), + ), + ); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: const Color(0xfff5f6fa), + appBar: AppBar( + leading: const BackButton(color: Colors.white), + title: Text( + "", + style: GoogleFonts.poppins( + color: Colors.white, fontSize: 16, fontWeight: FontWeight.w600), + ), + backgroundColor: Colors.blue, + ), + body: Center( + child: SingleChildScrollView( + child: Container( + width: 500, + margin: const EdgeInsets.all(16), + padding: const EdgeInsets.all(24), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + boxShadow: const [ + BoxShadow(color: Colors.black12, blurRadius: 12) + ], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _label("Nama Desa"), + _input(_nama), + const SizedBox(height: 24), + SizedBox( + width: double.infinity, + child: OutlinedButton( + onPressed: _loading ? null : _simpan, + style: OutlinedButton.styleFrom( + backgroundColor: Colors.white, // Background Putih + side: const BorderSide( + color: Colors.blue, width: 1.5), // Garis Tepi Biru + padding: const EdgeInsets.symmetric(vertical: 14), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10), + ), + ), + child: _loading + ? const SizedBox( + height: 20, + width: 20, + child: CircularProgressIndicator( + color: Colors.blue, strokeWidth: 2), + ) + : Text( + "Simpan", + style: GoogleFonts.poppins( + color: Colors + .blue, // Teks Biru agar senada dengan border + fontWeight: FontWeight.bold, + fontSize: 12, + ), + ), + ), + ), + ], + ), + ), + ), + ), + ); + } + + Widget _label(String text) { + return Padding( + padding: const EdgeInsets.only(bottom: 6), + child: Text( + text, + style: GoogleFonts.poppins( + fontWeight: FontWeight.w600, + fontSize: 12, + color: Colors.black87, + ), + ), + ); + } + + Widget _input(TextEditingController c) { + return TextField( + controller: c, + style: GoogleFonts.poppins(fontSize: 12), + decoration: InputDecoration( + hintText: "Masukkan nama desa...", + hintStyle: GoogleFonts.poppins(fontSize: 12, color: Colors.grey), + contentPadding: + const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + ), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: const BorderSide(color: Colors.grey), + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: const BorderSide(color: Colors.blue, width: 1.5), + ), + ), + ); + } +} diff --git a/lib/pages/tambah_dusun.dart b/lib/pages/tambah_dusun.dart new file mode 100644 index 0000000..5a1d160 --- /dev/null +++ b/lib/pages/tambah_dusun.dart @@ -0,0 +1,210 @@ +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:http/http.dart' as http; + +class TambahDusunPage extends StatefulWidget { + const TambahDusunPage({super.key}); + + @override + State createState() => _TambahDusunPageState(); +} + +class _TambahDusunPageState extends State { + final _namaDusun = TextEditingController(); + bool _loading = false; + + List desaList = []; + String? selectedDesaId; + + final String url = "http://ta.myhost.id/E31230549/mposyandu_api/dusun/tambah_dusun.php"; + final String urlDesa = "http://ta.myhost.id/E31230549/mposyandu_api/desa/get_desa.php"; + + @override + void initState() { + super.initState(); + _fetchDesa(); + } + + Future _fetchDesa() async { + try { + final res = await http.get(Uri.parse(urlDesa)); + if (!mounted) return; + final data = json.decode(res.body); + if (data["success"] == true) { + setState(() => desaList = data["data"]); + } + } catch (e) { + debugPrint("DESA ERROR: $e"); + } + } + + bool _isValid() { + if (selectedDesaId == null) { + _snack("Desa wajib dipilih"); + return false; + } + if (_namaDusun.text.isEmpty) { + _snack("Nama dusun wajib diisi"); + return false; + } + return true; + } + + Future _simpan() async { + if (!_isValid()) return; + + setState(() => _loading = true); + + try { + final res = await http.post( + Uri.parse(url), + headers: {"Content-Type": "application/x-www-form-urlencoded"}, + body: { + "desa_id": selectedDesaId!, + "nama_dusun": _namaDusun.text, + }, + ); + + if (!mounted) return; // Penting untuk menghilangkan garis kuning + + final data = json.decode(res.body); + + if (data["success"] == true) { + _snack("Berhasil tambah dusun"); + Navigator.pop(context, true); + } else { + _snack(data["message"] ?? "Gagal"); + } + } catch (e) { + if (mounted) _snack("Error koneksi"); + } finally { + if (mounted) setState(() => _loading = false); + } + } + + // PERBAIKAN: Menambahkan pengecekan mounted agar tidak bergaris kuning + void _snack(String msg) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text( + msg, + style: GoogleFonts.poppins(fontSize: 12), + ), + ), + ); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: const Color(0xfff5f6fa), + appBar: AppBar( + leading: const BackButton(color: Colors.white), + title: Text( + "", + style: GoogleFonts.poppins(color: Colors.white, fontSize: 14), + ), + backgroundColor: Colors.blue, + ), + body: Center( + child: SingleChildScrollView( + child: Container( + width: 500, + margin: const EdgeInsets.all(16), + padding: const EdgeInsets.all(24), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + boxShadow: const [ + BoxShadow(color: Colors.black12, blurRadius: 12) + ], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _label("Pilih Desa"), + _dropdownDesa(), + const SizedBox(height: 16), + _label("Nama Dusun"), + _input(_namaDusun), + const SizedBox(height: 24), + SizedBox( + width: double.infinity, + child: OutlinedButton( + onPressed: _loading ? null : _simpan, + style: OutlinedButton.styleFrom( + backgroundColor: Colors.white, + side: const BorderSide(color: Colors.blue, width: 1.5), + padding: const EdgeInsets.symmetric(vertical: 14), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10)), + ), + child: _loading + ? const SizedBox( + width: 20, + height: 20, + child: CircularProgressIndicator( + strokeWidth: 2, color: Colors.blue), + ) + : Text( + "Simpan", + style: GoogleFonts.poppins( + color: Colors.blue, + fontWeight: FontWeight.bold, + fontSize: 12, + ), + ), + ), + ), + ], + ), + ), + ), + ), + ); + } + + Widget _label(String text) => Padding( + padding: const EdgeInsets.only(bottom: 6), + child: Text( + text, + style: GoogleFonts.poppins(fontWeight: FontWeight.w600, fontSize: 12), + ), + ); + + Widget _input(TextEditingController c) => TextField( + controller: c, + style: GoogleFonts.poppins(fontSize: 12), + decoration: InputDecoration( + hintText: "Masukkan nama dusun...", + hintStyle: GoogleFonts.poppins(fontSize: 12, color: Colors.grey), + contentPadding: + const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + border: OutlineInputBorder(borderRadius: BorderRadius.circular(10)), + ), + ); + + Widget _dropdownDesa() => DropdownButtonFormField( + value: selectedDesaId, + style: GoogleFonts.poppins(fontSize: 12, color: Colors.black), + items: desaList.map>((e) { + return DropdownMenuItem( + value: e["id"].toString(), + child: Text( + e["nama_desa"] ?? "", + style: GoogleFonts.poppins(fontSize: 12), + ), + ); + }).toList(), + onChanged: (v) => setState(() => selectedDesaId = v), + decoration: InputDecoration( + hintText: "Pilih desa", + hintStyle: GoogleFonts.poppins(fontSize: 12), + contentPadding: + const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + border: OutlineInputBorder(borderRadius: BorderRadius.circular(10)), + ), + ); +} diff --git a/lib/pages/tambah_petugas.dart b/lib/pages/tambah_petugas.dart new file mode 100644 index 0000000..0d06bd1 --- /dev/null +++ b/lib/pages/tambah_petugas.dart @@ -0,0 +1,416 @@ +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:http/http.dart' as http; + +class TambahPetugasPage extends StatefulWidget { + const TambahPetugasPage({super.key}); + + @override + State createState() => _TambahPetugasPageState(); +} + +class _TambahPetugasPageState extends State { + final _nama = TextEditingController(); + final _email = TextEditingController(); + final _password = TextEditingController(); + final _noHp = TextEditingController(); + + String? _role; + String? _desaId; + String? _dusunId; + + String? _errNama, + _errEmail, + _errPass, + _errNoHp, + _errRole, + _errDesa, + _errDusun; + + bool _loading = false; + bool _obscurePassword = true; + + List> desaList = []; + List> dusunList = []; + + final String url = + "http://ta.myhost.id/E31230549/mposyandu_api/petugas/tambah_petugas.php"; + final String desaUrl = "http://ta.myhost.id/E31230549/mposyandu_api/desa/get_desa.php"; + final String dsnUrl = "http://ta.myhost.id/E31230549/mposyandu_api/dusun/get_dusun.php"; + + @override + void initState() { + super.initState(); + _fetchDesa(); + } + + Future _fetchDesa() async { + try { + final res = await http.get(Uri.parse(desaUrl)); + if (res.statusCode == 200) { + final jsonData = json.decode(res.body); + if (jsonData["success"] == true) { + setState(() { + desaList = List>.from(jsonData["data"]); + }); + } + } + } catch (e) { + debugPrint("DESA ERROR: $e"); + } + } + + Future _fetchDusun(String desaId) async { + try { + final res = await http.get(Uri.parse("$dsnUrl?desa_id=$desaId")); + if (res.statusCode == 200) { + final jsonData = json.decode(res.body); + if (jsonData["success"] == true) { + setState(() { + dusunList = List>.from(jsonData["data"]); + }); + } + } + } catch (e) { + debugPrint("DUSUN ERROR: $e"); + } + } + + bool _isValid() { + setState(() { + // 1. Validasi Nama + _errNama = _nama.text.trim().isEmpty ? "Nama tidak boleh kosong" : null; + + // 2. Validasi Email + final emailRegex = RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$'); + if (_email.text.trim().isEmpty) { + _errEmail = "Email tidak boleh kosong"; + } else if (!emailRegex.hasMatch(_email.text.trim())) { + _errEmail = "Format email salah (misal: user@email.com)"; + } else { + _errEmail = null; + } + + // 3. Validasi Password (Wajib tepat 6 karakter, kombinasi huruf & angka) + final passRegex = RegExp(r'^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6}$'); + if (_password.text.isEmpty) { + _errPass = "Password tidak boleh kosong"; + } else if (!passRegex.hasMatch(_password.text)) { + _errPass = "Harus 6 karakter kombinasi Huruf & Angka"; + } else { + _errPass = null; + } + + // 4. Validasi No HP + _errNoHp = (_noHp.text.length < 10 || _noHp.text.length > 13) + ? "No HP harus 10-13 digit" + : null; + + // 5. Validasi Role + _errRole = _role == null ? "Pilih role petugas" : null; + + // 6. Validasi Wilayah Tugas + if (_role == "kader") { + _errDesa = _desaId == null ? "Pilih desa" : null; + _errDusun = _dusunId == null ? "Pilih dusun" : null; + } else { + _errDesa = null; + _errDusun = null; + } + }); + + return _errNama == null && + _errEmail == null && + _errPass == null && + _errNoHp == null && + _errRole == null && + _errDesa == null && + _errDusun == null; + } + + Future _simpan() async { + if (!_isValid()) return; + setState(() => _loading = true); + try { + final res = await http.post( + Uri.parse(url), + body: { + "nama": _nama.text.trim(), + "email": _email.text.trim(), + "password": _password.text, + "no_hp": _noHp.text.trim(), + "role": _role!, + "desa_id": _role == "kader" ? _desaId! : "", + "dusun_id": _role == "kader" ? _dusunId! : "", + }, + ); + final data = json.decode(res.body); + if (data["success"] == true) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar(SnackBar( + content: + Text("Berhasil!", style: GoogleFonts.poppins(fontSize: 12)))); + Navigator.pop(context, true); + } + } else { + _showSimpleError(data["message"] ?? "Gagal menyimpan"); + } + } catch (e) { + _showSimpleError("Terjadi kesalahan koneksi"); + } finally { + if (mounted) setState(() => _loading = false); + } + } + + void _showSimpleError(String msg) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(msg, style: GoogleFonts.poppins(fontSize: 12)))); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: const Color(0xfff5f6fa), + appBar: AppBar( + leading: const BackButton(color: Colors.white), + title: Text("", + style: GoogleFonts.poppins(color: Colors.white, fontSize: 16)), + backgroundColor: Colors.blue, + ), + body: Center( + child: SingleChildScrollView( + child: Column( + children: [ + Text( + "Tambah Data Petugas", + style: GoogleFonts.poppins( + fontSize: 18, + fontWeight: FontWeight.bold, + color: Colors.black, + ), + ), + const SizedBox(height: 16), + Container( + width: 500, + margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + padding: const EdgeInsets.all(24), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + boxShadow: const [ + BoxShadow(color: Colors.black12, blurRadius: 12) + ], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _label("Nama Lengkap"), + _input(_nama, error: _errNama), + const SizedBox(height: 16), + _label("Email"), + _input(_email, + hint: "contoh@email.com", + type: TextInputType.emailAddress, + error: _errEmail), + const SizedBox(height: 16), + _label("Password"), + _input(_password, + isPassword: true, + hint: "Wajib 6 digit (Huruf & Angka)", + limit: 6, + error: _errPass, + showToggle: true), + const SizedBox(height: 16), + _label("Role"), + _dropdown( + value: _role, + hint: "Pilih Role", + items: const ["kader", "bidan"], + error: _errRole, + onChanged: (v) { + setState(() { + _role = v; + _desaId = null; + _dusunId = null; + dusunList.clear(); + }); + }, + ), + const SizedBox(height: 16), + _label("Desa"), + _dropdownMap( + value: _desaId, + hint: "Pilih Desa", + error: _errDesa, + items: desaList, + itemKey: "nama_desa", + enabled: _role == "kader", + onChanged: (v) { + setState(() { + _desaId = v; + _dusunId = null; + }); + if (v != null) _fetchDusun(v); + }, + ), + const SizedBox(height: 16), + _label("Dusun"), + _dropdownMap( + value: _dusunId, + hint: "Pilih Dusun", + error: _errDusun, + items: dusunList, + itemKey: "nama_dusun", + enabled: _role == "kader", + onChanged: (v) => setState(() => _dusunId = v), + ), + const SizedBox(height: 16), + _label("Nomor HP"), + _input(_noHp, + hint: "08xxxx", + type: TextInputType.number, + limit: 13, + isNumberOnly: true, + error: _errNoHp), + const SizedBox(height: 32), + SizedBox( + width: double.infinity, + child: OutlinedButton( + onPressed: _loading ? null : _simpan, + style: OutlinedButton.styleFrom( + backgroundColor: Colors.white, + side: const BorderSide(color: Colors.blue, width: 2), + padding: const EdgeInsets.symmetric(vertical: 16), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10)), + ), + child: _loading + ? const SizedBox( + height: 20, + width: 20, + child: CircularProgressIndicator( + color: Colors.blue, strokeWidth: 2)) + : Text("Simpan", + style: GoogleFonts.poppins( + color: Colors.blue, + fontWeight: FontWeight.bold, + fontSize: 12)), + ), + ), + ], + ), + ), + const SizedBox(height: 20), + ], + ), + ), + ), + ); + } + + InputDecoration _decoration({String? hint, String? error, Widget? suffix}) { + return InputDecoration( + hintText: hint, + errorText: error, + suffixIcon: suffix, + hintStyle: GoogleFonts.poppins(fontSize: 12), + errorStyle: GoogleFonts.poppins(color: Colors.red, fontSize: 10), + contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12), + border: OutlineInputBorder(borderRadius: BorderRadius.circular(10)), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: const BorderSide(color: Colors.grey)), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: const BorderSide(color: Colors.blue, width: 2)), + ); + } + + Widget _label(String text) { + return Padding( + padding: const EdgeInsets.only(bottom: 6), + child: Text(text, + style: + GoogleFonts.poppins(fontWeight: FontWeight.w600, fontSize: 12)), + ); + } + + Widget _input(TextEditingController c, + {bool isPassword = false, + String? hint, + int? limit, + TextInputType type = TextInputType.text, + bool isNumberOnly = false, + String? error, + bool showToggle = false}) { + return TextField( + controller: c, + obscureText: isPassword ? _obscurePassword : false, + maxLength: limit, + style: GoogleFonts.poppins(fontSize: 12), + keyboardType: type, + inputFormatters: + isNumberOnly ? [FilteringTextInputFormatter.digitsOnly] : null, + decoration: _decoration( + hint: hint ?? "Masukkan...", + error: error, + suffix: showToggle + ? IconButton( + icon: Icon( + _obscurePassword ? Icons.visibility_off : Icons.visibility, + size: 20), + onPressed: () => + setState(() => _obscurePassword = !_obscurePassword), + ) + : null, + ).copyWith(counterText: ""), + ); + } + + Widget _dropdown( + {required String? value, + required List items, + required Function(String?) onChanged, + String? hint, + String? error}) { + return DropdownButtonFormField( + value: value, + style: GoogleFonts.poppins(color: Colors.black, fontSize: 12), + hint: Text(hint ?? "", style: GoogleFonts.poppins(fontSize: 12)), + decoration: _decoration(error: error), + items: items + .map((e) => DropdownMenuItem( + value: e, + child: Text(e, style: GoogleFonts.poppins(fontSize: 12)))) + .toList(), + onChanged: onChanged, + ); + } + + Widget _dropdownMap( + {required String? value, + required List> items, + required String itemKey, + required Function(String?) onChanged, + bool enabled = true, + String? hint, + String? error}) { + return DropdownButtonFormField( + value: value, + style: GoogleFonts.poppins(color: Colors.black, fontSize: 12), + hint: Text(hint ?? "", style: GoogleFonts.poppins(fontSize: 12)), + decoration: _decoration(error: error), + items: enabled + ? items + .map((e) => DropdownMenuItem( + value: e["id"].toString(), + child: Text(e[itemKey], + style: GoogleFonts.poppins(fontSize: 12)))) + .toList() + : [], + onChanged: enabled ? onChanged : null, + ); + } +} \ No newline at end of file diff --git a/lib/widgets/custom_textfield.dart b/lib/widgets/custom_textfield.dart new file mode 100644 index 0000000..e69de29 diff --git a/linux/.gitignore b/linux/.gitignore new file mode 100644 index 0000000..d3896c9 --- /dev/null +++ b/linux/.gitignore @@ -0,0 +1 @@ +flutter/ephemeral diff --git a/linux/CMakeLists.txt b/linux/CMakeLists.txt new file mode 100644 index 0000000..cb11cb4 --- /dev/null +++ b/linux/CMakeLists.txt @@ -0,0 +1,128 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "posyandu_care") +# The unique GTK application identifier for this application. See: +# https://wiki.gnome.org/HowDoI/ChooseApplicationID +set(APPLICATION_ID "com.example.posyandu_care") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(SET CMP0063 NEW) + +# Load bundled libraries from the lib/ directory relative to the binary. +set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") + +# Root filesystem for cross-building. +if(FLUTTER_TARGET_PLATFORM_SYSROOT) + set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) + set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +endif() + +# Define build configuration options. +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") +endif() + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_14) + target_compile_options(${TARGET} PRIVATE -Wall -Werror) + target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") + target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) + +# Only the install-generated bundle's copy of the executable will launch +# correctly, since the resources must in the right relative locations. To avoid +# people trying to run the unbundled copy, put it in a subdirectory instead of +# the default top-level location. +set_target_properties(${BINARY_NAME} + PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" +) + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# By default, "installing" just makes a relocatable bundle in the build +# directory. +set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +# Start with a clean build bundle directory every time. +install(CODE " + file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") + " COMPONENT Runtime) + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) + install(FILES "${bundled_library}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endforeach(bundled_library) + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") + install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() diff --git a/linux/flutter/CMakeLists.txt b/linux/flutter/CMakeLists.txt new file mode 100644 index 0000000..d5bd016 --- /dev/null +++ b/linux/flutter/CMakeLists.txt @@ -0,0 +1,88 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.10) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. + +# Serves the same purpose as list(TRANSFORM ... PREPEND ...), +# which isn't available in 3.10. +function(list_prepend LIST_NAME PREFIX) + set(NEW_LIST "") + foreach(element ${${LIST_NAME}}) + list(APPEND NEW_LIST "${PREFIX}${element}") + endforeach(element) + set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) +endfunction() + +# === Flutter Library === +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) +pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) +pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) + +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "fl_basic_message_channel.h" + "fl_binary_codec.h" + "fl_binary_messenger.h" + "fl_dart_project.h" + "fl_engine.h" + "fl_json_message_codec.h" + "fl_json_method_codec.h" + "fl_message_codec.h" + "fl_method_call.h" + "fl_method_channel.h" + "fl_method_codec.h" + "fl_method_response.h" + "fl_plugin_registrar.h" + "fl_plugin_registry.h" + "fl_standard_message_codec.h" + "fl_standard_method_codec.h" + "fl_string_codec.h" + "fl_value.h" + "fl_view.h" + "flutter_linux.h" +) +list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") +target_link_libraries(flutter INTERFACE + PkgConfig::GTK + PkgConfig::GLIB + PkgConfig::GIO +) +add_dependencies(flutter flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CMAKE_CURRENT_BINARY_DIR}/_phony_ + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" + ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} +) diff --git a/linux/flutter/generated_plugin_registrant.cc b/linux/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..f693f59 --- /dev/null +++ b/linux/flutter/generated_plugin_registrant.cc @@ -0,0 +1,27 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include +#include +#include +#include + +void fl_register_plugins(FlPluginRegistry* registry) { + g_autoptr(FlPluginRegistrar) audioplayers_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "AudioplayersLinuxPlugin"); + audioplayers_linux_plugin_register_with_registrar(audioplayers_linux_registrar); + g_autoptr(FlPluginRegistrar) file_selector_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "FileSelectorPlugin"); + file_selector_plugin_register_with_registrar(file_selector_linux_registrar); + g_autoptr(FlPluginRegistrar) printing_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "PrintingPlugin"); + printing_plugin_register_with_registrar(printing_registrar); + g_autoptr(FlPluginRegistrar) url_launcher_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "UrlLauncherPlugin"); + url_launcher_plugin_register_with_registrar(url_launcher_linux_registrar); +} diff --git a/linux/flutter/generated_plugin_registrant.h b/linux/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..e0f0a47 --- /dev/null +++ b/linux/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void fl_register_plugins(FlPluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/linux/flutter/generated_plugins.cmake b/linux/flutter/generated_plugins.cmake new file mode 100644 index 0000000..38cb98b --- /dev/null +++ b/linux/flutter/generated_plugins.cmake @@ -0,0 +1,27 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + audioplayers_linux + file_selector_linux + printing + url_launcher_linux +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/linux/runner/CMakeLists.txt b/linux/runner/CMakeLists.txt new file mode 100644 index 0000000..e97dabc --- /dev/null +++ b/linux/runner/CMakeLists.txt @@ -0,0 +1,26 @@ +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} + "main.cc" + "my_application.cc" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the application ID. +add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") + +# Add dependency libraries. Add any application-specific dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter) +target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) + +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") diff --git a/linux/runner/main.cc b/linux/runner/main.cc new file mode 100644 index 0000000..e7c5c54 --- /dev/null +++ b/linux/runner/main.cc @@ -0,0 +1,6 @@ +#include "my_application.h" + +int main(int argc, char** argv) { + g_autoptr(MyApplication) app = my_application_new(); + return g_application_run(G_APPLICATION(app), argc, argv); +} diff --git a/linux/runner/my_application.cc b/linux/runner/my_application.cc new file mode 100644 index 0000000..d57b215 --- /dev/null +++ b/linux/runner/my_application.cc @@ -0,0 +1,130 @@ +#include "my_application.h" + +#include +#ifdef GDK_WINDOWING_X11 +#include +#endif + +#include "flutter/generated_plugin_registrant.h" + +struct _MyApplication { + GtkApplication parent_instance; + char** dart_entrypoint_arguments; +}; + +G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) + +// Implements GApplication::activate. +static void my_application_activate(GApplication* application) { + MyApplication* self = MY_APPLICATION(application); + GtkWindow* window = + GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); + + // Use a header bar when running in GNOME as this is the common style used + // by applications and is the setup most users will be using (e.g. Ubuntu + // desktop). + // If running on X and not using GNOME then just use a traditional title bar + // in case the window manager does more exotic layout, e.g. tiling. + // If running on Wayland assume the header bar will work (may need changing + // if future cases occur). + gboolean use_header_bar = TRUE; +#ifdef GDK_WINDOWING_X11 + GdkScreen* screen = gtk_window_get_screen(window); + if (GDK_IS_X11_SCREEN(screen)) { + const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); + if (g_strcmp0(wm_name, "GNOME Shell") != 0) { + use_header_bar = FALSE; + } + } +#endif + if (use_header_bar) { + GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); + gtk_widget_show(GTK_WIDGET(header_bar)); + gtk_header_bar_set_title(header_bar, "posyandu_care"); + gtk_header_bar_set_show_close_button(header_bar, TRUE); + gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); + } else { + gtk_window_set_title(window, "posyandu_care"); + } + + gtk_window_set_default_size(window, 1280, 720); + gtk_widget_show(GTK_WIDGET(window)); + + g_autoptr(FlDartProject) project = fl_dart_project_new(); + fl_dart_project_set_dart_entrypoint_arguments(project, self->dart_entrypoint_arguments); + + FlView* view = fl_view_new(project); + gtk_widget_show(GTK_WIDGET(view)); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); + + fl_register_plugins(FL_PLUGIN_REGISTRY(view)); + + gtk_widget_grab_focus(GTK_WIDGET(view)); +} + +// Implements GApplication::local_command_line. +static gboolean my_application_local_command_line(GApplication* application, gchar*** arguments, int* exit_status) { + MyApplication* self = MY_APPLICATION(application); + // Strip out the first argument as it is the binary name. + self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); + + g_autoptr(GError) error = nullptr; + if (!g_application_register(application, nullptr, &error)) { + g_warning("Failed to register: %s", error->message); + *exit_status = 1; + return TRUE; + } + + g_application_activate(application); + *exit_status = 0; + + return TRUE; +} + +// Implements GApplication::startup. +static void my_application_startup(GApplication* application) { + //MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application startup. + + G_APPLICATION_CLASS(my_application_parent_class)->startup(application); +} + +// Implements GApplication::shutdown. +static void my_application_shutdown(GApplication* application) { + //MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application shutdown. + + G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application); +} + +// Implements GObject::dispose. +static void my_application_dispose(GObject* object) { + MyApplication* self = MY_APPLICATION(object); + g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); + G_OBJECT_CLASS(my_application_parent_class)->dispose(object); +} + +static void my_application_class_init(MyApplicationClass* klass) { + G_APPLICATION_CLASS(klass)->activate = my_application_activate; + G_APPLICATION_CLASS(klass)->local_command_line = my_application_local_command_line; + G_APPLICATION_CLASS(klass)->startup = my_application_startup; + G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown; + G_OBJECT_CLASS(klass)->dispose = my_application_dispose; +} + +static void my_application_init(MyApplication* self) {} + +MyApplication* my_application_new() { + // Set the program name to the application ID, which helps various systems + // like GTK and desktop environments map this running application to its + // corresponding .desktop file. This ensures better integration by allowing + // the application to be recognized beyond its binary name. + g_set_prgname(APPLICATION_ID); + + return MY_APPLICATION(g_object_new(my_application_get_type(), + "application-id", APPLICATION_ID, + "flags", G_APPLICATION_NON_UNIQUE, + nullptr)); +} diff --git a/linux/runner/my_application.h b/linux/runner/my_application.h new file mode 100644 index 0000000..72271d5 --- /dev/null +++ b/linux/runner/my_application.h @@ -0,0 +1,18 @@ +#ifndef FLUTTER_MY_APPLICATION_H_ +#define FLUTTER_MY_APPLICATION_H_ + +#include + +G_DECLARE_FINAL_TYPE(MyApplication, my_application, MY, APPLICATION, + GtkApplication) + +/** + * my_application_new: + * + * Creates a new Flutter-based application. + * + * Returns: a new #MyApplication. + */ +MyApplication* my_application_new(); + +#endif // FLUTTER_MY_APPLICATION_H_ diff --git a/macos/.gitignore b/macos/.gitignore new file mode 100644 index 0000000..746adbb --- /dev/null +++ b/macos/.gitignore @@ -0,0 +1,7 @@ +# Flutter-related +**/Flutter/ephemeral/ +**/Pods/ + +# Xcode-related +**/dgph +**/xcuserdata/ diff --git a/macos/Flutter/Flutter-Debug.xcconfig b/macos/Flutter/Flutter-Debug.xcconfig new file mode 100644 index 0000000..c2efd0b --- /dev/null +++ b/macos/Flutter/Flutter-Debug.xcconfig @@ -0,0 +1 @@ +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/macos/Flutter/Flutter-Release.xcconfig b/macos/Flutter/Flutter-Release.xcconfig new file mode 100644 index 0000000..c2efd0b --- /dev/null +++ b/macos/Flutter/Flutter-Release.xcconfig @@ -0,0 +1 @@ +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/macos/Flutter/GeneratedPluginRegistrant.swift b/macos/Flutter/GeneratedPluginRegistrant.swift new file mode 100644 index 0000000..9ced393 --- /dev/null +++ b/macos/Flutter/GeneratedPluginRegistrant.swift @@ -0,0 +1,22 @@ +// +// Generated file. Do not edit. +// + +import FlutterMacOS +import Foundation + +import audioplayers_darwin +import file_selector_macos +import printing +import quill_native_bridge_macos +import shared_preferences_foundation +import url_launcher_macos + +func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { + AudioplayersDarwinPlugin.register(with: registry.registrar(forPlugin: "AudioplayersDarwinPlugin")) + FileSelectorPlugin.register(with: registry.registrar(forPlugin: "FileSelectorPlugin")) + PrintingPlugin.register(with: registry.registrar(forPlugin: "PrintingPlugin")) + QuillNativeBridgePlugin.register(with: registry.registrar(forPlugin: "QuillNativeBridgePlugin")) + SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin")) + UrlLauncherPlugin.register(with: registry.registrar(forPlugin: "UrlLauncherPlugin")) +} diff --git a/macos/Runner.xcodeproj/project.pbxproj b/macos/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..a729ad1 --- /dev/null +++ b/macos/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,705 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXAggregateTarget section */ + 33CC111A2044C6BA0003C045 /* Flutter Assemble */ = { + isa = PBXAggregateTarget; + buildConfigurationList = 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */; + buildPhases = ( + 33CC111E2044C6BF0003C045 /* ShellScript */, + ); + dependencies = ( + ); + name = "Flutter Assemble"; + productName = FLX; + }; +/* End PBXAggregateTarget section */ + +/* Begin PBXBuildFile section */ + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C80D7294CF71000263BE5 /* RunnerTests.swift */; }; + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; }; + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; }; + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; }; + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; }; + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC10EC2044A3C60003C045; + remoteInfo = Runner; + }; + 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC111A2044C6BA0003C045; + remoteInfo = FLX; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 33CC110E2044A8840003C045 /* Bundle Framework */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Bundle Framework"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 331C80D7294CF71000263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = ""; }; + 33CC10ED2044A3C60003C045 /* posyandu_care.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "posyandu_care.app"; sourceTree = BUILT_PRODUCTS_DIR; }; + 33CC10F02044A3C60003C045 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 33CC10F22044A3C60003C045 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = Runner/Assets.xcassets; sourceTree = ""; }; + 33CC10F52044A3C60003C045 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = ""; }; + 33CC10F72044A3C60003C045 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = Runner/Info.plist; sourceTree = ""; }; + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainFlutterWindow.swift; sourceTree = ""; }; + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Debug.xcconfig"; sourceTree = ""; }; + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Release.xcconfig"; sourceTree = ""; }; + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = "Flutter-Generated.xcconfig"; path = "ephemeral/Flutter-Generated.xcconfig"; sourceTree = ""; }; + 33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = ""; }; + 33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = ""; }; + 33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 331C80D2294CF70F00263BE5 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EA2044A3C60003C045 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C80D6294CF71000263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C80D7294CF71000263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 33BA886A226E78AF003329D5 /* Configs */ = { + isa = PBXGroup; + children = ( + 33E5194F232828860026EE4D /* AppInfo.xcconfig */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */, + ); + path = Configs; + sourceTree = ""; + }; + 33CC10E42044A3C60003C045 = { + isa = PBXGroup; + children = ( + 33FAB671232836740065AC1E /* Runner */, + 33CEB47122A05771004F2AC0 /* Flutter */, + 331C80D6294CF71000263BE5 /* RunnerTests */, + 33CC10EE2044A3C60003C045 /* Products */, + D73912EC22F37F3D000D13A0 /* Frameworks */, + ); + sourceTree = ""; + }; + 33CC10EE2044A3C60003C045 /* Products */ = { + isa = PBXGroup; + children = ( + 33CC10ED2044A3C60003C045 /* posyandu_care.app */, + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 33CC11242044D66E0003C045 /* Resources */ = { + isa = PBXGroup; + children = ( + 33CC10F22044A3C60003C045 /* Assets.xcassets */, + 33CC10F42044A3C60003C045 /* MainMenu.xib */, + 33CC10F72044A3C60003C045 /* Info.plist */, + ); + name = Resources; + path = ..; + sourceTree = ""; + }; + 33CEB47122A05771004F2AC0 /* Flutter */ = { + isa = PBXGroup; + children = ( + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */, + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */, + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */, + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */, + ); + path = Flutter; + sourceTree = ""; + }; + 33FAB671232836740065AC1E /* Runner */ = { + isa = PBXGroup; + children = ( + 33CC10F02044A3C60003C045 /* AppDelegate.swift */, + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */, + 33E51913231747F40026EE4D /* DebugProfile.entitlements */, + 33E51914231749380026EE4D /* Release.entitlements */, + 33CC11242044D66E0003C045 /* Resources */, + 33BA886A226E78AF003329D5 /* Configs */, + ); + path = Runner; + sourceTree = ""; + }; + D73912EC22F37F3D000D13A0 /* Frameworks */ = { + isa = PBXGroup; + children = ( + ); + name = Frameworks; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C80D4294CF70F00263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 331C80D1294CF70F00263BE5 /* Sources */, + 331C80D2294CF70F00263BE5 /* Frameworks */, + 331C80D3294CF70F00263BE5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 331C80DA294CF71000263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C80D5294CF71000263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 33CC10EC2044A3C60003C045 /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 33CC10E92044A3C60003C045 /* Sources */, + 33CC10EA2044A3C60003C045 /* Frameworks */, + 33CC10EB2044A3C60003C045 /* Resources */, + 33CC110E2044A8840003C045 /* Bundle Framework */, + 3399D490228B24CF009A79C7 /* ShellScript */, + ); + buildRules = ( + ); + dependencies = ( + 33CC11202044C79F0003C045 /* PBXTargetDependency */, + ); + name = Runner; + productName = Runner; + productReference = 33CC10ED2044A3C60003C045 /* posyandu_care.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 33CC10E52044A3C60003C045 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastSwiftUpdateCheck = 0920; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C80D4294CF70F00263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 33CC10EC2044A3C60003C045; + }; + 33CC10EC2044A3C60003C045 = { + CreatedOnToolsVersion = 9.2; + LastSwiftMigration = 1100; + ProvisioningStyle = Automatic; + SystemCapabilities = { + com.apple.Sandbox = { + enabled = 1; + }; + }; + }; + 33CC111A2044C6BA0003C045 = { + CreatedOnToolsVersion = 9.2; + ProvisioningStyle = Manual; + }; + }; + }; + buildConfigurationList = 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 33CC10E42044A3C60003C045; + productRefGroup = 33CC10EE2044A3C60003C045 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 33CC10EC2044A3C60003C045 /* Runner */, + 331C80D4294CF70F00263BE5 /* RunnerTests */, + 33CC111A2044C6BA0003C045 /* Flutter Assemble */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C80D3294CF70F00263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EB2044A3C60003C045 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */, + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3399D490228B24CF009A79C7 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + ); + outputFileListPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "echo \"$PRODUCT_NAME.app\" > \"$PROJECT_DIR\"/Flutter/ephemeral/.app_filename && \"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh embed\n"; + }; + 33CC111E2044C6BF0003C045 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + Flutter/ephemeral/FlutterInputs.xcfilelist, + ); + inputPaths = ( + Flutter/ephemeral/tripwire, + ); + outputFileListPaths = ( + Flutter/ephemeral/FlutterOutputs.xcfilelist, + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C80D1294CF70F00263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10E92044A3C60003C045 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */, + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */, + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C80DA294CF71000263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC10EC2044A3C60003C045 /* Runner */; + targetProxy = 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */; + }; + 33CC11202044C79F0003C045 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC111A2044C6BA0003C045 /* Flutter Assemble */; + targetProxy = 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 33CC10F42044A3C60003C045 /* MainMenu.xib */ = { + isa = PBXVariantGroup; + children = ( + 33CC10F52044A3C60003C045 /* Base */, + ); + name = MainMenu.xib; + path = Runner; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 331C80DB294CF71000263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.posyanduCare.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/posyandu_care.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/posyandu_care"; + }; + name = Debug; + }; + 331C80DC294CF71000263BE5 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.posyanduCare.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/posyandu_care.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/posyandu_care"; + }; + name = Release; + }; + 331C80DD294CF71000263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.posyanduCare.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/posyandu_care.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/posyandu_care"; + }; + name = Profile; + }; + 338D0CE9231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.14; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Profile; + }; + 338D0CEA231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Profile; + }; + 338D0CEB231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Profile; + }; + 33CC10F92044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.14; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 33CC10FA2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.14; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Release; + }; + 33CC10FC2044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + 33CC10FD2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/Release.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; + 33CC111C2044C6BA0003C045 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Debug; + }; + 33CC111D2044C6BA0003C045 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C80DB294CF71000263BE5 /* Debug */, + 331C80DC294CF71000263BE5 /* Release */, + 331C80DD294CF71000263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10F92044A3C60003C045 /* Debug */, + 33CC10FA2044A3C60003C045 /* Release */, + 338D0CE9231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10FC2044A3C60003C045 /* Debug */, + 33CC10FD2044A3C60003C045 /* Release */, + 338D0CEA231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC111C2044C6BA0003C045 /* Debug */, + 33CC111D2044C6BA0003C045 /* Release */, + 338D0CEB231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 33CC10E52044A3C60003C045 /* Project object */; +} diff --git a/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..7a86100 --- /dev/null +++ b/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,98 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/macos/Runner.xcworkspace/contents.xcworkspacedata b/macos/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..1d526a1 --- /dev/null +++ b/macos/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/macos/Runner/AppDelegate.swift b/macos/Runner/AppDelegate.swift new file mode 100644 index 0000000..b3c1761 --- /dev/null +++ b/macos/Runner/AppDelegate.swift @@ -0,0 +1,13 @@ +import Cocoa +import FlutterMacOS + +@main +class AppDelegate: FlutterAppDelegate { + override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { + return true + } + + override func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool { + return true + } +} diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..a2ec33f --- /dev/null +++ b/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,68 @@ +{ + "images" : [ + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_16.png", + "scale" : "1x" + }, + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "2x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "1x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_64.png", + "scale" : "2x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_128.png", + "scale" : "1x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "2x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "1x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "2x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "1x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_1024.png", + "scale" : "2x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png new file mode 100644 index 0000000..82b6f9d Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png new file mode 100644 index 0000000..13b35eb Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png new file mode 100644 index 0000000..0a3f5fa Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png new file mode 100644 index 0000000..bdb5722 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png new file mode 100644 index 0000000..f083318 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png new file mode 100644 index 0000000..326c0e7 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png new file mode 100644 index 0000000..2f1632c Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png differ diff --git a/macos/Runner/Base.lproj/MainMenu.xib b/macos/Runner/Base.lproj/MainMenu.xib new file mode 100644 index 0000000..80e867a --- /dev/null +++ b/macos/Runner/Base.lproj/MainMenu.xib @@ -0,0 +1,343 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/macos/Runner/Configs/AppInfo.xcconfig b/macos/Runner/Configs/AppInfo.xcconfig new file mode 100644 index 0000000..28424c4 --- /dev/null +++ b/macos/Runner/Configs/AppInfo.xcconfig @@ -0,0 +1,14 @@ +// Application-level settings for the Runner target. +// +// This may be replaced with something auto-generated from metadata (e.g., pubspec.yaml) in the +// future. If not, the values below would default to using the project name when this becomes a +// 'flutter create' template. + +// The application's name. By default this is also the title of the Flutter window. +PRODUCT_NAME = posyandu_care + +// The application's bundle identifier +PRODUCT_BUNDLE_IDENTIFIER = com.example.posyanduCare + +// The copyright displayed in application information +PRODUCT_COPYRIGHT = Copyright © 2026 com.example. All rights reserved. diff --git a/macos/Runner/Configs/Debug.xcconfig b/macos/Runner/Configs/Debug.xcconfig new file mode 100644 index 0000000..36b0fd9 --- /dev/null +++ b/macos/Runner/Configs/Debug.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Debug.xcconfig" +#include "Warnings.xcconfig" diff --git a/macos/Runner/Configs/Release.xcconfig b/macos/Runner/Configs/Release.xcconfig new file mode 100644 index 0000000..dff4f49 --- /dev/null +++ b/macos/Runner/Configs/Release.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Release.xcconfig" +#include "Warnings.xcconfig" diff --git a/macos/Runner/Configs/Warnings.xcconfig b/macos/Runner/Configs/Warnings.xcconfig new file mode 100644 index 0000000..42bcbf4 --- /dev/null +++ b/macos/Runner/Configs/Warnings.xcconfig @@ -0,0 +1,13 @@ +WARNING_CFLAGS = -Wall -Wconditional-uninitialized -Wnullable-to-nonnull-conversion -Wmissing-method-return-type -Woverlength-strings +GCC_WARN_UNDECLARED_SELECTOR = YES +CLANG_UNDEFINED_BEHAVIOR_SANITIZER_NULLABILITY = YES +CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE +CLANG_WARN__DUPLICATE_METHOD_MATCH = YES +CLANG_WARN_PRAGMA_PACK = YES +CLANG_WARN_STRICT_PROTOTYPES = YES +CLANG_WARN_COMMA = YES +GCC_WARN_STRICT_SELECTOR_MATCH = YES +CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES +CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES +GCC_WARN_SHADOW = YES +CLANG_WARN_UNREACHABLE_CODE = YES diff --git a/macos/Runner/DebugProfile.entitlements b/macos/Runner/DebugProfile.entitlements new file mode 100644 index 0000000..dddb8a3 --- /dev/null +++ b/macos/Runner/DebugProfile.entitlements @@ -0,0 +1,12 @@ + + + + + com.apple.security.app-sandbox + + com.apple.security.cs.allow-jit + + com.apple.security.network.server + + + diff --git a/macos/Runner/Info.plist b/macos/Runner/Info.plist new file mode 100644 index 0000000..4789daa --- /dev/null +++ b/macos/Runner/Info.plist @@ -0,0 +1,32 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIconFile + + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSMinimumSystemVersion + $(MACOSX_DEPLOYMENT_TARGET) + NSHumanReadableCopyright + $(PRODUCT_COPYRIGHT) + NSMainNibFile + MainMenu + NSPrincipalClass + NSApplication + + diff --git a/macos/Runner/MainFlutterWindow.swift b/macos/Runner/MainFlutterWindow.swift new file mode 100644 index 0000000..3cc05eb --- /dev/null +++ b/macos/Runner/MainFlutterWindow.swift @@ -0,0 +1,15 @@ +import Cocoa +import FlutterMacOS + +class MainFlutterWindow: NSWindow { + override func awakeFromNib() { + let flutterViewController = FlutterViewController() + let windowFrame = self.frame + self.contentViewController = flutterViewController + self.setFrame(windowFrame, display: true) + + RegisterGeneratedPlugins(registry: flutterViewController) + + super.awakeFromNib() + } +} diff --git a/macos/Runner/Release.entitlements b/macos/Runner/Release.entitlements new file mode 100644 index 0000000..852fa1a --- /dev/null +++ b/macos/Runner/Release.entitlements @@ -0,0 +1,8 @@ + + + + + com.apple.security.app-sandbox + + + diff --git a/macos/RunnerTests/RunnerTests.swift b/macos/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..61f3bd1 --- /dev/null +++ b/macos/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Cocoa +import FlutterMacOS +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/pubspec.lock b/pubspec.lock new file mode 100644 index 0000000..4bab19d --- /dev/null +++ b/pubspec.lock @@ -0,0 +1,1095 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + archive: + dependency: transitive + description: + name: archive + sha256: a96e8b390886ee8abb49b7bd3ac8df6f451c621619f52a26e815fdcf568959ff + url: "https://pub.dev" + source: hosted + version: "4.0.9" + args: + dependency: transitive + description: + name: args + sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04 + url: "https://pub.dev" + source: hosted + version: "2.7.0" + async: + dependency: transitive + description: + name: async + sha256: e2eb0491ba5ddb6177742d2da23904574082139b07c1e33b8503b9f46f3e1a37 + url: "https://pub.dev" + source: hosted + version: "2.13.1" + audioplayers: + dependency: "direct main" + description: + name: audioplayers + sha256: a72dd459d1a48f61a6fb9c0134dba26597c9236af40639ff0eb70eb4e0baab70 + url: "https://pub.dev" + source: hosted + version: "6.6.0" + audioplayers_android: + dependency: transitive + description: + name: audioplayers_android + sha256: "60a6728277228413a85755bd3ffd6fab98f6555608923813ce383b190a360605" + url: "https://pub.dev" + source: hosted + version: "5.2.1" + audioplayers_darwin: + dependency: transitive + description: + name: audioplayers_darwin + sha256: c994b3bb3a921e4904ac40e013fbc94488e824fd7c1de6326f549943b0b44a91 + url: "https://pub.dev" + source: hosted + version: "6.4.0" + audioplayers_linux: + dependency: transitive + description: + name: audioplayers_linux + sha256: f75bce1ce864170ef5e6a2c6a61cd3339e1a17ce11e99a25bae4474ea491d001 + url: "https://pub.dev" + source: hosted + version: "4.2.1" + audioplayers_platform_interface: + dependency: transitive + description: + name: audioplayers_platform_interface + sha256: "0e2f6a919ab56d0fec272e801abc07b26ae7f31980f912f24af4748763e5a656" + url: "https://pub.dev" + source: hosted + version: "7.1.1" + audioplayers_web: + dependency: transitive + description: + name: audioplayers_web + sha256: faa8fa6587f996a6f604433b53af44c57a1407d4fe8dff5766cf63d6875e8de9 + url: "https://pub.dev" + source: hosted + version: "5.2.0" + audioplayers_windows: + dependency: transitive + description: + name: audioplayers_windows + sha256: bafff2b38b6f6d331887558ba6e0a01c9c208d9dbb3ad0005234db065122a734 + url: "https://pub.dev" + source: hosted + version: "4.3.0" + barcode: + dependency: transitive + description: + name: barcode + sha256: "7b6729c37e3b7f34233e2318d866e8c48ddb46c1f7ad01ff7bb2a8de1da2b9f4" + url: "https://pub.dev" + source: hosted + version: "2.2.9" + bidi: + dependency: transitive + description: + name: bidi + sha256: "77f475165e94b261745cf1032c751e2032b8ed92ccb2bf5716036db79320637d" + url: "https://pub.dev" + source: hosted + version: "2.0.13" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + characters: + dependency: transitive + description: + name: characters + sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b + url: "https://pub.dev" + source: hosted + version: "1.4.1" + charcode: + dependency: transitive + description: + name: charcode + sha256: fb0f1107cac15a5ea6ef0a6ef71a807b9e4267c713bb93e00e92d737cc8dbd8a + url: "https://pub.dev" + source: hosted + version: "1.4.0" + checked_yaml: + dependency: transitive + description: + name: checked_yaml + sha256: "959525d3162f249993882720d52b7e0c833978df229be20702b33d48d91de70f" + url: "https://pub.dev" + source: hosted + version: "2.0.4" + cli_util: + dependency: transitive + description: + name: cli_util + sha256: ff6785f7e9e3c38ac98b2fb035701789de90154024a75b6cb926445e83197d1c + url: "https://pub.dev" + source: hosted + version: "0.4.2" + clock: + dependency: transitive + description: + name: clock + sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b + url: "https://pub.dev" + source: hosted + version: "1.1.2" + code_assets: + dependency: transitive + description: + name: code_assets + sha256: "83ccdaa064c980b5596c35dd64a8d3ecc68620174ab9b90b6343b753aa721687" + url: "https://pub.dev" + source: hosted + version: "1.0.0" + collection: + dependency: transitive + description: + name: collection + sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" + url: "https://pub.dev" + source: hosted + version: "1.19.1" + cross_file: + dependency: transitive + description: + name: cross_file + sha256: "28bb3ae56f117b5aec029d702a90f57d285cd975c3c5c281eaca38dbc47c5937" + url: "https://pub.dev" + source: hosted + version: "0.3.5+2" + crypto: + dependency: transitive + description: + name: crypto + sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf + url: "https://pub.dev" + source: hosted + version: "3.0.7" + csslib: + dependency: transitive + description: + name: csslib + sha256: "09bad715f418841f976c77db72d5398dc1253c21fb9c0c7f0b0b985860b2d58e" + url: "https://pub.dev" + source: hosted + version: "1.0.2" + cupertino_icons: + dependency: "direct main" + description: + name: cupertino_icons + sha256: "41e005c33bd814be4d3096aff55b1908d419fde52ca656c8c47719ec745873cd" + url: "https://pub.dev" + source: hosted + version: "1.0.9" + dart_quill_delta: + dependency: transitive + description: + name: dart_quill_delta + sha256: bddb0b2948bd5b5a328f1651764486d162c59a8ccffd4c63e8b2c5e44be1dac4 + url: "https://pub.dev" + source: hosted + version: "10.8.3" + diff_match_patch: + dependency: transitive + description: + name: diff_match_patch + sha256: "2efc9e6e8f449d0abe15be240e2c2a3bcd977c8d126cfd70598aee60af35c0a4" + url: "https://pub.dev" + source: hosted + version: "0.4.1" + equatable: + dependency: transitive + description: + name: equatable + sha256: "3e0141505477fd8ad55d6eb4e7776d3fe8430be8e497ccb1521370c3f21a3e2b" + url: "https://pub.dev" + source: hosted + version: "2.0.8" + fake_async: + dependency: transitive + description: + name: fake_async + sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44" + url: "https://pub.dev" + source: hosted + version: "1.3.3" + ffi: + dependency: transitive + description: + name: ffi + sha256: "6d7fd89431262d8f3125e81b50d3847a091d846eafcd4fdb88dd06f36d705a45" + url: "https://pub.dev" + source: hosted + version: "2.2.0" + file: + dependency: transitive + description: + name: file + sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4 + url: "https://pub.dev" + source: hosted + version: "7.0.1" + file_selector_linux: + dependency: transitive + description: + name: file_selector_linux + sha256: "2567f398e06ac72dcf2e98a0c95df2a9edd03c2c2e0cacd4780f20cdf56263a0" + url: "https://pub.dev" + source: hosted + version: "0.9.4" + file_selector_macos: + dependency: transitive + description: + name: file_selector_macos + sha256: "5e0bbe9c312416f1787a68259ea1505b52f258c587f12920422671807c4d618a" + url: "https://pub.dev" + source: hosted + version: "0.9.5" + file_selector_platform_interface: + dependency: transitive + description: + name: file_selector_platform_interface + sha256: "35e0bd61ebcdb91a3505813b055b09b79dfdc7d0aee9c09a7ba59ae4bb13dc85" + url: "https://pub.dev" + source: hosted + version: "2.7.0" + file_selector_windows: + dependency: transitive + description: + name: file_selector_windows + sha256: "62197474ae75893a62df75939c777763d39c2bc5f73ce5b88497208bc269abfd" + url: "https://pub.dev" + source: hosted + version: "0.9.3+5" + fixnum: + dependency: transitive + description: + name: fixnum + sha256: b6dc7065e46c974bc7c5f143080a6764ec7a4be6da1285ececdc37be96de53be + url: "https://pub.dev" + source: hosted + version: "1.1.1" + fl_chart: + dependency: "direct main" + description: + name: fl_chart + sha256: b938f77d042cbcd822936a7a359a7235bad8bd72070de1f827efc2cc297ac888 + url: "https://pub.dev" + source: hosted + version: "1.2.0" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_colorpicker: + dependency: transitive + description: + name: flutter_colorpicker + sha256: "969de5f6f9e2a570ac660fb7b501551451ea2a1ab9e2097e89475f60e07816ea" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + flutter_keyboard_visibility_linux: + dependency: transitive + description: + name: flutter_keyboard_visibility_linux + sha256: "6fba7cd9bb033b6ddd8c2beb4c99ad02d728f1e6e6d9b9446667398b2ac39f08" + url: "https://pub.dev" + source: hosted + version: "1.0.0" + flutter_keyboard_visibility_macos: + dependency: transitive + description: + name: flutter_keyboard_visibility_macos + sha256: c5c49b16fff453dfdafdc16f26bdd8fb8d55812a1d50b0ce25fc8d9f2e53d086 + url: "https://pub.dev" + source: hosted + version: "1.0.0" + flutter_keyboard_visibility_platform_interface: + dependency: transitive + description: + name: flutter_keyboard_visibility_platform_interface + sha256: e43a89845873f7be10cb3884345ceb9aebf00a659f479d1c8f4293fcb37022a4 + url: "https://pub.dev" + source: hosted + version: "2.0.0" + flutter_keyboard_visibility_temp_fork: + dependency: transitive + description: + name: flutter_keyboard_visibility_temp_fork + sha256: e3d02900640fbc1129245540db16944a0898b8be81694f4bf04b6c985bed9048 + url: "https://pub.dev" + source: hosted + version: "0.1.5" + flutter_keyboard_visibility_windows: + dependency: transitive + description: + name: flutter_keyboard_visibility_windows + sha256: fc4b0f0b6be9b93ae527f3d527fb56ee2d918cd88bbca438c478af7bcfd0ef73 + url: "https://pub.dev" + source: hosted + version: "1.0.0" + flutter_launcher_icons: + dependency: "direct main" + description: + name: flutter_launcher_icons + sha256: "526faf84284b86a4cb36d20a5e45147747b7563d921373d4ee0559c54fcdbcea" + url: "https://pub.dev" + source: hosted + version: "0.13.1" + flutter_lints: + dependency: "direct dev" + description: + name: flutter_lints + sha256: "3105dc8492f6183fb076ccf1f351ac3d60564bff92e20bfc4af9cc1651f4e7e1" + url: "https://pub.dev" + source: hosted + version: "6.0.0" + flutter_localizations: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + flutter_plugin_android_lifecycle: + dependency: transitive + description: + name: flutter_plugin_android_lifecycle + sha256: "38d1c268de9097ff59cf0e844ac38759fc78f76836d37edad06fa21e182055a0" + url: "https://pub.dev" + source: hosted + version: "2.0.34" + flutter_quill: + dependency: "direct main" + description: + name: flutter_quill + sha256: b96bb8525afdeaaea52f5d02f525e05cc34acd176467ab6d6f35d434cf14fde2 + url: "https://pub.dev" + source: hosted + version: "11.5.0" + flutter_quill_delta_from_html: + dependency: transitive + description: + name: flutter_quill_delta_from_html + sha256: "0eb801ea8dd498cadc057507af5da794d4c9599ce58b2569cb3d4bb53ba8bed2" + url: "https://pub.dev" + source: hosted + version: "1.5.3" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + flutter_web_plugins: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + glob: + dependency: transitive + description: + name: glob + sha256: c3f1ee72c96f8f78935e18aa8cecced9ab132419e8625dc187e1c2408efc20de + url: "https://pub.dev" + source: hosted + version: "2.1.3" + google_fonts: + dependency: "direct main" + description: + name: google_fonts + sha256: "4e9391085e524954a51e3625b7c9c7e9851dc3f376603208bb45c24b9a66255d" + url: "https://pub.dev" + source: hosted + version: "8.1.0" + hooks: + dependency: transitive + description: + name: hooks + sha256: "025f060e86d2d4c3c47b56e33caf7f93bf9283340f26d23424ebcfccf34f621e" + url: "https://pub.dev" + source: hosted + version: "1.0.3" + html: + dependency: transitive + description: + name: html + sha256: "6d1264f2dffa1b1101c25a91dff0dc2daee4c18e87cd8538729773c073dbf602" + url: "https://pub.dev" + source: hosted + version: "0.15.6" + http: + dependency: "direct main" + description: + name: http + sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412" + url: "https://pub.dev" + source: hosted + version: "1.6.0" + http_parser: + dependency: transitive + description: + name: http_parser + sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571" + url: "https://pub.dev" + source: hosted + version: "4.1.2" + image: + dependency: transitive + description: + name: image + sha256: f9881ff4998044947ec38d098bc7c8316ae1186fa786eddffdb867b9bc94dfce + url: "https://pub.dev" + source: hosted + version: "4.8.0" + image_picker: + dependency: "direct main" + description: + name: image_picker + sha256: "91c025426c2881c551100bce834e201c835a170151545f58d17da5180ca7d9ac" + url: "https://pub.dev" + source: hosted + version: "1.2.2" + image_picker_android: + dependency: "direct overridden" + description: + name: image_picker_android + sha256: c0a6763d50b354793d0192afd0a12560b823147d3ded7c6b77daf658fa05cc85 + url: "https://pub.dev" + source: hosted + version: "0.8.12+13" + image_picker_for_web: + dependency: transitive + description: + name: image_picker_for_web + sha256: "66257a3191ab360d23a55c8241c91a6e329d31e94efa7be9cf7a212e65850214" + url: "https://pub.dev" + source: hosted + version: "3.1.1" + image_picker_ios: + dependency: transitive + description: + name: image_picker_ios + sha256: b9c4a438a9ff4f60808c9cf0039b93a42bb6c2211ef6ebb647394b2b3fa84588 + url: "https://pub.dev" + source: hosted + version: "0.8.13+6" + image_picker_linux: + dependency: transitive + description: + name: image_picker_linux + sha256: "1f81c5f2046b9ab724f85523e4af65be1d47b038160a8c8deed909762c308ed4" + url: "https://pub.dev" + source: hosted + version: "0.2.2" + image_picker_macos: + dependency: transitive + description: + name: image_picker_macos + sha256: "86f0f15a309de7e1a552c12df9ce5b59fe927e71385329355aec4776c6a8ec91" + url: "https://pub.dev" + source: hosted + version: "0.2.2+1" + image_picker_platform_interface: + dependency: transitive + description: + name: image_picker_platform_interface + sha256: "567e056716333a1647c64bb6bd873cff7622233a5c3f694be28a583d4715690c" + url: "https://pub.dev" + source: hosted + version: "2.11.1" + image_picker_windows: + dependency: transitive + description: + name: image_picker_windows + sha256: d248c86554a72b5495a31c56f060cf73a41c7ff541689327b1a7dbccc33adfae + url: "https://pub.dev" + source: hosted + version: "0.2.2" + intl: + dependency: "direct main" + description: + name: intl + sha256: "3df61194eb431efc39c4ceba583b95633a403f46c9fd341e550ce0bfa50e9aa5" + url: "https://pub.dev" + source: hosted + version: "0.20.2" + json_annotation: + dependency: transitive + description: + name: json_annotation + sha256: cb09e7dac6210041fad964ed7fbee004f14258b4eca4040f72d1234062ace4c8 + url: "https://pub.dev" + source: hosted + version: "4.11.0" + leak_tracker: + dependency: transitive + description: + name: leak_tracker + sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de" + url: "https://pub.dev" + source: hosted + version: "11.0.2" + leak_tracker_flutter_testing: + dependency: transitive + description: + name: leak_tracker_flutter_testing + sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1" + url: "https://pub.dev" + source: hosted + version: "3.0.10" + leak_tracker_testing: + dependency: transitive + description: + name: leak_tracker_testing + sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1" + url: "https://pub.dev" + source: hosted + version: "3.0.2" + lints: + dependency: transitive + description: + name: lints + sha256: "12f842a479589fea194fe5c5a3095abc7be0c1f2ddfa9a0e76aed1dbd26a87df" + url: "https://pub.dev" + source: hosted + version: "6.1.0" + logging: + dependency: transitive + description: + name: logging + sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61 + url: "https://pub.dev" + source: hosted + version: "1.3.0" + markdown: + dependency: transitive + description: + name: markdown + sha256: ee85086ad7698b42522c6ad42fe195f1b9898e4d974a1af4576c1a3a176cada9 + url: "https://pub.dev" + source: hosted + version: "7.3.1" + matcher: + dependency: transitive + description: + name: matcher + sha256: dc0b7dc7651697ea4ff3e69ef44b0407ea32c487a39fff6a4004fa585e901861 + url: "https://pub.dev" + source: hosted + version: "0.12.19" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b" + url: "https://pub.dev" + source: hosted + version: "0.13.0" + meta: + dependency: transitive + description: + name: meta + sha256: "23f08335362185a5ea2ad3a4e597f1375e78bce8a040df5c600c8d3552ef2394" + url: "https://pub.dev" + source: hosted + version: "1.17.0" + mime: + dependency: transitive + description: + name: mime + sha256: "41a20518f0cb1256669420fdba0cd90d21561e560ac240f26ef8322e45bb7ed6" + url: "https://pub.dev" + source: hosted + version: "2.0.0" + native_toolchain_c: + dependency: transitive + description: + name: native_toolchain_c + sha256: "6ba77bb18063eebe9de401f5e6437e95e1438af0a87a3a39084fbd37c90df572" + url: "https://pub.dev" + source: hosted + version: "0.17.6" + objective_c: + dependency: transitive + description: + name: objective_c + sha256: "100a1c87616ab6ed41ec263b083c0ef3261ee6cd1dc3b0f35f8ddfa4f996fe52" + url: "https://pub.dev" + source: hosted + version: "9.3.0" + path: + dependency: transitive + description: + name: path + sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" + url: "https://pub.dev" + source: hosted + version: "1.9.1" + path_parsing: + dependency: transitive + description: + name: path_parsing + sha256: "883402936929eac138ee0a45da5b0f2c80f89913e6dc3bf77eb65b84b409c6ca" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + path_provider: + dependency: transitive + description: + name: path_provider + sha256: "50c5dd5b6e1aaf6fb3a78b33f6aa3afca52bf903a8a5298f53101fdaee55bbcd" + url: "https://pub.dev" + source: hosted + version: "2.1.5" + path_provider_android: + dependency: "direct overridden" + description: + name: path_provider_android + sha256: "4adf4fd5423ec60a29506c76581bc05854c55e3a0b72d35bb28d661c9686edf2" + url: "https://pub.dev" + source: hosted + version: "2.2.15" + path_provider_foundation: + dependency: transitive + description: + name: path_provider_foundation + sha256: "2a376b7d6392d80cd3705782d2caa734ca4727776db0b6ec36ef3f1855197699" + url: "https://pub.dev" + source: hosted + version: "2.6.0" + path_provider_linux: + dependency: transitive + description: + name: path_provider_linux + sha256: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279 + url: "https://pub.dev" + source: hosted + version: "2.2.1" + path_provider_platform_interface: + dependency: transitive + description: + name: path_provider_platform_interface + sha256: "88f5779f72ba699763fa3a3b06aa4bf6de76c8e5de842cf6f29e2e06476c2334" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + path_provider_windows: + dependency: transitive + description: + name: path_provider_windows + sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7 + url: "https://pub.dev" + source: hosted + version: "2.3.0" + pdf: + dependency: "direct main" + description: + name: pdf + sha256: e47a275b267873d5944ad5f5ff0dcc7ac2e36c02b3046a0ffac9b72fd362c44b + url: "https://pub.dev" + source: hosted + version: "3.12.0" + pdf_widget_wrapper: + dependency: transitive + description: + name: pdf_widget_wrapper + sha256: c930860d987213a3d58c7ec3b7ecf8085c3897f773e8dc23da9cae60a5d6d0f5 + url: "https://pub.dev" + source: hosted + version: "1.0.4" + petitparser: + dependency: transitive + description: + name: petitparser + sha256: "91bd59303e9f769f108f8df05e371341b15d59e995e6806aefab827b58336675" + url: "https://pub.dev" + source: hosted + version: "7.0.2" + platform: + dependency: transitive + description: + name: platform + sha256: "5d6b1b0036a5f331ebc77c850ebc8506cbc1e9416c27e59b439f917a902a4984" + url: "https://pub.dev" + source: hosted + version: "3.1.6" + plugin_platform_interface: + dependency: transitive + description: + name: plugin_platform_interface + sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02" + url: "https://pub.dev" + source: hosted + version: "2.1.8" + posix: + dependency: transitive + description: + name: posix + sha256: "185ef7606574f789b40f289c233efa52e96dead518aed988e040a10737febb07" + url: "https://pub.dev" + source: hosted + version: "6.5.0" + printing: + dependency: "direct main" + description: + name: printing + sha256: "689170c9ddb1bda85826466ba80378aa8993486d3c959a71cd7d2d80cb606692" + url: "https://pub.dev" + source: hosted + version: "5.14.3" + pub_semver: + dependency: transitive + description: + name: pub_semver + sha256: "5bfcf68ca79ef689f8990d1160781b4bad40a3bd5e5218ad4076ddb7f4081585" + url: "https://pub.dev" + source: hosted + version: "2.2.0" + qr: + dependency: transitive + description: + name: qr + sha256: "5a1d2586170e172b8a8c8470bbbffd5eb0cd38a66c0d77155ea138d3af3a4445" + url: "https://pub.dev" + source: hosted + version: "3.0.2" + quill_native_bridge: + dependency: transitive + description: + name: quill_native_bridge + sha256: "76a16512e398e84216f3f659f7cb18a89ec1e141ea908e954652b4ce6cf15b18" + url: "https://pub.dev" + source: hosted + version: "11.1.0" + quill_native_bridge_android: + dependency: transitive + description: + name: quill_native_bridge_android + sha256: b75c7e6ede362a7007f545118e756b1f19053994144ec9eda932ce5e54a57569 + url: "https://pub.dev" + source: hosted + version: "0.0.1+2" + quill_native_bridge_ios: + dependency: transitive + description: + name: quill_native_bridge_ios + sha256: d23de3cd7724d482fe2b514617f8eedc8f296e120fb297368917ac3b59d8099f + url: "https://pub.dev" + source: hosted + version: "0.0.1" + quill_native_bridge_macos: + dependency: transitive + description: + name: quill_native_bridge_macos + sha256: "1c0631bd1e2eee765a8b06017c5286a4e829778f4585736e048eb67c97af8a77" + url: "https://pub.dev" + source: hosted + version: "0.0.1" + quill_native_bridge_platform_interface: + dependency: transitive + description: + name: quill_native_bridge_platform_interface + sha256: "8264a2bdb8a294c31377a27b46c0f8717fa9f968cf113f7dc52d332ed9c84526" + url: "https://pub.dev" + source: hosted + version: "0.0.2+1" + quill_native_bridge_web: + dependency: transitive + description: + name: quill_native_bridge_web + sha256: "7c723f6824b0250d7f33e8b6c23f2f8eb0103fe48ee7ebf47ab6786b64d5c05d" + url: "https://pub.dev" + source: hosted + version: "0.0.2" + quill_native_bridge_windows: + dependency: transitive + description: + name: quill_native_bridge_windows + sha256: "3f96ced19e3206ddf4f6f7dde3eb16bdd05e10294964009ea3a806d995aa7caa" + url: "https://pub.dev" + source: hosted + version: "0.0.2" + quiver: + dependency: transitive + description: + name: quiver + sha256: ea0b925899e64ecdfbf9c7becb60d5b50e706ade44a85b2363be2a22d88117d2 + url: "https://pub.dev" + source: hosted + version: "3.2.2" + record_use: + dependency: transitive + description: + name: record_use + sha256: "2551bd8eecfe95d14ae75f6021ad0248be5c27f138c2ec12fcb52b500b3ba1ed" + url: "https://pub.dev" + source: hosted + version: "0.6.0" + shared_preferences: + dependency: "direct main" + description: + name: shared_preferences + sha256: c3025c5534b01739267eb7d76959bbc25a6d10f6988e1c2a3036940133dd10bf + url: "https://pub.dev" + source: hosted + version: "2.5.5" + shared_preferences_android: + dependency: "direct overridden" + description: + name: shared_preferences_android + sha256: "480ba4345773f56acda9abf5f50bd966f581dac5d514e5fc4a18c62976bbba7e" + url: "https://pub.dev" + source: hosted + version: "2.3.2" + shared_preferences_foundation: + dependency: transitive + description: + name: shared_preferences_foundation + sha256: "4e7eaffc2b17ba398759f1151415869a34771ba11ebbccd1b0145472a619a64f" + url: "https://pub.dev" + source: hosted + version: "2.5.6" + shared_preferences_linux: + dependency: transitive + description: + name: shared_preferences_linux + sha256: "580abfd40f415611503cae30adf626e6656dfb2f0cee8f465ece7b6defb40f2f" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + shared_preferences_platform_interface: + dependency: transitive + description: + name: shared_preferences_platform_interface + sha256: "649dc798a33931919ea356c4305c2d1f81619ea6e92244070b520187b5140ef9" + url: "https://pub.dev" + source: hosted + version: "2.4.2" + shared_preferences_web: + dependency: transitive + description: + name: shared_preferences_web + sha256: c49bd060261c9a3f0ff445892695d6212ff603ef3115edbb448509d407600019 + url: "https://pub.dev" + source: hosted + version: "2.4.3" + shared_preferences_windows: + dependency: transitive + description: + name: shared_preferences_windows + sha256: "94ef0f72b2d71bc3e700e025db3710911bd51a71cefb65cc609dd0d9a982e3c1" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + source_span: + dependency: transitive + description: + name: source_span + sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab" + url: "https://pub.dev" + source: hosted + version: "1.10.2" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1" + url: "https://pub.dev" + source: hosted + version: "1.12.1" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43" + url: "https://pub.dev" + source: hosted + version: "1.4.1" + synchronized: + dependency: transitive + description: + name: synchronized + sha256: "63896c27e81b28f8cb4e69ead0d3e8f03f1d1e5fc531a3e579cabed6a2c7c9e5" + url: "https://pub.dev" + source: hosted + version: "3.4.0+1" + term_glyph: + dependency: transitive + description: + name: term_glyph + sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e" + url: "https://pub.dev" + source: hosted + version: "1.2.2" + test_api: + dependency: transitive + description: + name: test_api + sha256: "8161c84903fd860b26bfdefb7963b3f0b68fee7adea0f59ef805ecca346f0c7a" + url: "https://pub.dev" + source: hosted + version: "0.7.10" + typed_data: + dependency: transitive + description: + name: typed_data + sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + url_launcher: + dependency: transitive + description: + name: url_launcher + sha256: f6a7e5c4835bb4e3026a04793a4199ca2d14c739ec378fdfe23fc8075d0439f8 + url: "https://pub.dev" + source: hosted + version: "6.3.2" + url_launcher_android: + dependency: "direct overridden" + description: + name: url_launcher_android + sha256: "6fc2f56536ee873eeb867ad176ae15f304ccccc357848b351f6f0d8d4a40d193" + url: "https://pub.dev" + source: hosted + version: "6.3.14" + url_launcher_ios: + dependency: transitive + description: + name: url_launcher_ios + sha256: "580fe5dfb51671ae38191d316e027f6b76272b026370708c2d898799750a02b0" + url: "https://pub.dev" + source: hosted + version: "6.4.1" + url_launcher_linux: + dependency: transitive + description: + name: url_launcher_linux + sha256: d5e14138b3bc193a0f63c10a53c94b91d399df0512b1f29b94a043db7482384a + url: "https://pub.dev" + source: hosted + version: "3.2.2" + url_launcher_macos: + dependency: transitive + description: + name: url_launcher_macos + sha256: "368adf46f71ad3c21b8f06614adb38346f193f3a59ba8fe9a2fd74133070ba18" + url: "https://pub.dev" + source: hosted + version: "3.2.5" + url_launcher_platform_interface: + dependency: transitive + description: + name: url_launcher_platform_interface + sha256: "552f8a1e663569be95a8190206a38187b531910283c3e982193e4f2733f01029" + url: "https://pub.dev" + source: hosted + version: "2.3.2" + url_launcher_web: + dependency: transitive + description: + name: url_launcher_web + sha256: d0412fcf4c6b31ecfdb7762359b7206ffba3bbffd396c6d9f9c4616ece476c1f + url: "https://pub.dev" + source: hosted + version: "2.4.2" + url_launcher_windows: + dependency: transitive + description: + name: url_launcher_windows + sha256: "712c70ab1b99744ff066053cbe3e80c73332b38d46e5e945c98689b2e66fc15f" + url: "https://pub.dev" + source: hosted + version: "3.1.5" + uuid: + dependency: transitive + description: + name: uuid + sha256: "1fef9e8e11e2991bb773070d4656b7bd5d850967a2456cfc83cf47925ba79489" + url: "https://pub.dev" + source: hosted + version: "4.5.3" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b + url: "https://pub.dev" + source: hosted + version: "2.2.0" + vm_service: + dependency: transitive + description: + name: vm_service + sha256: "0016aef94fc66495ac78af5859181e3f3bf2026bd8eecc72b9565601e19ab360" + url: "https://pub.dev" + source: hosted + version: "15.2.0" + web: + dependency: transitive + description: + name: web + sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a" + url: "https://pub.dev" + source: hosted + version: "1.1.1" + win32: + dependency: transitive + description: + name: win32 + sha256: d7cb55e04cd34096cd3a79b3330245f54cb96a370a1c27adb3c84b917de8b08e + url: "https://pub.dev" + source: hosted + version: "5.15.0" + xdg_directories: + dependency: transitive + description: + name: xdg_directories + sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + xml: + dependency: transitive + description: + name: xml + sha256: "971043b3a0d3da28727e40ed3e0b5d18b742fa5a68665cca88e74b7876d5e025" + url: "https://pub.dev" + source: hosted + version: "6.6.1" + yaml: + dependency: transitive + description: + name: yaml + sha256: b9da305ac7c39faa3f030eccd175340f968459dae4af175130b3fc47e40d76ce + url: "https://pub.dev" + source: hosted + version: "3.1.3" +sdks: + dart: ">=3.11.0 <4.0.0" + flutter: ">=3.38.4" diff --git a/pubspec.yaml b/pubspec.yaml new file mode 100644 index 0000000..11c7090 --- /dev/null +++ b/pubspec.yaml @@ -0,0 +1,120 @@ +name: posyandu_care +description: "A new Flutter project." +# The following line prevents the package from being accidentally published to +# pub.dev using `flutter pub publish`. This is preferred for private packages. +publish_to: 'none' # Remove this line if you wish to publish to pub.dev + +# The following defines the version and build number for your application. +# A version number is three numbers separated by dots, like 1.2.43 +# followed by an optional build number separated by a +. +# Both the version and the builder number may be overridden in flutter +# build by specifying --build-name and --build-number, respectively. +# In Android, build-name is used as versionName while build-number used as versionCode. +# Read more about Android versioning at https://developer.android.com/studio/publish/versioning +# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion. +# Read more about iOS versioning at +# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html +# In Windows, build-name is used as the major, minor, and patch parts +# of the product and file versions while build-number is used as the build suffix. +version: 1.0.0+1 + +environment: + sdk: ^3.6.1 + +# Dependencies specify other packages that your package needs in order to work. +# To automatically upgrade your package dependencies to the latest versions +# consider running `flutter pub upgrade --major-versions`. Alternatively, +# dependencies can be manually updated by changing the version numbers below to +# the latest version available on pub.dev. To see which dependencies have newer +# versions available, run `flutter pub outdated`. +dependencies: + flutter: + sdk: flutter + + + google_fonts: ^8.1.0 + fl_chart: ^1.2.0 + http: ^1.2.1 + shared_preferences: ^2.2.2 + audioplayers: ^6.6.0 + flutter_quill: ^11.5.0 # Gunakan versi terbaru + pdf: ^3.10.7 + printing: ^5.11.1 + flutter_launcher_icons: ^0.13.1 + intl: ^0.20.2 + + # The following adds the Cupertino Icons font to your application. + # Use with the CupertinoIcons class for iOS style icons. + image_picker: ^1.0.7 + cupertino_icons: ^1.0.8 + +dev_dependencies: + flutter_test: + sdk: flutter + + # The "flutter_lints" package below contains a set of recommended lints to + # encourage good coding practices. The lint set provided by the package is + # activated in the `analysis_options.yaml` file located at the root of your + # package. See that file for information about deactivating specific lint + # rules and activating additional ones. + flutter_lints: ^6.0.0 + +flutter_launcher_icons: + android: "launcher_icon" + ios: true + image_path: "assets/images/logoo.webp" + + +# For information on the generic Dart part of this file, see the +# following page: https://dart.dev/tools/pub/pubspec + +# The following section is specific to Flutter packages. +flutter: + + # The following line ensures that the Material Icons font is + # included with your application, so that you can use the icons in + # the material Icons class. + uses-material-design: true + + + assets: + - assets/images/logoo.webp + - assets/sounds/notif.mp3 + - assets/images/logo sumberasih.png + +dependency_overrides: + image_picker_android: 0.8.12+13 + shared_preferences_android: 2.3.2 + url_launcher_android: 6.3.14 + path_provider_android: 2.2.15 + + # To add assets to your application, add an assets section, like this: + # assets: + # - images/a_dot_burr.jpeg + # - images/a_dot_ham.jpeg + + # An image asset can refer to one or more resolution-specific "variants", see + # https://flutter.dev/to/resolution-aware-images + + # For details regarding adding assets from package dependencies, see + # https://flutter.dev/to/asset-from-package + + # To add custom fonts to your application, add a fonts section here, + # in this "flutter" section. Each entry in this list should have a + # "family" key with the font family name, and a "fonts" key with a + # list giving the asset and other descriptors for the font. For + # example: + # fonts: + # - family: Schyler + # fonts: + # - asset: fonts/Schyler-Regular.ttf + # - asset: fonts/Schyler-Italic.ttf + # style: italic + # - family: Trajan Pro + # fonts: + # - asset: fonts/TrajanPro.ttf + # - asset: fonts/TrajanPro_Bold.ttf + # weight: 700 + # + # For details regarding fonts from package dependencies, + # see https://flutter.dev/to/font-from-package diff --git a/test/widget_test.dart b/test/widget_test.dart new file mode 100644 index 0000000..864bccd --- /dev/null +++ b/test/widget_test.dart @@ -0,0 +1,23 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +// Ganti posyandu_care menjadi m_posyandu sesuai nama di pubspec.yaml Anda +import 'package:posyandu_care/main.dart'; + +void main() { + testWidgets('Counter increments smoke test', (WidgetTester tester) async { + // Berikan parameter initialRoute (misal ke '/') agar tidak error + await tester.pumpWidget(const MyApp(initialRoute: '/')); + + // Catatan: Jika aplikasi Anda tidak memiliki Counter (angka 0 dan 1), + // baris expect di bawah ini mungkin akan gagal (fail), tapi tidak lagi Error Merah. + expect(find.text('0'), findsOneWidget); + expect(find.text('1'), findsNothing); + + await tester.tap(find.byIcon(Icons.add)); + await tester.pump(); + + expect(find.text('0'), findsNothing); + expect(find.text('1'), findsOneWidget); + }); +} \ No newline at end of file diff --git a/web/favicon.png b/web/favicon.png new file mode 100644 index 0000000..8aaa46a Binary files /dev/null and b/web/favicon.png differ diff --git a/web/icons/Icon-192.png b/web/icons/Icon-192.png new file mode 100644 index 0000000..b749bfe Binary files /dev/null and b/web/icons/Icon-192.png differ diff --git a/web/icons/Icon-512.png b/web/icons/Icon-512.png new file mode 100644 index 0000000..88cfd48 Binary files /dev/null and b/web/icons/Icon-512.png differ diff --git a/web/icons/Icon-maskable-192.png b/web/icons/Icon-maskable-192.png new file mode 100644 index 0000000..eb9b4d7 Binary files /dev/null and b/web/icons/Icon-maskable-192.png differ diff --git a/web/icons/Icon-maskable-512.png b/web/icons/Icon-maskable-512.png new file mode 100644 index 0000000..d69c566 Binary files /dev/null and b/web/icons/Icon-maskable-512.png differ diff --git a/web/index.html b/web/index.html new file mode 100644 index 0000000..0264aed --- /dev/null +++ b/web/index.html @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + posyandu_care + + + + + + diff --git a/web/manifest.json b/web/manifest.json new file mode 100644 index 0000000..a1b221c --- /dev/null +++ b/web/manifest.json @@ -0,0 +1,35 @@ +{ + "name": "posyandu_care", + "short_name": "posyandu_care", + "start_url": ".", + "display": "standalone", + "background_color": "#0175C2", + "theme_color": "#0175C2", + "description": "A new Flutter project.", + "orientation": "portrait-primary", + "prefer_related_applications": false, + "icons": [ + { + "src": "icons/Icon-192.png", + "sizes": "192x192", + "type": "image/png" + }, + { + "src": "icons/Icon-512.png", + "sizes": "512x512", + "type": "image/png" + }, + { + "src": "icons/Icon-maskable-192.png", + "sizes": "192x192", + "type": "image/png", + "purpose": "maskable" + }, + { + "src": "icons/Icon-maskable-512.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "maskable" + } + ] +} diff --git a/windows/.gitignore b/windows/.gitignore new file mode 100644 index 0000000..d492d0d --- /dev/null +++ b/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ephemeral/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/windows/CMakeLists.txt b/windows/CMakeLists.txt new file mode 100644 index 0000000..0473543 --- /dev/null +++ b/windows/CMakeLists.txt @@ -0,0 +1,108 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(posyandu_care LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "posyandu_care") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(VERSION 3.14...3.25) + +# Define build configuration option. +get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) +if(IS_MULTICONFIG) + set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" + CACHE STRING "" FORCE) +else() + if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") + endif() +endif() +# Define settings for the Profile build mode. +set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") +set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") +set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") +set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") + +# Use Unicode for all projects. +add_definitions(-DUNICODE -D_UNICODE) + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_17) + target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") + target_compile_options(${TARGET} PRIVATE /EHsc) + target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") + target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# Support files are copied into place next to the executable, so that it can +# run in place. This is done instead of making a separate bundle (as on Linux) +# so that building and running from within Visual Studio will work. +set(BUILD_BUNDLE_DIR "$") +# Make the "install" step default, as it's required to run. +set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +if(PLUGIN_BUNDLED_LIBRARIES) + install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + CONFIGURATIONS Profile;Release + COMPONENT Runtime) diff --git a/windows/flutter/CMakeLists.txt b/windows/flutter/CMakeLists.txt new file mode 100644 index 0000000..903f489 --- /dev/null +++ b/windows/flutter/CMakeLists.txt @@ -0,0 +1,109 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.14) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. +set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") + +# Set fallback configurations for older versions of the flutter tool. +if (NOT DEFINED FLUTTER_TARGET_PLATFORM) + set(FLUTTER_TARGET_PLATFORM "windows-x64") +endif() + +# === Flutter Library === +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "flutter_export.h" + "flutter_windows.h" + "flutter_messenger.h" + "flutter_plugin_registrar.h" + "flutter_texture_registrar.h" +) +list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") +add_dependencies(flutter flutter_assemble) + +# === Wrapper === +list(APPEND CPP_WRAPPER_SOURCES_CORE + "core_implementations.cc" + "standard_codec.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_PLUGIN + "plugin_registrar.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_APP + "flutter_engine.cc" + "flutter_view_controller.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") + +# Wrapper sources needed for a plugin. +add_library(flutter_wrapper_plugin STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} +) +apply_standard_settings(flutter_wrapper_plugin) +set_target_properties(flutter_wrapper_plugin PROPERTIES + POSITION_INDEPENDENT_CODE ON) +set_target_properties(flutter_wrapper_plugin PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) +target_include_directories(flutter_wrapper_plugin PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_plugin flutter_assemble) + +# Wrapper sources needed for the runner. +add_library(flutter_wrapper_app STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_APP} +) +apply_standard_settings(flutter_wrapper_app) +target_link_libraries(flutter_wrapper_app PUBLIC flutter) +target_include_directories(flutter_wrapper_app PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_app flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") +set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} + ${PHONY_OUTPUT} + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" + ${FLUTTER_TARGET_PLATFORM} $ + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} +) diff --git a/windows/flutter/generated_plugin_registrant.cc b/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..c5117ce --- /dev/null +++ b/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,23 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include +#include +#include +#include + +void RegisterPlugins(flutter::PluginRegistry* registry) { + AudioplayersWindowsPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("AudioplayersWindowsPlugin")); + FileSelectorWindowsRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FileSelectorWindows")); + PrintingPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("PrintingPlugin")); + UrlLauncherWindowsRegisterWithRegistrar( + registry->GetRegistrarForPlugin("UrlLauncherWindows")); +} diff --git a/windows/flutter/generated_plugin_registrant.h b/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..dc139d8 --- /dev/null +++ b/windows/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void RegisterPlugins(flutter::PluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/windows/flutter/generated_plugins.cmake b/windows/flutter/generated_plugins.cmake new file mode 100644 index 0000000..0fbd82d --- /dev/null +++ b/windows/flutter/generated_plugins.cmake @@ -0,0 +1,27 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + audioplayers_windows + file_selector_windows + printing + url_launcher_windows +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/windows/runner/CMakeLists.txt b/windows/runner/CMakeLists.txt new file mode 100644 index 0000000..394917c --- /dev/null +++ b/windows/runner/CMakeLists.txt @@ -0,0 +1,40 @@ +cmake_minimum_required(VERSION 3.14) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} WIN32 + "flutter_window.cpp" + "main.cpp" + "utils.cpp" + "win32_window.cpp" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" + "Runner.rc" + "runner.exe.manifest" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the build version. +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") + +# Disable Windows macros that collide with C++ standard library functions. +target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") + +# Add dependency libraries and include directories. Add any application-specific +# dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/windows/runner/Runner.rc b/windows/runner/Runner.rc new file mode 100644 index 0000000..4ce4957 --- /dev/null +++ b/windows/runner/Runner.rc @@ -0,0 +1,121 @@ +// Microsoft Visual C++ generated resource script. +// +#pragma code_page(65001) +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (United States) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_APP_ICON ICON "resources\\app_icon.ico" + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) +#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD +#else +#define VERSION_AS_NUMBER 1,0,0,0 +#endif + +#if defined(FLUTTER_VERSION) +#define VERSION_AS_STRING FLUTTER_VERSION +#else +#define VERSION_AS_STRING "1.0.0" +#endif + +VS_VERSION_INFO VERSIONINFO + FILEVERSION VERSION_AS_NUMBER + PRODUCTVERSION VERSION_AS_NUMBER + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK +#ifdef _DEBUG + FILEFLAGS VS_FF_DEBUG +#else + FILEFLAGS 0x0L +#endif + FILEOS VOS__WINDOWS32 + FILETYPE VFT_APP + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904e4" + BEGIN + VALUE "CompanyName", "com.example" "\0" + VALUE "FileDescription", "posyandu_care" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "posyandu_care" "\0" + VALUE "LegalCopyright", "Copyright (C) 2026 com.example. All rights reserved." "\0" + VALUE "OriginalFilename", "posyandu_care.exe" "\0" + VALUE "ProductName", "posyandu_care" "\0" + VALUE "ProductVersion", VERSION_AS_STRING "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1252 + END +END + +#endif // English (United States) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED diff --git a/windows/runner/flutter_window.cpp b/windows/runner/flutter_window.cpp new file mode 100644 index 0000000..955ee30 --- /dev/null +++ b/windows/runner/flutter_window.cpp @@ -0,0 +1,71 @@ +#include "flutter_window.h" + +#include + +#include "flutter/generated_plugin_registrant.h" + +FlutterWindow::FlutterWindow(const flutter::DartProject& project) + : project_(project) {} + +FlutterWindow::~FlutterWindow() {} + +bool FlutterWindow::OnCreate() { + if (!Win32Window::OnCreate()) { + return false; + } + + RECT frame = GetClientArea(); + + // The size here must match the window dimensions to avoid unnecessary surface + // creation / destruction in the startup path. + flutter_controller_ = std::make_unique( + frame.right - frame.left, frame.bottom - frame.top, project_); + // Ensure that basic setup of the controller was successful. + if (!flutter_controller_->engine() || !flutter_controller_->view()) { + return false; + } + RegisterPlugins(flutter_controller_->engine()); + SetChildContent(flutter_controller_->view()->GetNativeWindow()); + + flutter_controller_->engine()->SetNextFrameCallback([&]() { + this->Show(); + }); + + // Flutter can complete the first frame before the "show window" callback is + // registered. The following call ensures a frame is pending to ensure the + // window is shown. It is a no-op if the first frame hasn't completed yet. + flutter_controller_->ForceRedraw(); + + return true; +} + +void FlutterWindow::OnDestroy() { + if (flutter_controller_) { + flutter_controller_ = nullptr; + } + + Win32Window::OnDestroy(); +} + +LRESULT +FlutterWindow::MessageHandler(HWND hwnd, UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + // Give Flutter, including plugins, an opportunity to handle window messages. + if (flutter_controller_) { + std::optional result = + flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, + lparam); + if (result) { + return *result; + } + } + + switch (message) { + case WM_FONTCHANGE: + flutter_controller_->engine()->ReloadSystemFonts(); + break; + } + + return Win32Window::MessageHandler(hwnd, message, wparam, lparam); +} diff --git a/windows/runner/flutter_window.h b/windows/runner/flutter_window.h new file mode 100644 index 0000000..6da0652 --- /dev/null +++ b/windows/runner/flutter_window.h @@ -0,0 +1,33 @@ +#ifndef RUNNER_FLUTTER_WINDOW_H_ +#define RUNNER_FLUTTER_WINDOW_H_ + +#include +#include + +#include + +#include "win32_window.h" + +// A window that does nothing but host a Flutter view. +class FlutterWindow : public Win32Window { + public: + // Creates a new FlutterWindow hosting a Flutter view running |project|. + explicit FlutterWindow(const flutter::DartProject& project); + virtual ~FlutterWindow(); + + protected: + // Win32Window: + bool OnCreate() override; + void OnDestroy() override; + LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, + LPARAM const lparam) noexcept override; + + private: + // The project to run. + flutter::DartProject project_; + + // The Flutter instance hosted by this window. + std::unique_ptr flutter_controller_; +}; + +#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/windows/runner/main.cpp b/windows/runner/main.cpp new file mode 100644 index 0000000..2a394c1 --- /dev/null +++ b/windows/runner/main.cpp @@ -0,0 +1,43 @@ +#include +#include +#include + +#include "flutter_window.h" +#include "utils.h" + +int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, + _In_ wchar_t *command_line, _In_ int show_command) { + // Attach to console when present (e.g., 'flutter run') or create a + // new console when running with a debugger. + if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { + CreateAndAttachConsole(); + } + + // Initialize COM, so that it is available for use in the library and/or + // plugins. + ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); + + flutter::DartProject project(L"data"); + + std::vector command_line_arguments = + GetCommandLineArguments(); + + project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); + + FlutterWindow window(project); + Win32Window::Point origin(10, 10); + Win32Window::Size size(1280, 720); + if (!window.Create(L"posyandu_care", origin, size)) { + return EXIT_FAILURE; + } + window.SetQuitOnClose(true); + + ::MSG msg; + while (::GetMessage(&msg, nullptr, 0, 0)) { + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); + } + + ::CoUninitialize(); + return EXIT_SUCCESS; +} diff --git a/windows/runner/resource.h b/windows/runner/resource.h new file mode 100644 index 0000000..66a65d1 --- /dev/null +++ b/windows/runner/resource.h @@ -0,0 +1,16 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Runner.rc +// +#define IDI_APP_ICON 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/windows/runner/resources/app_icon.ico b/windows/runner/resources/app_icon.ico new file mode 100644 index 0000000..c04e20c Binary files /dev/null and b/windows/runner/resources/app_icon.ico differ diff --git a/windows/runner/runner.exe.manifest b/windows/runner/runner.exe.manifest new file mode 100644 index 0000000..153653e --- /dev/null +++ b/windows/runner/runner.exe.manifest @@ -0,0 +1,14 @@ + + + + + PerMonitorV2 + + + + + + + + + diff --git a/windows/runner/utils.cpp b/windows/runner/utils.cpp new file mode 100644 index 0000000..3a0b465 --- /dev/null +++ b/windows/runner/utils.cpp @@ -0,0 +1,65 @@ +#include "utils.h" + +#include +#include +#include +#include + +#include + +void CreateAndAttachConsole() { + if (::AllocConsole()) { + FILE *unused; + if (freopen_s(&unused, "CONOUT$", "w", stdout)) { + _dup2(_fileno(stdout), 1); + } + if (freopen_s(&unused, "CONOUT$", "w", stderr)) { + _dup2(_fileno(stdout), 2); + } + std::ios::sync_with_stdio(); + FlutterDesktopResyncOutputStreams(); + } +} + +std::vector GetCommandLineArguments() { + // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. + int argc; + wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); + if (argv == nullptr) { + return std::vector(); + } + + std::vector command_line_arguments; + + // Skip the first argument as it's the binary name. + for (int i = 1; i < argc; i++) { + command_line_arguments.push_back(Utf8FromUtf16(argv[i])); + } + + ::LocalFree(argv); + + return command_line_arguments; +} + +std::string Utf8FromUtf16(const wchar_t* utf16_string) { + if (utf16_string == nullptr) { + return std::string(); + } + unsigned int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, nullptr, 0, nullptr, nullptr) + -1; // remove the trailing null character + int input_length = (int)wcslen(utf16_string); + std::string utf8_string; + if (target_length == 0 || target_length > utf8_string.max_size()) { + return utf8_string; + } + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, utf8_string.data(), target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/windows/runner/utils.h b/windows/runner/utils.h new file mode 100644 index 0000000..3879d54 --- /dev/null +++ b/windows/runner/utils.h @@ -0,0 +1,19 @@ +#ifndef RUNNER_UTILS_H_ +#define RUNNER_UTILS_H_ + +#include +#include + +// Creates a console for the process, and redirects stdout and stderr to +// it for both the runner and the Flutter library. +void CreateAndAttachConsole(); + +// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string +// encoded in UTF-8. Returns an empty std::string on failure. +std::string Utf8FromUtf16(const wchar_t* utf16_string); + +// Gets the command line arguments passed in as a std::vector, +// encoded in UTF-8. Returns an empty std::vector on failure. +std::vector GetCommandLineArguments(); + +#endif // RUNNER_UTILS_H_ diff --git a/windows/runner/win32_window.cpp b/windows/runner/win32_window.cpp new file mode 100644 index 0000000..60608d0 --- /dev/null +++ b/windows/runner/win32_window.cpp @@ -0,0 +1,288 @@ +#include "win32_window.h" + +#include +#include + +#include "resource.h" + +namespace { + +/// Window attribute that enables dark mode window decorations. +/// +/// Redefined in case the developer's machine has a Windows SDK older than +/// version 10.0.22000.0. +/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute +#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE +#define DWMWA_USE_IMMERSIVE_DARK_MODE 20 +#endif + +constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; + +/// Registry key for app theme preference. +/// +/// A value of 0 indicates apps should use dark mode. A non-zero or missing +/// value indicates apps should use light mode. +constexpr const wchar_t kGetPreferredBrightnessRegKey[] = + L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; +constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; + +// The number of Win32Window objects that currently exist. +static int g_active_window_count = 0; + +using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); + +// Scale helper to convert logical scaler values to physical using passed in +// scale factor +int Scale(int source, double scale_factor) { + return static_cast(source * scale_factor); +} + +// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. +// This API is only needed for PerMonitor V1 awareness mode. +void EnableFullDpiSupportIfAvailable(HWND hwnd) { + HMODULE user32_module = LoadLibraryA("User32.dll"); + if (!user32_module) { + return; + } + auto enable_non_client_dpi_scaling = + reinterpret_cast( + GetProcAddress(user32_module, "EnableNonClientDpiScaling")); + if (enable_non_client_dpi_scaling != nullptr) { + enable_non_client_dpi_scaling(hwnd); + } + FreeLibrary(user32_module); +} + +} // namespace + +// Manages the Win32Window's window class registration. +class WindowClassRegistrar { + public: + ~WindowClassRegistrar() = default; + + // Returns the singleton registrar instance. + static WindowClassRegistrar* GetInstance() { + if (!instance_) { + instance_ = new WindowClassRegistrar(); + } + return instance_; + } + + // Returns the name of the window class, registering the class if it hasn't + // previously been registered. + const wchar_t* GetWindowClass(); + + // Unregisters the window class. Should only be called if there are no + // instances of the window. + void UnregisterWindowClass(); + + private: + WindowClassRegistrar() = default; + + static WindowClassRegistrar* instance_; + + bool class_registered_ = false; +}; + +WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; + +const wchar_t* WindowClassRegistrar::GetWindowClass() { + if (!class_registered_) { + WNDCLASS window_class{}; + window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); + window_class.lpszClassName = kWindowClassName; + window_class.style = CS_HREDRAW | CS_VREDRAW; + window_class.cbClsExtra = 0; + window_class.cbWndExtra = 0; + window_class.hInstance = GetModuleHandle(nullptr); + window_class.hIcon = + LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); + window_class.hbrBackground = 0; + window_class.lpszMenuName = nullptr; + window_class.lpfnWndProc = Win32Window::WndProc; + RegisterClass(&window_class); + class_registered_ = true; + } + return kWindowClassName; +} + +void WindowClassRegistrar::UnregisterWindowClass() { + UnregisterClass(kWindowClassName, nullptr); + class_registered_ = false; +} + +Win32Window::Win32Window() { + ++g_active_window_count; +} + +Win32Window::~Win32Window() { + --g_active_window_count; + Destroy(); +} + +bool Win32Window::Create(const std::wstring& title, + const Point& origin, + const Size& size) { + Destroy(); + + const wchar_t* window_class = + WindowClassRegistrar::GetInstance()->GetWindowClass(); + + const POINT target_point = {static_cast(origin.x), + static_cast(origin.y)}; + HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); + UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); + double scale_factor = dpi / 96.0; + + HWND window = CreateWindow( + window_class, title.c_str(), WS_OVERLAPPEDWINDOW, + Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), + Scale(size.width, scale_factor), Scale(size.height, scale_factor), + nullptr, nullptr, GetModuleHandle(nullptr), this); + + if (!window) { + return false; + } + + UpdateTheme(window); + + return OnCreate(); +} + +bool Win32Window::Show() { + return ShowWindow(window_handle_, SW_SHOWNORMAL); +} + +// static +LRESULT CALLBACK Win32Window::WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + if (message == WM_NCCREATE) { + auto window_struct = reinterpret_cast(lparam); + SetWindowLongPtr(window, GWLP_USERDATA, + reinterpret_cast(window_struct->lpCreateParams)); + + auto that = static_cast(window_struct->lpCreateParams); + EnableFullDpiSupportIfAvailable(window); + that->window_handle_ = window; + } else if (Win32Window* that = GetThisFromHandle(window)) { + return that->MessageHandler(window, message, wparam, lparam); + } + + return DefWindowProc(window, message, wparam, lparam); +} + +LRESULT +Win32Window::MessageHandler(HWND hwnd, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + switch (message) { + case WM_DESTROY: + window_handle_ = nullptr; + Destroy(); + if (quit_on_close_) { + PostQuitMessage(0); + } + return 0; + + case WM_DPICHANGED: { + auto newRectSize = reinterpret_cast(lparam); + LONG newWidth = newRectSize->right - newRectSize->left; + LONG newHeight = newRectSize->bottom - newRectSize->top; + + SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, + newHeight, SWP_NOZORDER | SWP_NOACTIVATE); + + return 0; + } + case WM_SIZE: { + RECT rect = GetClientArea(); + if (child_content_ != nullptr) { + // Size and position the child window. + MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, + rect.bottom - rect.top, TRUE); + } + return 0; + } + + case WM_ACTIVATE: + if (child_content_ != nullptr) { + SetFocus(child_content_); + } + return 0; + + case WM_DWMCOLORIZATIONCOLORCHANGED: + UpdateTheme(hwnd); + return 0; + } + + return DefWindowProc(window_handle_, message, wparam, lparam); +} + +void Win32Window::Destroy() { + OnDestroy(); + + if (window_handle_) { + DestroyWindow(window_handle_); + window_handle_ = nullptr; + } + if (g_active_window_count == 0) { + WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); + } +} + +Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { + return reinterpret_cast( + GetWindowLongPtr(window, GWLP_USERDATA)); +} + +void Win32Window::SetChildContent(HWND content) { + child_content_ = content; + SetParent(content, window_handle_); + RECT frame = GetClientArea(); + + MoveWindow(content, frame.left, frame.top, frame.right - frame.left, + frame.bottom - frame.top, true); + + SetFocus(child_content_); +} + +RECT Win32Window::GetClientArea() { + RECT frame; + GetClientRect(window_handle_, &frame); + return frame; +} + +HWND Win32Window::GetHandle() { + return window_handle_; +} + +void Win32Window::SetQuitOnClose(bool quit_on_close) { + quit_on_close_ = quit_on_close; +} + +bool Win32Window::OnCreate() { + // No-op; provided for subclasses. + return true; +} + +void Win32Window::OnDestroy() { + // No-op; provided for subclasses. +} + +void Win32Window::UpdateTheme(HWND const window) { + DWORD light_mode; + DWORD light_mode_size = sizeof(light_mode); + LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, + kGetPreferredBrightnessRegValue, + RRF_RT_REG_DWORD, nullptr, &light_mode, + &light_mode_size); + + if (result == ERROR_SUCCESS) { + BOOL enable_dark_mode = light_mode == 0; + DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE, + &enable_dark_mode, sizeof(enable_dark_mode)); + } +} diff --git a/windows/runner/win32_window.h b/windows/runner/win32_window.h new file mode 100644 index 0000000..e901dde --- /dev/null +++ b/windows/runner/win32_window.h @@ -0,0 +1,102 @@ +#ifndef RUNNER_WIN32_WINDOW_H_ +#define RUNNER_WIN32_WINDOW_H_ + +#include + +#include +#include +#include + +// A class abstraction for a high DPI-aware Win32 Window. Intended to be +// inherited from by classes that wish to specialize with custom +// rendering and input handling +class Win32Window { + public: + struct Point { + unsigned int x; + unsigned int y; + Point(unsigned int x, unsigned int y) : x(x), y(y) {} + }; + + struct Size { + unsigned int width; + unsigned int height; + Size(unsigned int width, unsigned int height) + : width(width), height(height) {} + }; + + Win32Window(); + virtual ~Win32Window(); + + // Creates a win32 window with |title| that is positioned and sized using + // |origin| and |size|. New windows are created on the default monitor. Window + // sizes are specified to the OS in physical pixels, hence to ensure a + // consistent size this function will scale the inputted width and height as + // as appropriate for the default monitor. The window is invisible until + // |Show| is called. Returns true if the window was created successfully. + bool Create(const std::wstring& title, const Point& origin, const Size& size); + + // Show the current window. Returns true if the window was successfully shown. + bool Show(); + + // Release OS resources associated with window. + void Destroy(); + + // Inserts |content| into the window tree. + void SetChildContent(HWND content); + + // Returns the backing Window handle to enable clients to set icon and other + // window properties. Returns nullptr if the window has been destroyed. + HWND GetHandle(); + + // If true, closing this window will quit the application. + void SetQuitOnClose(bool quit_on_close); + + // Return a RECT representing the bounds of the current client area. + RECT GetClientArea(); + + protected: + // Processes and route salient window messages for mouse handling, + // size change and DPI. Delegates handling of these to member overloads that + // inheriting classes can handle. + virtual LRESULT MessageHandler(HWND window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Called when CreateAndShow is called, allowing subclass window-related + // setup. Subclasses should return false if setup fails. + virtual bool OnCreate(); + + // Called when Destroy is called. + virtual void OnDestroy(); + + private: + friend class WindowClassRegistrar; + + // OS callback called by message pump. Handles the WM_NCCREATE message which + // is passed when the non-client area is being created and enables automatic + // non-client DPI scaling so that the non-client area automatically + // responds to changes in DPI. All other messages are handled by + // MessageHandler. + static LRESULT CALLBACK WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Retrieves a class instance pointer for |window| + static Win32Window* GetThisFromHandle(HWND const window) noexcept; + + // Update the window frame's theme to match the system theme. + static void UpdateTheme(HWND const window); + + bool quit_on_close_ = false; + + // window handle for top level window. + HWND window_handle_ = nullptr; + + // window handle for hosted content. + HWND child_content_ = nullptr; +}; + +#endif // RUNNER_WIN32_WINDOW_H_