Home > Net >  Instantiating a List with Provider
Instantiating a List with Provider

Time:11-24

I am trying to learn how to use ChangeNotifierProvider and have gotten stuck. I've setup the class as so:

void main() => runApp(
    ChangeNotifierProvider(create: (context) => ItemList(),
      child: MyApp(),
    )

);

class ItemData {
  final String title;
  final int score;

  ItemData({required this.title, required this.score});

}

class ItemList extends ChangeNotifier{
  final _items = [];

  void add(item){
    _items.add(item);
    notifyListeners();
  }

  void update(){
    notifyListeners();
  }
}

final itemList = ItemList();

Now I want to create the list:

I'm trying to add items by calling:

itemList.add(ItemData({elements}))

but this isn't working. How do I create my list so I can put it into a Listview Builder?

CodePudding user response:

Try this one:

main.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

void main() => runApp(
      const MyApp(),
    );

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: ChangeNotifierProvider(
          create: (context) => ItemList(), child: const NewHomePage()),
    );
  }
}

class NewHomePage extends StatefulWidget {
  const NewHomePage({Key? key}) : super(key: key);

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

class _NewHomePageState extends State<NewHomePage> {
  @override
  Widget build(BuildContext context) {
    return Consumer<ItemList>(builder: (context, providerItem, child) {
      return Scaffold(
          appBar: AppBar(
            backgroundColor: const Color(0XFF2e3438),
          ),
          body: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              providerItem.basketItem.isEmpty
                  ? const Text("No item in the list")
                  : ListView.builder(
                      itemCount: providerItem.basketItem.length,
                      shrinkWrap: true,
                      itemBuilder: (context, index) {
                        return Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: Text(
                              "Title: "   providerItem.basketItem[index].title),
                        );
                      }),
              ElevatedButton(
                  onPressed: () {
                    providerItem.addItem(ItemData(
                        title: DateTime.now().toString(),
                        score: DateTime.now().month));
                    print("data added successfully"  
                        providerItem.basketItem.length.toString());
                  },
                  child: const Text("Add Data")),
            ],
          ));
    });
  }
}

item_data.dart

class ItemData {
  final String title;
  final int score;

  ItemData({required this.title, required this.score});
}

item_list.dart

class ItemList extends ChangeNotifier {
  List<ItemData> _items = [];

  void addItem(ItemData itemData) {
    _items.add(itemData);
    notifyListeners();
  }

  List<ItemData> get basketItem {
    return _items;
  }
}

  • Related