Skip to content
TheChatArchiveThe Chat Archive
o1-preview-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

import 'package:flutter/material.dart'; import 'package:imagepicker/imagepicker.dart';…

  1. User

    import 'package:flutter/material.dart'; import 'package:image_picker/image_picker.dart'; import 'recognition_page.dart'; import 'result_page.dart'; import 'live_scan_page.dart'; import '../services/database_service.dart'; import '../services/ad_helper.dart';

    class MainPage extends StatefulWidget { const MainPage({super.key});

    @override MainPageState createState() => MainPageState(); }

    class MainPageState extends State { final TextEditingController _ingredientController = TextEditingController(); final InterstitialAdManager _interstitialAdManager = InterstitialAdManager();

    @override void initState() { super.initState(); _interstitialAdManager.loadAd(); }

    @override void dispose() { _ingredientController.dispose(); _interstitialAdManager.dispose(); super.dispose(); }

    Future _navigateToLiveScan() async { final result = await Navigator.push<Map<String, dynamic>>( context, MaterialPageRoute(builder: (context) => const LiveScanPage()), ); if (result != null) { final ingredients = result['ingredients'] as List; final genericSulfateOrSulfonateDetected = result['genericSulfateOrSulfonateDetected'] as bool;

      setState(() {
        _ingredientController.text = ingredients.join(', ');
      });
    
      try {
        final details =
            await DatabaseHelper.instance.fetchIngredientsDetails(ingredients);
        if (!mounted) return;
    
        await Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => ResultPage(
              genericSulfateOrSulfonateDetected:
                  genericSulfateOrSulfonateDetected,
              ingredientsDetails: details,
              adManager: _interstitialAdManager,
            ),
          ),
        );
      } catch (e) {
        _showErrorSnackBar('Error fetching ingredient details: $e');
      }
    }
    

    }

    Future _pickImage() async { try { final pickedImage = await ImagePicker().pickImage(source: ImageSource.gallery); if (pickedImage != null) { final result = await Navigator.push( context, MaterialPageRoute( builder: (context) => RecognitionPage(xFile: pickedImage), ), ); if (result != null) { setState(() { _ingredientController.text = result; }); } } } catch (e) { _showErrorSnackBar('Error picking image: $e'); } }

    Future _handleIngredients() async { final ingredientsText = _ingredientController.text .split(',') .map((s) => s.trim()) .where((s) => s.isNotEmpty) .toList();

    if (ingredientsText.isEmpty) {
      _showErrorSnackBar('Please enter at least one ingredient.');
      return;
    }
    
    try {
      final details = await DatabaseHelper.instance
          .fetchIngredientsDetails(ingredientsText);
      if (!mounted) return;
    
      await Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => ResultPage(
            genericSulfateOrSulfonateDetected: false,
            ingredientsDetails: details,
            adManager: _interstitialAdManager,
          ),
        ),
      );
    } catch (e) {
      _showErrorSnackBar('Error fetching ingredient details: $e');
    }
    

    }

    void _showErrorSnackBar(String message) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text(message), behavior: SnackBarBehavior.floating, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)), ), ); }

    @override Widget build(BuildContext context) { final theme = Theme.of(context);

    return Scaffold(
      appBar: AppBar(
        title: Text(
          "Curlify",
          style: theme.textTheme.headlineSmall?.copyWith(
            fontWeight: FontWeight.bold,
          ),
        ),
        elevation: 0,
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: SafeArea(
        child: Padding(
          padding: const EdgeInsets.fromLTRB(16, 0, 16, 0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget>[
              const SizedBox(height: 16),
              Card(
                elevation: 2,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(16),
                ),
                child: Padding(
                  padding: const EdgeInsets.fromLTRB(16, 8, 16, 8),
                  child: TextField(
                    controller: _ingredientController,
                    decoration: const InputDecoration(
                      hintText: 'Type in ingredients separated by a comma...',
                      border: InputBorder.none,
                    ),
                    style: theme.textTheme.bodyMedium,
                    maxLines: 5,
                  ),
                ),
              ),
              const SizedBox(height: 24),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  Expanded(
                    child: ElevatedButton.icon(
                      onPressed: _pickImage,
                      icon: const Icon(Icons.photo_library),
                      label: const Text('Gallery'),
                    ),
                  ),
                  const SizedBox(width: 16),
                  Expanded(
                    child: ElevatedButton.icon(
                      onPressed: _navigateToLiveScan,
                      icon: const Icon(Icons.camera_alt),
                      label: const Text('Scan'),
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 24),
              ElevatedButton(
                onPressed: _handleIngredients,
                child: const Text('Analyze Ingredients'),
              ),
            ],
          ),
        ),
      ),
    );
    

    } }

    import 'dart:typed_data';

    import 'package:flutter/material.dart'; import 'package:camera/camera.dart'; import 'package:flutter/services.dart'; import 'package:google_mlkit_text_recognition/google_mlkit_text_recognition.dart'; import '../services/database_service.dart';

    class LiveScanPage extends StatefulWidget { const LiveScanPage({super.key});

    @override State createState() => _LiveScanPageState(); }

    class _LiveScanPageState extends State { late CameraController _cameraController; late TextRecognizer _textRecognizer; bool _isCameraInitialized = false; bool _isProcessing = false; final Set _detectedIngredients = {}; final Map<String, dynamic> _ingredientDetails = {}; List _textBuffer = []; DateTime _lastProcessTime = DateTime.now(); bool _genericSulfateOrSulfonateDetected = false;

    @override void initState() { super.initState(); _initializeCamera(); _textRecognizer = TextRecognizer(script: TextRecognitionScript.latin); }

    @override void dispose() { _cameraController.dispose(); _textRecognizer.close(); super.dispose(); }

    Future _initializeCamera() async { final cameras = await availableCameras(); _cameraController = CameraController(cameras[0], ResolutionPreset.medium, enableAudio: false);

    await _cameraController.initialize();
    if (!mounted) return;
    
    setState(() => _isCameraInitialized = true);
    _startImageStream();
    

    }

    void _startImageStream() { _cameraController.startImageStream(_processCameraImage); }

    Future _processCameraImage(CameraImage image) async { if (_isProcessing) return; _isProcessing = true;

    try {
      final inputImage = _prepareInputImage(image);
      final recognizedText = await _textRecognizer.processImage(inputImage);
    
      _addToTextBuffer(recognizedText.text);
    
      if (DateTime.now().difference(_lastProcessTime).inSeconds >= 1) {
        await _processTextBuffer();
        _lastProcessTime = DateTime.now();
      }
    } catch (e) {
      print('Error processing image: $e');
    } finally {
      _isProcessing = false;
    }
    

    }

    InputImage _prepareInputImage(CameraImage image) { final WriteBuffer allBytes = WriteBuffer(); for (final Plane plane in image.planes) { allBytes.putUint8List(plane.bytes); } final bytes = allBytes.done().buffer.asUint8List();

    final imageSize = Size(image.width.toDouble(), image.height.toDouble());
    const imageRotation = InputImageRotation.rotation0deg;
    const inputImageFormat = InputImageFormat.yuv420;
    
    final inputImageData = InputImageMetadata(
      size: imageSize,
      rotation: imageRotation,
      format: inputImageFormat,
      bytesPerRow: image.planes[0].bytesPerRow,
    );
    
    return InputImage.fromBytes(
      bytes: bytes,
      metadata: inputImageData,
    );
    

    }

    void _addToTextBuffer(String text) { _textBuffer.addAll(text.split(RegExp(r'[,\s]+'))); _textBuffer = _textBuffer .map((word) => word.trim().toLowerCase()) .where((word) => word.isNotEmpty) .toList(); }

    Future _processTextBuffer() async { if (_textBuffer.isEmpty) return;

    final newIngredients = _textBuffer.toSet().difference(_detectedIngredients);
    if (newIngredients.isNotEmpty) {
      final details = await DatabaseHelper.instance
          .fetchIngredientsDetails(newIngredients.toList());
      setState(() {
        for (final detail in details) {
          final name = detail['ingredient_name'] as String;
          _detectedIngredients.add(name.toLowerCase());
          _ingredientDetails[name.toLowerCase()] = detail;
        }
    
        // Check for generic sulfates or sulfonates
        for (final ingredient in newIngredients) {
          if (!_detectedIngredients.contains(ingredient.toLowerCase()) &&
              (ingredient.toLowerCase().contains('sulfate') ||
                  ingredient.toLowerCase().contains('sulfonate'))) {
            _genericSulfateOrSulfonateDetected = true;
            break;
          }
        }
      });
    }
    
    _textBuffer.clear();
    

    }

    @override Widget build(BuildContext context) { if (!_isCameraInitialized) { return const Center(child: CircularProgressIndicator()); } final theme = Theme.of(context);

    return Scaffold(
      appBar: AppBar(
        title: Text(
          "Ingredient Scan",
          style: theme.textTheme.headlineSmall?.copyWith(
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
      body: Column(
        children: [
          Expanded(flex: 3, child: _buildCameraPreview()),
          Expanded(flex: 2, child: _buildIngredientList()),
        ],
      ),
    );
    

    }

    Widget _buildCameraPreview() { return ClipRRect( borderRadius: BorderRadius.circular(16), child: AspectRatio( aspectRatio: 3 / 4, child: CameraPreview(_cameraController), ), ); }

    Widget _buildIngredientList() { return ListView( padding: const EdgeInsets.all(16), children: [ Text('Detected Ingredients:', style: Theme.of(context).textTheme.titleLarge), const SizedBox(height: 8), ..._detectedIngredients.map((ingredient) => ListTile( title: Text(ingredient), )), ElevatedButton( onPressed: () { Navigator.pop(context, { 'ingredients': _detectedIngredients.toList(), 'genericSulfateOrSulfonateDetected': _genericSulfateOrSulfonateDetected, }); }, child: const Text('Done'), ), ], ); } }

    import 'dart:io'; import 'package:curlify/src/services/ad_helper.dart'; import 'package:flutter/material.dart'; import 'package:google_mlkit_text_recognition/google_mlkit_text_recognition.dart'; import 'package:image_picker/image_picker.dart'; import '../services/database_service.dart'; import 'result_page.dart';

    class RecognitionPage extends StatefulWidget { const RecognitionPage({super.key, required this.xFile});

    final XFile xFile;

    @override State createState() => _RecognitionPageState(); }

    class _RecognitionPageState extends State { final InterstitialAdManager _interstitialAdManager = InterstitialAdManager(); bool _isScanning = false; String _scannedText = ''; final bool _isList = false;

    Future _getRecognizedText() async { if (!mounted) return;

    setState(() => _isScanning = true);
    
    try {
      final inputImage = InputImage.fromFilePath(widget.xFile.path);
      final textRecognizer =
          TextRecognizer(script: TextRecognitionScript.latin);
    
      final RecognizedText recognizedText =
          await textRecognizer.processImage(inputImage);
    
      if (!mounted) return;
    
      setState(() {
        _scannedText = recognizedText.blocks
            .expand((block) => block.lines)
            .map((line) => line.text)
            .join(_isList ? '\n' : ' ');
      });
    
      textRecognizer.close();
      await _processScannedText();
    } catch (e) {
      _showErrorSnackBar('Error recognizing text: $e');
    } finally {
      if (mounted) setState(() => _isScanning = false);
    }
    

    }

    Future _processScannedText() async { if (!mounted) return;

    String cleanedText = _scannedText.replaceAll(
        RegExp(r'[0-9]|Image ID:|www\.\S+|\s{2,}|QUESTIONS?.*'), '');
    
    final ingredientsText = cleanedText
        .split(',')
        .map((s) => s.trim())
        .where((s) => s.isNotEmpty)
        .toList();
    
    if (ingredientsText.isEmpty) {
      _showErrorSnackBar('No valid ingredients detected, please try again.');
      return;
    }
    
    try {
      final details = await DatabaseHelper.instance
          .fetchIngredientsDetails(ingredientsText);
      if (!mounted) return;
    
      await Navigator.pushReplacement(
        context,
        MaterialPageRoute(
          builder: (context) => ResultPage(
            genericSulfateOrSulfonateDetected: false,
            ingredientsDetails: details,
            adManager: _interstitialAdManager,
          ),
        ),
      );
    } catch (e) {
      _showErrorSnackBar('Error fetching ingredient details: $e');
    }
    

    }

    void _showErrorSnackBar(String message) { ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text(message)), ); }

    @override Widget build(BuildContext context) { final theme = Theme.of(context); return Scaffold( appBar: AppBar( title: Text( "Selected Image", style: theme.textTheme.headlineSmall?.copyWith( fontWeight: FontWeight.bold, ), ), ), floatingActionButton: FloatingActionButton.extended( onPressed: _getRecognizedText, label: const Text('Scan'), icon: const Icon(Icons.check_outlined), ), body: SingleChildScrollView( padding: const EdgeInsets.all(12.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ ClipRRect( borderRadius: BorderRadius.circular(12.0), child: ConstrainedBox( constraints: const BoxConstraints(maxHeight: 500), child: Image.file( File(widget.xFile.path), width: double.infinity, fit: BoxFit.contain, ), ), ), if (_isScanning) const Center(child: CircularProgressIndicator()), ], ), ), ); } }

    import 'package:flutter/material.dart'; import 'package:typicons_flutter/typicons_flutter.dart'; import '../services/ad_helper.dart';

    class ResultPage extends StatefulWidget { final List<Map<String, dynamic>> ingredientsDetails; final InterstitialAdManager adManager; final bool genericSulfateOrSulfonateDetected;

    const ResultPage({ super.key, required this.ingredientsDetails, required this.adManager, required this.genericSulfateOrSulfonateDetected, });

    @override ResultPageState createState() => ResultPageState(); }

    class ResultPageState extends State { @override Widget build(BuildContext context) { final hasCationicIngredient = widget.ingredientsDetails.any((item) => item['is_cationic'] == 1); final hasDimethicone = widget.ingredientsDetails.any( (item) => _isDimethicone(_capitalizeWords(item['ingredient_name']))); final hasRelationship = hasCationicIngredient && hasDimethicone;

    final List<Map<String, dynamic>> relationshipIngredients = hasRelationship
        ? widget.ingredientsDetails
            .where((ingredient) =>
                ingredient['is_cationic'] == 1 ||
                _isDimethicone(_capitalizeWords(ingredient['ingredient_name'])))
            .toList()
        : [];
    
    final List<Map<String, dynamic>> normalIngredients = hasRelationship
        ? widget.ingredientsDetails
            .where((ingredient) =>
                ingredient['is_cationic'] != 1 &&
                !_isDimethicone(
                    _capitalizeWords(ingredient['ingredient_name'])))
            .toList()
        : widget.ingredientsDetails;
    
    final sortedNormalIngredients = _sortIngredients(normalIngredients);
    final overallStatus =
        _getOverallStatus(widget.ingredientsDetails, hasRelationship);
    
    return PopScope(
      canPop: false,
      onPopInvoked: (didPop) {
        if (didPop) return;
        _handleBackNavigation();
      },
      child: Scaffold(
        body: SafeArea(
          child: Column(
            children: [
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: Row(
                  children: [
                    IconButton(
                      icon: const Icon(Icons.arrow_back),
                      onPressed: _handleBackNavigation,
                    ),
                    const Expanded(
                      child: Text(
                        "Results",
                        style: TextStyle(
                          fontSize: 20,
                          fontWeight: FontWeight.bold,
                        ),
                        textAlign: TextAlign.center,
                      ),
                    ),
                    const SizedBox(width: 48), // To balance the back button
                  ],
                ),
              ),
              _buildStatusBanner(overallStatus),
              Expanded(
                child: ListView(
                  children: [
                    if (hasRelationship)
                      _buildRelationshipSection(
                          context, relationshipIngredients),
                    ..._buildIngredientList(context, sortedNormalIngredients),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
    

    }

    void _handleBackNavigation() { widget.adManager.showAdIfLoaded( context, () { if (!mounted) return; Navigator.of(context) .pop(); // This will now happen after the ad is closed }, ); }

    Widget _buildStatusBanner(String status) { Color color; IconData icon; switch (status) { case 'Not Approved': color = Colors.red[400]!; icon = Typicons.times; break; case 'Approved with Caution': color = Colors.orange[300]!; icon = Typicons.warning; break; case 'Approved': color = Colors.green[400]!; icon = Typicons.tick; break; default: color = Colors.grey; icon = Icons.help; }

    return Container(
      color: color,
      padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 16),
      child: Row(
        children: [
          Icon(icon, color: Colors.white),
          const SizedBox(width: 8),
          Text(
            status,
            style: const TextStyle(
                color: Colors.white, fontWeight: FontWeight.bold),
          ),
        ],
      ),
    );
    

    }

    List _buildIngredientList( BuildContext context, List<Map<String, dynamic>> sortedIngredients) { List widgets = []; String currentStatus = '';

    // Add generic sulfate/sulfonate if detected
    if (widget.genericSulfateOrSulfonateDetected) {
      sortedIngredients.insert(0, {
        'ingredient_name': 'Generic Sulfate / Sulfonate',
        'ingredient_type': 'Sulfate/Sulfonate',
        'cg_approval_status': 'No',
        'notes':
            'Generic sulfate or sulfonate detected. These are typically not approved for curly hair care.',
      });
    }
    
    for (var ingredient in sortedIngredients) {
      if (ingredient['cg_approval_status'] != currentStatus) {
        currentStatus = ingredient['cg_approval_status'];
        final ingredientsInCategory = sortedIngredients
            .where((i) => i['cg_approval_status'] == currentStatus)
            .toList();
    
        if (ingredientsInCategory.isNotEmpty) {
          if (widgets.isNotEmpty) {
            widgets.add(_buildCustomDivider());
          }
          widgets.add(
            Padding(
              padding: const EdgeInsets.fromLTRB(16, 8, 16, 0),
              child: Text(
                _getStatusText(currentStatus),
                style: const TextStyle(fontWeight: FontWeight.bold),
              ),
            ),
          );
        }
      }
    
      widgets.add(_buildIngredientTile(context, ingredient));
    }
    
    return widgets;
    

    }

    Widget _buildCustomDivider() { return Padding( padding: const EdgeInsets.symmetric(horizontal: 16.0), child: Container( height: 1, color: Colors.grey[300], ), ); }

    Widget _buildRelationshipSection( BuildContext context, List<Map<String, dynamic>> ingredients) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Padding( padding: EdgeInsets.all(16.0), child: Text( 'The following ingredients are not approved due to their relationship, which may cause build-up', style: TextStyle(fontWeight: FontWeight.bold), ), ), Container( margin: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0), decoration: BoxDecoration( color: Colors.transparent, borderRadius: BorderRadius.circular(12), ), child: Card( margin: EdgeInsets.zero, elevation: 0, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(12), side: const BorderSide( color: Color.fromARGB(255, 241, 107, 107), width: 2, )), color: Colors.transparent, child: Padding( padding: const EdgeInsets.all(16), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ ...ingredients.map((ingredient) => _buildIngredientTile(context, ingredient)), ], ), ), ), ), ], ); }

    Widget _buildIngredientTile( BuildContext context, Map<String, dynamic> ingredient) { return ListTile( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(16.0), ), contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 0), leading: Container( width: 50, height: 50, decoration: BoxDecoration( color: _getColorForIngredientType(ingredient['ingredient_type']), borderRadius: BorderRadius.circular(8), ), alignment: Alignment.center, child: Text( _getAbbreviationForType(ingredient['ingredient_type']), style: const TextStyle( color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold), ), ), title: Text(_capitalizeWords( ingredient['ingredient_name'] ?? 'Unknown Ingredient')), subtitle: Text(ingredient['ingredient_type'] ?? 'Unknown Type'), onTap: () => _showNotesDialog(context, ingredient), ); }

    bool _isDimethicone(String? name) { if (name == null) return false; String lowercaseName = name.toLowerCase(); return lowercaseName == 'dimethicone' || lowercaseName == 'dimethicone copolyol'; }

    List<Map<String, dynamic>> _sortIngredients( List<Map<String, dynamic>> ingredients) { return List<Map<String, dynamic>>.from(ingredients) ..sort((a, b) { int statusOrder(String? status) { switch (status) { case 'No': return 0; case 'Caution': return 1; case 'Yes': return 2; default: return 3; } }

        return statusOrder(a['cg_approval_status'])
            .compareTo(statusOrder(b['cg_approval_status']));
      });
    

    }

    String _getOverallStatus( List<Map<String, dynamic>> ingredients, bool hasRelationship) { if (hasRelationship || widget.genericSulfateOrSulfonateDetected) { return 'Not Approved'; } else if (ingredients.any((i) => i['cg_approval_status'] == 'No')) { return 'Not Approved'; } else if (ingredients.any((i) => i['cg_approval_status'] == 'Caution')) { return 'Approved with Caution'; } else { return 'Approved'; } }

    String _getAbbreviationForType(String? type) { if (type == null) return "??"; List words = type.split(' '); if (words.length == 1) { return type.substring(0, type.length >= 2 ? 2 : 1); } return (words[0][0] + words[1][0]); }

    Color _getColorForIngredientType(String? type) { switch (type?.toLowerCase()) { case 'solvent': return Colors.blue[300]!; case 'oil': return Colors.green[300]!; case 'humectant': return Colors.purple[300]!; case 'emollient': return Colors.orange[300]!; case 'fragrance': return Colors.pink[300]!; case 'emulsifier': return Colors.teal[300]!; case 'butter': return Colors.yellow[400]!; case 'occlusive agent': return Colors.brown[400]!; case 'preservative': return Colors.red[300]!; case 'extract': return Colors.lightGreen[300]!; case 'protein': return Colors.deepOrange[300]!; case 'polyquat': return Colors.cyan[300]!; case 'surfactant': return Colors.indigo[300]!; case 'vitamin': return Colors.amber[200]!; case 'film former': return Colors.lime[200]!; case 'sulfate': return Colors.deepPurple[300]!; default: return Colors.grey[400]!; } }

    void _showNotesDialog(BuildContext context, Map<String, dynamic> ingredient) { showDialog( context: context, builder: (context) { return AlertDialog( title: Text(_capitalizeWords(ingredient['ingredient_name'])), content: Text( ingredient['notes'] ?? 'No additional information available.', ), actions: [ TextButton( onPressed: () => Navigator.of(context).pop(), child: const Text('OK'), ), ], ); }, ); }

    String _capitalizeWords(String text) { return text.split(' ').map((word) { if (word.startsWith('(') && word.length > 1) { return '(word[1].toUpperCase(){word[1].toUpperCase()}{word.substring(2).toLowerCase()}'; } return word.isNotEmpty ? word[0].toUpperCase() + word.substring(1).toLowerCase() : word; }).join(' '); }

    String _getStatusText(String status) { switch (status) { case 'No': return 'Not Approved'; case 'Caution': return 'Approved with Caution'; case 'Yes': return 'Approved'; default: return 'Other Ingredients'; } } }

    import 'dart:io'; import 'package:curlify/src/pages/ad_overlay.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:google_mobile_ads/google_mobile_ads.dart';

    class AdHelper { static String get interstitialAdUnitId { if (Platform.isAndroid) { return 'ca-app-pub-3940256099942544/1033173712'; // Test ad unit ID for Android } else if (Platform.isIOS) { return 'ca-app-pub-3940256099942544/4411468910'; // Test ad unit ID for iOS } else { throw UnsupportedError('Unsupported platform'); } }

    static Future initAds() async { await MobileAds.instance.initialize(); } }

    class InterstitialAdManager { InterstitialAd? _interstitialAd; bool _isAdLoaded = false; bool _isAdLoading = false;

    void loadAd() { if (_isAdLoading) return; _isAdLoading = true;

    InterstitialAd.load(
      adUnitId: AdHelper.interstitialAdUnitId,
      request: const AdRequest(),
      adLoadCallback: InterstitialAdLoadCallback(
        onAdLoaded: (ad) {
          _interstitialAd = ad;
          _isAdLoaded = true;
          _isAdLoading = false;
          print('Interstitial ad loaded successfully.');
        },
        onAdFailedToLoad: (error) {
          print('InterstitialAd failed to load: $error');
          _isAdLoading = false;
          _isAdLoaded = false;
          _interstitialAd = null;
          Future.delayed(const Duration(minutes: 1), loadAd);
        },
      ),
    );
    

    }

    Future showAdIfLoaded( BuildContext context, VoidCallback onAdClosed) async { if (_isAdLoaded && _interstitialAd != null) { // Show overlay showDialog( context: context, barrierDismissible: false, builder: (BuildContext context) => AdOverlay(onAdClosed: onAdClosed), );

      _interstitialAd!.fullScreenContentCallback = FullScreenContentCallback(
        onAdShowedFullScreenContent: (InterstitialAd ad) {
          SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersive);
        },
        onAdDismissedFullScreenContent: (ad) {
          SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
          ad.dispose();
          _isAdLoaded = false;
          _interstitialAd = null;
          Navigator.of(context).pop(); // Dismiss overlay
          onAdClosed();
          loadAd(); // Load the next ad
        },
        onAdFailedToShowFullScreenContent: (ad, error) {
          print('Failed to show ad: $error');
          ad.dispose();
          _isAdLoaded = false;
          _interstitialAd = null;
          Navigator.of(context).pop(); // Dismiss overlay
          onAdClosed();
          loadAd();
        },
      );
      await _interstitialAd!.show();
    } else {
      print('Interstitial ad not ready yet. Proceeding without showing ad.');
      onAdClosed();
      loadAd();
    }
    

    }

    void dispose() { _interstitialAd?.dispose(); } }

    import 'package:sqflite/sqflite.dart'; import 'package:path/path.dart'; import 'package:flutter/services.dart' show rootBundle; import 'package:csv/csv.dart';

    class DatabaseHelper { static final DatabaseHelper instance = DatabaseHelper._init(); static Database? _database;

    DatabaseHelper._init();

    Future get database async { if (_database != null) return _database!; _database = await _initDB('ingredients.db'); return _database!; }

    Future _initDB(String filePath) async { final dbPath = await getDatabasesPath(); final path = join(dbPath, filePath);

    return await openDatabase(
      path,
      version: 11,
      onCreate: _createDB,
      onUpgrade: _onUpgrade,
    );
    

    }

    Future _createDB(Database db, int version) async { await db.execute(''' CREATE TABLE ingredients ( id INTEGER PRIMARY KEY AUTOINCREMENT, ingredient_name TEXT NOT NULL UNIQUE, ingredient_type TEXT NOT NULL, cg_approval_status TEXT, notes TEXT, is_cationic INTEGER NOT NULL ) ''');

    await db.execute('''
      CREATE TABLE ingredient_aliases (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        ingredient_id INTEGER NOT NULL,
        alias TEXT NOT NULL UNIQUE,
        FOREIGN KEY (ingredient_id) REFERENCES ingredients (id)
      )
    ''');
    
    await db.execute(
        'CREATE INDEX idx_ingredient_name ON ingredients (ingredient_name)');
    await db.execute(
        'CREATE INDEX idx_ingredient_alias ON ingredient_aliases (alias)');
    
    await _importCSVData(db);
    

    }

    Future _onUpgrade(Database db, int oldVersion, int newVersion) async { if (oldVersion < newVersion) { // Drop old tables await db.execute('DROP TABLE IF EXISTS ingredient_aliases'); await db.execute('DROP TABLE IF EXISTS ingredients');

      // Recreate tables
      await _createDB(db, newVersion);
    }
    

    }

    Future _importCSVData(Database db) async { try { final String csvData = await rootBundle.loadString('assets/ingredients.csv'); final List<List> csvTable = const CsvToListConverter().convert(csvData);

      await db.transaction((txn) async {
        for (var i = 1; i < csvTable.length; i++) {
          final row = csvTable[i];
          final int id = await txn.rawInsert('''
            INSERT OR REPLACE INTO ingredients 
            (ingredient_name, ingredient_type, cg_approval_status, notes, is_cationic)
            VALUES (?, ?, ?, ?, ?)
          ''', [
            row[0],
            row[1],
            row[2],
            row[3],
            row[4] == 'true' ? 1 : 0,
          ]);
    
          // Add alias if it exists
          if (row.length > 5 && row[5] != null && row[5].isNotEmpty) {
            await txn.rawInsert('''
              INSERT OR REPLACE INTO ingredient_aliases
              (ingredient_id, alias)
              VALUES (?, ?)
            ''', [id, row[5]]);
          }
        }
      });
    } catch (e) {
      print('Error importing CSV data: $e');
    }
    

    }

    Future<List<Map<String, dynamic>>> fetchIngredientsDetails( List ingredients) async { final db = await database; final lowercasedIngredients = ingredients.map((e) => e.toLowerCase()).toList();

    try {
      final List<Map<String, dynamic>> results = await db.rawQuery('''
      SELECT DISTINCT i.*
      FROM ingredients i
      WHERE LOWER(i.ingredient_name) IN (${List.filled(lowercasedIngredients.length, '?').join(',')})
      OR i.id IN (
        SELECT a.ingredient_id
        FROM ingredient_aliases a
        WHERE LOWER(a.alias) IN (${List.filled(lowercasedIngredients.length, '?').join(',')})
      )
    ''', [...lowercasedIngredients, ...lowercasedIngredients]);
      return results;
    } catch (e) {
      print('Error fetching ingredient details: $e');
      return [];
    }
    

    }

    Future closeDatabase() async { final db = await instance.database; await db.close(); _database = null; }

    Future resetDatabase() async { final db = await instance.database; await db.transaction((txn) async { await txn.delete('ingredients'); await txn.delete('ingredient_aliases'); await _importCSVData(db); }); } }

    Please adjust my code for the following changes:

    2 dollars for ad removal, buyable via google play store, with restore purchase, the first click on startup and every second click shows implemented advert Settings page for Design (system, dark, light), Upgrade to pro, terms of service (nutzungsbedingungen), Rate App Onboarding screen with explanation Info button and scanning tutorial and pretty animations (User should slowly scan for the ocr to pick up most of the items) Scanning Page: Explanation similar to onboarding screen as a disclaimer, floating done button that is sticky, improved design for found items (tile based like in results)

    BUG:
Please enter one ingredient banner not disappearing and looking ugly

  2. Assistant

    Sure! Let's update your Flutter app according to your requests. This will involve several steps:

    1. Implement In-App Purchases for Ad Removal
    2. Create a Settings Page
    3. Add an Onboarding Screen with Tutorial
    4. Improve the Scanning Page
    5. Fix the SnackBar Bug

    I'll provide code snippets and explanations for each step. Let's get started!


    1. Implement In-App Purchases for Ad Removal

    We'll use the in_app_purchase package to handle in-app purchases. We'll create a PurchaseManager class to manage purchases and integrate it into your app.

    Step 1: Add Dependencies

    Add the following dependencies to your pubspec.yaml:

    dependencies:
      flutter:
        sdk: flutter
      google_mobile_ads: ^2.3.0
      in_app_purchase: ^3.0.7
      shared_preferences: ^2.0.15
      # Add other dependencies as needed
    

    Step 2: Create PurchaseManager Class

    Create a new file purchase_manager.dart in your services directory:

    // services/purchase_manager.dart
    import 'package:flutter/material.dart';
    import 'package:in_app_purchase/in_app_purchase.dart';
    import 'package:shared_preferences/shared_preferences.dart';
    
    class PurchaseManager {
      static const String _productId = 'remove_ads';
      static final PurchaseManager _instance = PurchaseManager._internal();
      final InAppPurchase _inAppPurchase = InAppPurchase.instance;
      bool _isAvailable = false;
      bool _isPurchased = false;
      List<ProductDetails> _products = [];
      final ValueNotifier<bool> purchaseNotifier = ValueNotifier<bool>(false);
    
      factory PurchaseManager() {
        return _instance;
      }
    
      PurchaseManager._internal() {
        _initialize();
      }
    
      Future<void> _initialize() async {
        _isAvailable = await _inAppPurchase.isAvailable();
    
        if (_isAvailable) {
          // Retrieve product details
          ProductDetailsResponse response = await _inAppPurchase.queryProductDetails({_productId});
          _products = response.productDetails;
    
          // Restore past purchases
          _inAppPurchase.restorePurchases();
    
          // Listen to purchase updates
          _inAppPurchase.purchaseStream.listen(_listenToPurchaseUpdated);
        }
    
        // Check if the user has purchased the product before (from local storage)
        SharedPreferences prefs = await SharedPreferences.getInstance();
        _isPurchased = prefs.getBool('isPurchased') ?? false;
        purchaseNotifier.value = _isPurchased;
      }
    
      Future<void> buyRemoveAds() async {
        if (_products.isNotEmpty) {
          final PurchaseParam purchaseParam = PurchaseParam(productDetails: _products.first);
          await _inAppPurchase.buyNonConsumable(purchaseParam: purchaseParam);
        }
      }
    
      Future<void> restorePurchases() async {
        await _inAppPurchase.restorePurchases();
      }
    
      void _listenToPurchaseUpdated(List<PurchaseDetails> purchaseDetailsList) async {
        for (var purchaseDetails in purchaseDetailsList) {
          if (purchaseDetails.productID == _productId && purchaseDetails.status == PurchaseStatus.purchased) {
            // Verify the purchase here if necessary
            _deliverProduct(purchaseDetails);
          } else if (purchaseDetails.status == PurchaseStatus.restored) {
            _deliverProduct(purchaseDetails);
          } else if (purchaseDetails.status == PurchaseStatus.error) {
            // Handle error
          }
    
          if (purchaseDetails.pendingCompletePurchase) {
            await _inAppPurchase.completePurchase(purchaseDetails);
          }
        }
      }
    
      void _deliverProduct(PurchaseDetails purchaseDetails) async {
        _isPurchased = true;
        purchaseNotifier.value = true;
        SharedPreferences prefs = await SharedPreferences.getInstance();
        await prefs.setBool('isPurchased', true);
      }
    
      bool get isPurchased => _isPurchased;
    }
    

    Explanation:

    • The PurchaseManager class handles in-app purchases and keeps track of whether the user has purchased the "Remove Ads" product.
    • It uses a ValueNotifier to notify the app of changes in the purchase status.
    • Purchases are stored locally using SharedPreferences.

    Step 3: Modify InterstitialAdManager

    Update your InterstitialAdManager to check if ads should be displayed:

    // services/ad_helper.dart (update InterstitialAdManager class)
    import 'package:flutter/material.dart';
    import 'purchase_manager.dart';  // Import the purchase manager
    
    class InterstitialAdManager {
      InterstitialAd? _interstitialAd;
      bool _isAdLoaded = false;
      bool _isAdLoading = false;
      int _adDisplayCount = 0;
    
      final PurchaseManager _purchaseManager = PurchaseManager();
    
      void loadAd() {
        if (_isAdLoading || _purchaseManager.isPurchased) return;
        _isAdLoading = true;
    
        // Remainder of your loadAd method...
      }
    
      Future<void> showAdIfLoaded(BuildContext context, VoidCallback onAdClosed) async {
        if (_purchaseManager.isPurchased) {
          onAdClosed();
          return;
        }
    
        _adDisplayCount++;
        if (_adDisplayCount % 2 != 0) {
          onAdClosed();
          return;
        }
    
        // Remainder of your showAdIfLoaded method...
      }
    
      // Remainder of your class...
    }
    

    Explanation:

    • The InterstitialAdManager now checks if the user has purchased ad removal before loading or showing ads.
    • Ads are shown on the first click and every second click thereafter, as per your requirement.
    • We keep track of the number of times an ad could be displayed using _adDisplayCount.

    Step 4: Update Your Main App

    In your main.dart or wherever you're initializing your app, initialize the PurchaseManager:

    void main() async {
      WidgetsFlutterBinding.ensureInitialized();
      await AdHelper.initAds();
      PurchaseManager(); // Initialize the purchase manager
      runApp(MyApp());
    }
    

    Step 5: Update the UI to Reflect Ad Removal

    Whenever you create an instance of InterstitialAdManager, make sure to pass the PurchaseManager or check if ads should be shown.

    2. Create a Settings Page

    Create a settings page with options to change the theme, upgrade to pro, view terms of service, and rate the app.

    Step 1: Create the Settings Page

    Create settings_page.dart:

    // pages/settings_page.dart
    import 'package:flutter/material.dart';
    import 'package:shared_preferences/shared_preferences.dart';
    import '../services/purchase_manager.dart';
    import 'package:url_launcher/url_launcher.dart';
    
    class SettingsPage extends StatefulWidget {
      const SettingsPage({super.key});
    
      @override
      SettingsPageState createState() => SettingsPageState();
    }
    
    class SettingsPageState extends State<SettingsPage> {
      ThemeMode _themeMode = ThemeMode.system;
      final PurchaseManager _purchaseManager = PurchaseManager();
    
      @override
      void initState() {
        super.initState();
        _loadThemeMode();
      }
    
      Future<void> _loadThemeMode() async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        String? theme = prefs.getString('themeMode');
        setState(() {
          switch (theme) {
            case 'light':
              _themeMode = ThemeMode.light;
              break;
            case 'dark':
              _themeMode = ThemeMode.dark;
              break;
            default:
              _themeMode = ThemeMode.system;
          }
        });
      }
    
      Future<void> _changeThemeMode(ThemeMode mode) async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        await prefs.setString('themeMode', mode.toString().split('.')[1]);
        setState(() {
          _themeMode = mode;
        });
      }
    
      _launchURL(String url) async {
        Uri uri = Uri.parse(url);
        if (await canLaunchUrl(uri)) {
          await launchUrl(uri);
        } else {
          // Could not launch URL
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: const Text('Settings'),
          ),
          body: ListView(
            children: [
              ListTile(
                title: const Text('Design'),
                subtitle: const Text('Choose your preferred theme'),
                trailing: DropdownButton<ThemeMode>(
                  value: _themeMode,
                  items: const [
                    DropdownMenuItem(
                      value: ThemeMode.system,
                      child: Text('System'),
                    ),
                    DropdownMenuItem(
                      value: ThemeMode.light,
                      child: Text('Light'),
                    ),
                    DropdownMenuItem(
                      value: ThemeMode.dark,
                      child: Text('Dark'),
                    ),
                  ],
                  onChanged: (ThemeMode? mode) {
                    if (mode != null) {
                      _changeThemeMode(mode);
                      // Notify the app to update the theme
                      MyApp.of(context)?.setThemeMode(mode);
                    }
                  },
                ),
              ),
              ListTile(
                title: const Text('Upgrade to Pro'),
                subtitle: const Text('Remove ads by upgrading'),
                trailing: ValueListenableBuilder<bool>(
                  valueListenable: _purchaseManager.purchaseNotifier,
                  builder: (context, isPurchased, child) {
                    return isPurchased
                        ? const Text('Purchased', style: TextStyle(color: Colors.green))
                        : ElevatedButton(
                            onPressed: () {
                              _purchaseManager.buyRemoveAds();
                            },
                            child: const Text('Buy (\$2.00)'),
                          );
                  },
                ),
              ),
              ListTile(
                title: const Text('Restore Purchase'),
                onTap: () {
                  _purchaseManager.restorePurchases();
                },
              ),
              ListTile(
                title: const Text('Terms of Service'),
                onTap: () {
                  _launchURL('https://yourapp.com/terms');
                },
              ),
              ListTile(
                title: const Text('Rate App'),
                onTap: () {
                  _launchURL('https://play.google.com/store/apps/details?id=your_app_id');
                },
              ),
            ],
          ),
        );
      }
    }
    
    class MyApp extends StatefulWidget {
      // Your main app widget
    
      static MyAppState? of(BuildContext context) =>
          context.findAncestorStateOfType<MyAppState>();
    
      @override
      MyAppState createState() => MyAppState();
    }
    
    class MyAppState extends State<MyApp> {
      ThemeMode _themeMode = ThemeMode.system;
    
      void setThemeMode(ThemeMode mode) {
        setState(() {
          _themeMode = mode;
        });
      }
    
      // Rest of your MyApp code...
    }
    

    Explanation:

    • The settings page allows the user to select the theme, upgrade to pro, restore purchases, view terms of service, and rate the app.
    • The theme mode is saved in SharedPreferences.
    • The MyApp class is modified to allow changing the theme dynamically.

    Step 2: Modify Your main.dart to Use MyApp

    Ensure your main.dart uses the MyApp class:

    void main() async {
      // ...
      runApp(MyApp());
    }
    
    class MyApp extends StatefulWidget {
      // ...
    }
    
    class MyAppState extends State<MyApp> {
      ThemeMode _themeMode = ThemeMode.system;
    
      @override
      void initState() {
        super.initState();
        _loadThemeMode();
      }
    
      Future<void> _loadThemeMode() async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        String? theme = prefs.getString('themeMode');
        setState(() {
          switch (theme) {
            case 'light':
              _themeMode = ThemeMode.light;
              break;
            case 'dark':
              _themeMode = ThemeMode.dark;
              break;
            default:
              _themeMode = ThemeMode.system;
          }
        });
      }
    
      void setThemeMode(ThemeMode mode) {
        setState(() {
          _themeMode = mode;
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Curlify',
          themeMode: _themeMode,
          // Define your themes here
          theme: ThemeData.light(),
          darkTheme: ThemeData.dark(),
          home: MainPage(),
        );
      }
    }
    

    Step 3: Add Navigation to Settings Page

    In your main page or wherever appropriate, add a way to navigate to the settings page:

    // In MainPage's AppBar
    actions: [
      IconButton(
        icon: Icon(Icons.settings),
        onPressed: () {
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => const SettingsPage()),
          );
        },
      ),
    ],
    

    3. Add an Onboarding Screen with Tutorial

    We'll add an onboarding screen that shows up on the first launch.

    Step 1: Add the introduction_screen Package

    Add the introduction_screen package to your pubspec.yaml:

    dependencies:
      introduction_screen: ^3.0.2
    

    Step 2: Create the Onboarding Screen

    Create onboarding_page.dart:

    // pages/onboarding_page.dart
    import 'package:flutter/material.dart';
    import 'package:shared_preferences/shared_preferences.dart';
    import 'package:introduction_screen/introduction_screen.dart';
    
    class OnboardingPage extends StatelessWidget {
      const OnboardingPage({super.key});
    
      void _onIntroEnd(context) async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        await prefs.setBool('onboardingComplete', true);
        Navigator.of(context).pushReplacementNamed('/main');
      }
    
      @override
      Widget build(BuildContext context) {
        const bodyStyle = TextStyle(fontSize: 16.0);
        return IntroductionScreen(
          pages: [
            PageViewModel(
              title: "Welcome to Curlify",
              body: "Your personal hair care assistant.",
              image: Center(child: Image.asset("assets/images/onboarding1.png", height: 175.0)),
              decoration: const PageDecoration(
                bodyTextStyle: bodyStyle,
              ),
            ),
            PageViewModel(
              title: "Scan Ingredients",
              body: "Easily scan product ingredients and get instant feedback.",
              image: Center(child: Image.asset("assets/images/onboarding2.png", height: 175.0)),
              decoration: const PageDecoration(
                bodyTextStyle: bodyStyle,
              ),
            ),
            PageViewModel(
              title: "Get Recommendations",
              body: "Receive personalized recommendations based on your scans.",
              image: Center(child: Image.asset("assets/images/onboarding3.png", height: 175.0)),
              decoration: const PageDecoration(
                bodyTextStyle: bodyStyle,
              ),
            ),
          ],
          onDone: () => _onIntroEnd(context),
          onSkip: () => _onIntroEnd(context), // You can choose to disable skip if you want
          showSkipButton: true,
          skip: const Text('Skip'),
          next: const Icon(Icons.arrow_forward),
          done: const Text('Done', style: TextStyle(fontWeight: FontWeight.w600)),
          dotsDecorator: const DotsDecorator(
            activeColor: Colors.deepPurple,
          ),
        );
      }
    }
    

    Note: Replace the images and text with content relevant to your app.

    Step 3: Update Your main.dart to Show Onboarding Screen

    Modify your main.dart:

    // In main.dart
    void main() async {
      WidgetsFlutterBinding.ensureInitialized();
      await AdHelper.initAds();
      PurchaseManager();
      runApp(MyApp());
    }
    
    class MyApp extends StatefulWidget {
      // ...
    
      @override
      MyAppState createState() => MyAppState();
    }
    
    class MyAppState extends State<MyApp> {
      // ...
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Curlify',
          // ...
          initialRoute: '/',
          routes: {
            '/': (context) => SplashScreen(), // Show a splash screen while loading
            '/onboarding': (context) => const OnboardingPage(),
            '/main': (context) => const MainPage(),
          },
        );
      }
    }
    
    class SplashScreen extends StatelessWidget {
      // This widget checks if onboarding is complete and navigates accordingly
      @override
      Widget build(BuildContext context) {
        Future.delayed(Duration.zero, () async {
          SharedPreferences prefs = await SharedPreferences.getInstance();
          bool onboardingComplete = prefs.getBool('onboardingComplete') ?? false;
          if (onboardingComplete) {
            Navigator.of(context).pushReplacementNamed('/main');
          } else {
            Navigator.of(context).pushReplacementNamed('/onboarding');
          }
        });
    
        return Scaffold(
          body: Center(
            child: CircularProgressIndicator(),
          ),
        );
      }
    }
    

    4. Improve the Scanning Page

    We'll add an explanation and improve the UI on the scanning page.

    Step 1: Add Explanation to Scanning Page

    Modify your LiveScanPage to include an explanation at the top and a floating 'Done' button.

    // pages/live_scan_page.dart (modify build method)
    @override
    Widget build(BuildContext context) {
      if (!_isCameraInitialized) {
        return const Center(child: CircularProgressIndicator());
      }
      final theme = Theme.of(context);
    
      return Scaffold(
        appBar: AppBar(
          title: Text(
            "Ingredient Scan",
            style: theme.textTheme.headlineSmall?.copyWith(
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
        floatingActionButton: FloatingActionButton.extended(
          onPressed: () {
            Navigator.pop(context, {
              'ingredients': _detectedIngredients.toList(),
              'genericSulfateOrSulfonateDetected': _genericSulfateOrSulfonateDetected,
            });
          },
          label: const Text('Done'),
          icon: const Icon(Icons.check),
        ),
        body: Column(
          children: [
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: Text(
                'Please slowly move your camera over the ingredients list to scan. Ensure good lighting for better results.',
                style: theme.textTheme.bodyMedium,
                textAlign: TextAlign.center,
              ),
            ),
            Expanded(flex: 3, child: _buildCameraPreview()),
            Expanded(flex: 2, child: _buildIngredientList()),
          ],
        ),
      );
    }
    

    Step 2: Improve Design of Found Items

    Modify _buildIngredientList() method to display items in a tile-based layout similar to the results page:

    Widget _buildIngredientList() {
      return GridView.builder(
        padding: const EdgeInsets.all(16),
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          childAspectRatio: 3,
          crossAxisSpacing: 10,
          mainAxisSpacing: 10,
        ),
        itemCount: _detectedIngredients.length,
        itemBuilder: (context, index) {
          final ingredient = _detectedIngredients.elementAt(index);
          final details = _ingredientDetails[ingredient];
    
          return GestureDetector(
            onTap: () {
              if (details != null) {
                _showNotesDialog(context, details);
              }
            },
            child: Card(
              elevation: 2,
              child: Center(
                child: Text(
                  ingredient,
                  textAlign: TextAlign.center,
                ),
              ),
            ),
          );
        },
      );
    }
    
    void _showNotesDialog(BuildContext context, Map<String, dynamic> ingredient) {
      showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text(ingredient['ingredient_name'] ?? ''),
            content: Text(ingredient['notes'] ?? 'No additional information available.'),
            actions: [
              TextButton(
                onPressed: () => Navigator.of(context).pop(),
                child: const Text('OK'),
              ),
            ],
          );
        },
      );
    }
    

    5. Fix the SnackBar Bug

    The issue is that the SnackBar isn't disappearing and doesn't look good. Let's fix this.

    Problem:

    You're likely showing multiple SnackBars without dismissing the previous one, and perhaps not using the proper context.

    Solution:

    Modify the _showErrorSnackBar method to ensure the SnackBar is properly displayed and hides previous ones.

    Updated _showErrorSnackBar method:

    void _showErrorSnackBar(String message) {
      ScaffoldMessenger.of(context).hideCurrentSnackBar(); // Hide any existing SnackBar
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(message),
          behavior: SnackBarBehavior.floating,
          margin: const EdgeInsets.all(16),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8),
          ),
        ),
      );
    }
    

    Explanation:

    • We use ScaffoldMessenger.of(context).hideCurrentSnackBar() to hide any currently displayed SnackBar before showing a new one.
    • We set margin to provide space around the SnackBar, making it look better.

    I hope these changes meet your requirements. Remember to replace any placeholder text and images with content relevant to your app. Also, ensure you thoroughly test your app, especially the in-app purchases, to make sure everything works as expected.

    If you have any questions or need further assistance, feel free to ask!