Menus

Friday, 21 February 2025

Flutter : To avoid repeated loading of dropdown items

 

To avoid repeated loading of dropdown items (like courses, universities, etc.) on every page, you can use caching or a singleton pattern to load the items once and reuse them throughout your app. Here are the best solutions:

Solution 1: Use a Global Cache (Shared State)

You can store the dropdown items in a singleton service class or global variable and load them only once.

Step 1: Create a Singleton Service

dart
class DropdownService { static final DropdownService _instance = DropdownService._internal(); factory DropdownService() { return _instance; } DropdownService._internal(); List<Map<String, String>> courseItems = []; List<Map<String, String>> universityItems = []; bool isLoaded = false; Future<void> loadDropdowns() async { if (!isLoaded) { // Load only if not loaded before courseItems = await fetchGroupitems("2"); // Load Courses universityItems = await fetchGroupitems("3"); // Load Universities isLoaded = true; } } }


Step 2: Load Data Once in main.dart

dart
void main() async { WidgetsFlutterBinding.ensureInitialized(); await DropdownService().loadDropdowns(); // Load only once runApp(MyApp()); }

Step 3: Use in Any Page Without Reloading

dart
class MyDropdownPage extends StatefulWidget { @override _MyDropdownPageState createState() => _MyDropdownPageState(); } class _MyDropdownPageState extends State<MyDropdownPage> { List<Map<String, String>> courseItems = DropdownService().courseItems; String selectedCourse = "0"; @override Widget build(BuildContext context) { return DropdownButtonFormField<String>( decoration: InputDecoration(labelText: "Select Course"), value: selectedCourse, items: courseItems.map((item) { return DropdownMenuItem<String>( value: item['id'], child: Text(item['name'] ?? ""), ); }).toList(), onChanged: (value) { setState(() { selectedCourse = value!; }); }, ); } }


Solution 2: Store Dropdown Data in SharedPreferences

You can store the dropdown values in SharedPreferences and only update them when needed.

Step 1: Save Data After Fetching

dart
import 'package:shared_preferences/shared_preferences.dart'; import 'dart:convert'; Future<void> saveDropdownData(String key, List<Map<String, String>> data) async { SharedPreferences prefs = await SharedPreferences.getInstance(); prefs.setString(key, jsonEncode(data)); }

Step 2: Load Data from Cache

dart
Future<List<Map<String, String>>> loadDropdownData(String key) async { SharedPreferences prefs = await SharedPreferences.getInstance(); String? data = prefs.getString(key); if (data != null) { return List<Map<String, String>>.from(jsonDecode(data)); } return []; }

Step 3: Fetch Data Only if Needed

dart
Future<void> fetchCourses() async { courseItems = await loadDropdownData("courses"); if (courseItems.isEmpty) { courseItems = await fetchGroupitems("2"); saveDropdownData("courses", courseItems); } }

This way, data is fetched from cache instead of calling the API repeatedly.


Solution 3: Use a Provider or Riverpod for State Management

If you're using Provider or Riverpod, you can store the dropdown values in the app state and access them without reloading.

Using Provider

dart
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; class DropdownProvider with ChangeNotifier { List<Map<String, String>> courseItems = []; Future<void> loadDropdowns() async { if (courseItems.isEmpty) { courseItems = await fetchGroupitems("2"); notifyListeners(); // Notify UI to update } } }

Wrap Your App with Provider

dart
void main() { runApp( ChangeNotifierProvider( create: (_) => DropdownProvider()..loadDropdowns(), child: MyApp(), ), ); }

Use in Any Page

dart
DropdownButtonFormField<String>( value: selectedCourse, items: Provider.of<DropdownProvider>(context).courseItems.map((item) { return DropdownMenuItem<String>( value: item['id'], child: Text(item['name']), ); }).toList(), onChanged: (value) { setState(() { selectedCourse = value!; }); }, );

Which Solution Should You Use?

SolutionWhen to Use?
Singleton (DropdownService)If dropdown data is needed across multiple pages and should only be loaded once
SharedPreferences CacheIf you want dropdown data to persist even after the app restarts
Provider/RiverpodIf you're already using state management for better efficiency


Monday, 28 October 2024

Flutter using Add Two Numbers | Flutter Tutorials

Add Two Numbers using Flutter

In this presentation, we'll explore how to build a simple Flutter app that can add two numbers together. We'll cover the basics of the Dart programming language, Flutter's widget system, and the steps to create a functional user interface and add the necessary logic.


main.dart:


import 'package:add_two_numbers/addtwonumbers.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
       
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const AddTwoNumbers(),
    );
  }
}


addtwonumbers.dart:


import 'package:flutter/material.dart';

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

  @override
  State<AddTwoNumbers> createState() => _AddTwoNumbersState();
}

class _AddTwoNumbersState extends State<AddTwoNumbers> {

