MunimTajwar

Assignment Code

Nov 10th, 2025
480
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Dart 6.43 KB | Source Code | 0 0
  1. import 'package:flutter/material.dart';
  2. import 'package:math_expressions/math_expressions.dart';
  3. import 'package:shared_preferences/shared_preferences.dart';
  4.  
  5. class CalculatorScreen2 extends StatefulWidget {
  6.   const CalculatorScreen2({super.key});
  7.  
  8.   @override
  9.   _CalculatorScreen2State createState() => _CalculatorScreen2State();
  10. }
  11.  
  12. class _CalculatorScreen2State extends State<CalculatorScreen2> {
  13.   String _expression = '';
  14.   String _result = '';
  15.   String themeMode = 'dark';
  16.  
  17.   final List<String> _buttons = [
  18.     'C', '⌫', '%', '÷',
  19.     '7', '8', '9', '×',
  20.     '4', '5', '6', '-',
  21.     '1', '2', '3', '+',
  22.     '0', '.', '=',
  23.   ];
  24.  
  25.   bool _isOperator(String s) {
  26.     return ['+', '-', '×', '÷', '%', '*', '/'].contains(s);
  27.   }
  28.  
  29.   void _buttonPressed(String text) {
  30.     setState(() {
  31.       if (text == 'C') {
  32.         _expression = '';
  33.         _result = '';
  34.       } else if (text == '⌫') {
  35.         if (_expression.isNotEmpty) {
  36.           _expression = _expression.substring(0, _expression.length - 1);
  37.         }
  38.       } else if (text == '=') {
  39.         _calculateResult();
  40.       } else if (text == '.') {
  41.        
  42.         int lastOp = _expression.lastIndexOf(RegExp(r'[\+\-\×\÷\*\/%]'));
  43.         String lastNumber = lastOp == -1 ? _expression : _expression.substring(lastOp + 1);
  44.         if (!lastNumber.contains('.')) {
  45.           _expression += text;
  46.         }
  47.       } else {
  48.        
  49.         if (_expression.isNotEmpty &&
  50.             _isOperator(text) &&
  51.             _isOperator(_expression[_expression.length - 1])) {
  52.           _expression = _expression.substring(0, _expression.length - 1) + text;
  53.         } else {
  54.           _expression += text;
  55.         }
  56.       }
  57.     });
  58.   }
  59.  
  60.   void _calculateResult() {
  61.     try {
  62.       if (_expression.isEmpty) return;
  63.  
  64.       // Remove trailing operator if any
  65.       while (_expression.isNotEmpty && _isOperator(_expression[_expression.length - 1])) {
  66.         _expression = _expression.substring(0, _expression.length - 1);
  67.       }
  68.       if (_expression.isEmpty) return;
  69.  
  70.       String finalExpression = _expression
  71.           .replaceAll('×', '*')
  72.           .replaceAll('÷', '/')
  73.           .replaceAll('%', '/100');
  74.  
  75.       Parser p = Parser();
  76.       Expression exp = p.parse(finalExpression);
  77.       ContextModel cm = ContextModel();
  78.       double eval = exp.evaluate(EvaluationType.REAL, cm);
  79.  
  80.       String res = eval.toString();
  81.       if (res.endsWith('.0')) res = res.substring(0, res.length - 2);
  82.       _result = res;
  83.     } catch (e) {
  84.       _result = 'Error';
  85.     }
  86.   }
  87.  
  88.  
  89.   Future<void> loadTheme() async {
  90.     final prefs = await SharedPreferences.getInstance();
  91.     setState(() {
  92.       themeMode = prefs.getString('theme') ?? 'dark';
  93.     });
  94.   }
  95.  
  96.  
  97.   Future<void> saveTheme(String mode) async {
  98.     final prefs = await SharedPreferences.getInstance();
  99.     await prefs.setString('theme', mode);
  100.   }
  101.  
  102.   @override
  103.   void initState() {
  104.     super.initState();
  105.     loadTheme();
  106.   }
  107.  
  108.   Color _getButtonColor(String text) {
  109.     if (text == 'C') return Colors.redAccent;
  110.     if (text == '=' || text == '+' || text == '-' || text == '×' || text == '÷') {
  111.       return Colors.blueAccent;
  112.     }
  113.     return themeMode == 'dark' ? Colors.grey[850]! : Colors.grey[300]!;
  114.   }
  115.  
  116.   Color _getTextColor(String text) {
  117.     if (text == 'C' || text == '=' || text == '+' || text == '-' || text == '×' || text == '÷') {
  118.       return Colors.white;
  119.     }
  120.     return themeMode == 'dark' ? Colors.white70 : Colors.black87;
  121.   }
  122.  
  123.   @override
  124.   Widget build(BuildContext context) {
  125.     final bool isDark = themeMode == 'dark';
  126.  
  127.     return Scaffold(
  128.       appBar: AppBar(
  129.         title: const Text('Calculator App'),
  130.         centerTitle: true,
  131.         actions: [
  132.           IconButton(
  133.             onPressed: () {
  134.               setState(() {
  135.                 themeMode = isDark ? 'light' : 'dark';
  136.               });
  137.               saveTheme(themeMode);
  138.             },
  139.             icon: Icon(isDark ? Icons.sunny : Icons.dark_mode),
  140.           ),
  141.         ],
  142.       ),
  143.       backgroundColor: isDark ? Colors.black : Colors.white,
  144.       body: SafeArea(
  145.         child: Column(
  146.           mainAxisAlignment: MainAxisAlignment.end,
  147.           children: [
  148.             Container(
  149.               padding: const EdgeInsets.all(20),
  150.               alignment: Alignment.centerRight,
  151.               child: Text(
  152.                 _expression,
  153.                 style: TextStyle(
  154.                   fontSize: 30,
  155.                   color: isDark ? Colors.white : Colors.black,
  156.                 ),
  157.               ),
  158.             ),
  159.             Container(
  160.               padding: const EdgeInsets.all(20),
  161.               alignment: Alignment.centerRight,
  162.               child: Text(
  163.                 _result,
  164.                 style: TextStyle(
  165.                   fontSize: 40,
  166.                   color: isDark ? Colors.white : Colors.black,
  167.                   fontWeight: FontWeight.bold,
  168.                 ),
  169.               ),
  170.             ),
  171.             Divider(color: isDark ? Colors.white24 : Colors.black12),
  172.             Expanded(
  173.               flex: 2,
  174.               child: Container(
  175.                 padding: const EdgeInsets.all(10),
  176.                 child: GridView.builder(
  177.                   itemCount: _buttons.length,
  178.                   gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
  179.                     crossAxisCount: 4,
  180.                     mainAxisSpacing: 10,
  181.                     crossAxisSpacing: 10,
  182.                   ),
  183.                   itemBuilder: (context, index) {
  184.                     final buttonText = _buttons[index];
  185.                     return ElevatedButton(
  186.                       style: ElevatedButton.styleFrom(
  187.                         shape: const CircleBorder(),
  188.                         padding: const EdgeInsets.all(20),
  189.                         backgroundColor: _getButtonColor(buttonText),
  190.                       ),
  191.                       onPressed: () => _buttonPressed(buttonText),
  192.                       child: Text(
  193.                         buttonText,
  194.                         style: TextStyle(
  195.                           fontSize: 24,
  196.                           color: _getTextColor(buttonText),
  197.                           fontWeight: FontWeight.bold,
  198.                         ),
  199.                       ),
  200.                     );
  201.                   },
  202.                 ),
  203.               ),
  204.             ),
  205.           ],
  206.         ),
  207.       ),
  208.     );
  209.   }
  210. }
  211.  
Advertisement
Add Comment
Please, Sign In to add comment