Flutter: Management of the state of multiple items in a list view using ChangeNotifierProvider

一世执手 提交于 2021-02-10 22:22:52

问题


in my Flutter app

I want to display multiple items inside a listView

and I want to handle their state using Provider.

but how can I handle the state in a way that if I edit one item in the listview only that item get rebuild.

and the entire listview get rebuild only when I change the number of items either by adding or deleting.

how can I do this


回答1:


This is a working solution that is very close to what you want (It still rebuilds the whole ListView when one item is edited but have no worries about efficiency because ListView.builder takes care of that for you):

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

class MyModel {
  int modelNumber;

  MyModel(this.modelNumber);

  void edit(int newModelNumber) {
    modelNumber = newModelNumber;
  }
}

class MyModelListWrapper with ChangeNotifier {
  List<MyModel> modelsList;

  MyModelListWrapper(this.modelsList);

  void add(MyModel model) {
    modelsList.add(model);
    notifyListeners();
  }

  void removeAt(int index) {
    modelsList.removeAt(index);
    notifyListeners();
  }

  void editModelNumber(int index,int newModelNumber){
    modelsList[index].edit(newModelNumber);
    notifyListeners();
  }
}

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(
          create: (_) => MyModelListWrapper(
              [...List.generate(15, (index)=>MyModel(index))]),
        ),
      ],
      child: MaterialApp(
        home: HomePage(),
      ),
    );
  }
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Consumer<MyModelListWrapper>(
        builder: (_,myModelsListWrapper,__)=> ListView.builder(
          itemCount: myModelsListWrapper.modelsList.length,
          itemBuilder: (ctx, index) => ListTile(
            title: Text('${myModelsListWrapper.modelsList[index].modelNumber}'),
            onTap: (){
//              myModelsListWrapper.editModelNumber(index, -1);
              myModelsListWrapper.removeAt(index);
              //or do any other action you want
            },
          ),
        ),
      ),
    );
  }
}


来源:https://stackoverflow.com/questions/61442745/flutter-management-of-the-state-of-multiple-items-in-a-list-view-using-changeno

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!