  final TextEditingController _num1Controller = TextEditingController();
  final TextEditingController _num2Controller = TextEditingController();
  final TextEditingController _resultController = TextEditingController();

  void _addNumbers(){
    setState(() {
     
      double num1 = double.tryParse(_num1Controller.text)?? 0;
      double num2 = double.tryParse(_num2Controller.text)?? 0;

      double result = num1 + num2;

      _resultController.text = result.toString();
 
    });
  }



  @override
  Widget build(BuildContext context) {
    return Scaffold(

      appBar: AppBar(
        title: Text("LogicLab Academy"),
        centerTitle: true,
        backgroundColor: Colors.red,
      ),

      body: SafeArea(child: Container(
        padding:EdgeInsets.symmetric(horizontal: 15, vertical: 20),
        child: Column(
          children: [

            Text("Add Two Numbers",style: TextStyle(fontSize: 30,color: Colors.blue),),

            SizedBox(height: 15,),

            TextField(
              controller: _num1Controller,
              decoration: InputDecoration(
                labelText: "First Number",
                labelStyle: TextStyle(fontSize: 15,color: Colors.grey.shade400),
                border: OutlineInputBorder(borderRadius: BorderRadius.circular(10))
              ),
            ),

            SizedBox(height: 15,),

            TextField(
              controller: _num2Controller,
              decoration: InputDecoration(
                labelText: "Second Number",
                labelStyle: TextStyle(fontSize: 15,color: Colors.grey.shade400),
                border: OutlineInputBorder(borderRadius: BorderRadius.circular(10))
              ),
            ),

            SizedBox(height: 15,),


            ElevatedButton(
             
              style: ButtonStyle(
                padding: WidgetStatePropertyAll(EdgeInsets.only(
                  left: 150,
                  right: 150,
                  top: 10,
                  bottom: 10,

                )),
                backgroundColor: WidgetStatePropertyAll(Colors.red),
                foregroundColor: WidgetStatePropertyAll(Colors.white),
                textStyle: WidgetStatePropertyAll(TextStyle(fontSize: 20 ))
              ),

              onPressed: _addNumbers,
              child: Text("ADD")
              ),

              SizedBox(height: 15,),

            TextField(
              controller: _resultController,
              decoration: InputDecoration(
                labelText: "Result",
                labelStyle: TextStyle(fontSize: 15,color: Colors.grey.shade400),
                border: OutlineInputBorder(borderRadius: BorderRadius.circular(10))
              ),
            ),

          ],
        ),
      )),

    );
  }
}


Thursday, 1 February 2024

How to get relation value in index in yii2 and Filter


How to get relation value in index in yii2


Certainly! When using Yii2, the convention is to create a separate search model for handling search and filtering logic. Here's a basic example of a PostSearch model with filtering capabilities for the author.name attribute:

Assuming you have a Post model with a hasOne relation to Author:

  1. Create a PostSearch model:

// models/PostSearch.php

namespace app\models;

use yii\base\Model;

use yii\data\ActiveDataProvider;

class PostSearch extends Post

{

    public $authorName;

    public function rules()

    {

        return [

            [['id', 'author_id'], 'integer'],

            [['title', 'content', 'authorName'], 'safe'],

        ];

    }


    public function search($params)

