Menu
CoddyTech

Riverpod: StateProvider

חלק מהיחידה ניהול מצב במסלול ה-Flutter של Coddy. שיעור 18 מתוך 27.

Provider מכיל ערך שאינו משתנה לעולם. עבור ערך פשוט אחד שכן משתנה, מספר, bool או String, השתמשו ב-StateProvider:

final quantityProvider = StateProvider((ref) => 1);

קראו אותו באותה הדרך: ref.watch(quantityProvider) מחזיר את המספר, והרכיב נבנה מחדש כשהוא משתנה.

כדי לשנות אותו, קבלו את הnotifier שלו, האובייקט שמכיל את הערך, באמצעות ref.read, והגדירו את state שלו:

onPressed: () {
  ref.read(quantityProvider.notifier).state++;
},

כמו ב-Provider, השתמשו ב-ref.watch בתוך build כדי להציג ערך, וב-ref.read בתוך פונקציות callback כדי לשנות אותו. ושינוי של עותק לא משנה דבר: var n = ref.read(quantityProvider); n++; מוסיף 1 ל-n, ולא לספק. רק הגדרת state עושה זאת.

challenge icon

אתגר

קל

הזמנת הפנקייק מציגה את הכמות שלה, אבל הכפתורים עדיין לא עושים דבר.

  • כפתור הפלוס מוסיף 1 ל־quantityProvider.
  • כפתור המינוס מפחית 1, אך לעולם לא יורד מתחת ל־1.

נסו בעצמכם

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

final quantityProvider = StateProvider((ref) => 1);

void main() {
  runApp(const ProviderScope(child: MyApp()));
}

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

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      home: OrderPage(),
    );
  }
}

class OrderPage extends ConsumerWidget {
  const OrderPage({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final quantity = ref.watch(quantityProvider);
    return Scaffold(
      appBar: AppBar(title: const Text('Pancakes')),
      body: Center(
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            IconButton(
              icon: const Icon(Icons.remove),
              onPressed: () {},
            ),
            Text('Quantity: $quantity', style: const TextStyle(fontSize: 24)),
            IconButton(
              icon: const Icon(Icons.add),
              onPressed: () {},
            ),
          ],
        ),
      ),
    );
  }
}
quiz iconבחנו את עצמכם

השיעור הזה כולל חידון קצר. התחילו את השיעור כדי לענות עליו ולעקוב אחרי ההתקדמות.

כל השיעורים ביחידה ניהול מצב

תרגלו בעצמכם: קומפיילר Flutter אונליין