    {

        $query = Post::find()->joinWith('author');

        $dataProvider = new ActiveDataProvider([

            'query' => $query,

            'sort' => [

                'attributes' => [

                    'id',

                    'title',

                    'content',

                    'authorName' => [

                        'asc' => ['author.name' => SORT_ASC],

                        'desc' => ['author.name' => SORT_DESC],

                    ],

                ],

            ],

        ]);

        $dataProvider->sort->attributes['authorName'] = [

            'asc' => ['author.name' => SORT_ASC],

            'desc' => ['author.name' => SORT_DESC],

        ];

        $this->load($params);

        if (!$this->validate()) {

            return $dataProvider;

        }

        $query->andFilterWhere(['like', 'author.name', $this->authorName]);

        // Your other filtering logic goes here


        return $dataProvider;

    }

}


In your views/post/index.php, you can now use the GridView widget with the search model:

// views/post/index.php

use yii\grid\GridView;

// Other view code

<?= GridView::widget([

    'dataProvider' => $dataProvider,

    'filterModel' => $searchModel,

    'columns' => [

        // Your other columns


        [

            'attribute'=>'authorName'

            'value'=> 'author.name',

            'label' => 'Author Name',

        ],

        // Other columns

    ],

]); ?>


  1. In your Post model, ensure you have defined the relation to Author:
// models/Post.php

namespace app\models;

use yii\db\ActiveRecord;

class Post extends ActiveRecord
{
    // Your other attributes and methods here

    // Define the relation to Author

    public function getAuthor()
    {
        return $this->hasOne(Author::class, ['id' => 'author_id']);
    }

}


In your PostController, use the PostSearch model in the actionIndex method:

// controllers/PostController.php

namespace app\controllers;

use Yii;

use yii\web\Controller;

use app\models\PostSearch;

class PostController extends Controller

{

    public function actionIndex()

    {

        $searchModel = new PostSearch();

        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);


        return $this->render('index', [

            'searchModel' => $searchModel,

            'dataProvider' => $dataProvider,

        ]);

    }

}


 

Wednesday, 20 September 2023

Yii2 Gridview Dataprovider create with relationship

 

In Yii2, if you want to create a GridView with a DataProvider that includes related models and additional select columns, you can do the following:

  1. Create a Query with Related Models and Additional Select Columns:

$query = YourModel::find()

    ->select(['your_table.*', 'related_table.column AS alias'])

    ->joinWith('relatedRelation')

    ->where(['your_condition'])

    ->asArray();


Create a DataProvider using the Query:


$dataProvider = new \yii\data\ActiveDataProvider([

    'query' => $query,

    'pagination' => [

        'pageSize' => 20, // Set your desired page size

    ],

]);


Configure GridView to use the DataProvider:


<?= \yii\grid\GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
        'attribute1',
        'attribute2',
        // ... other attributes from your model ...
        'alias', // Access the added select column
        [
            'class' => 'yii\grid\ActionColumn',
            // ... configure action buttons ...
        ],
    ],
]); ?>


Make sure to replace 'your_table', 'related_table', 'alias', 'relatedRelation', and 'attribute1', 'attribute2' with actual table and attribute names from your application.

Keep in mind that this assumes you have properly set up your models, relations, and database tables in Yii2.

Remember to adjust the column names, relations, and conditions to match your specific application. This code serves as a template and may need to be customized based on your specific requirements.

Monday, 31 July 2023

Number System Conversion



 Decimal to Octal




















Saturday, 22 October 2022

How to Swap Two Arrays In C Language

 

#include<stdio.h>

void main()

{


  int a[5] = {5,6,7,8,9};

  int b[5] = {1,2,3,4,5};

  

  int i,swap;


  for(i=0;i<5;i++)

  {


    swap = a[i];

    a[i] = b[i];

    b[i] = swap;


  } 


  printf("A = ");

  for(i=0;i<5;i++)

    printf("%d ",a[i]);


  printf("\nB = ");

  for(i=0;i<5;i++)

    printf("%d ",b[i]); 


  printf("\n");

}







Saturday, 23 April 2022

Largest of three numbers in C

 #include <stdio.h>

int main()

{

 int x,y,z;

 clrscr();

 printf("Enter three numbers :");

 scanf("%d,%d,%d",&x,&y,&z);


 if(x>y)

 {

   if(x>z)

     printf("Largest value : %d ",x);

   else

     printf("Largest value : %d ",z);

 }

 else

 {

   if(y>z)

     printf("Largest value : %d",y);

   else

     printf("Largest value : %d",z);

 }


 getch();

}