7

Provider在我的颤振应用程序中使用,当我转到新页面时,Provider在第 2 页中无法访问提供给第 1 页的数据。

我理解这种Provider工作方式的方式是,有一个中心位置可以存储所有数据,并且可以在应用程序的任何位置访问这些数据。所以在我的应用程序中,如下所示,ToDoListManager是存储所有数据的地方。如果我在 中设置数据Page 1,那么我将能够在 中访问该数据Page 2,反之亦然。

如果这不正确,那么哪一部分是错误的?为什么它在我的应用程序中不起作用?

这是代码

第 1 页

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      builder: (context) => ToDoListManager(),
      child: Scaffold(
        appBar: AppBar(
          title: Text('Cool Project'),
        ),
        body:e ToDoList(),
      ),
    );
  }
}

class ToDoList extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final toDoListManager = Provider.of<ToDoListManager>(context);

    return ListView.builder(
      itemCount: toDoListManager.toDoList.length,
      itemBuilder: (context, index) {
        return GestureDetector(
          onTap: () {
            Navigator.push(context,
                MaterialPageRoute(builder: (context) => Details(index)));
          },
          child: Text(toDoListManager.toDoList[index]),
        );
      },
    );
  }
}

第2页

class Details extends StatelessWidget {
  final int index;

  Details(this.index);

  @override
  build(BuildContext context) {
    return ChangeNotifierProvider(
      builder: (context) => ToDoListManager(),
      child: Scaffold(
          appBar: AppBar(
            title: Text('Details Bro'),
          ),
          body: AppBody(index)),
    );
  }
}

class AppBody extends StatelessWidget {
  final int index;

  AppBody(this.index);

  @override
  Widget build(BuildContext context) {
    final toDoListManager = Provider.of<ToDoListManager>(context);
    print(toDoListManager.toDoList);

    return Text(toDoListManager.toDoList[1]);
  }
}

ToDoListProvider

class ToDoListManager with ChangeNotifier {
  List<String> _toDoList = ['yo', 'bro'];

  List<String> get toDoList => _toDoList;

  set toDoList(List<String> newToDoList) {
    _toDoList = newToDoList;
    notifyListeners();
  }
}
4

1 回答 1

6

您有 2 个选项:

  1. Place your ChangeNotifierProvider above your MaterialApp so that is accesible from any of you Navigator routes.

  2. Keep your Home widget as is but when pushing the new widget with the Navigator provide the original Manager.

onTap: () {
    Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) {
                return Provider<ToDoListManager>.value(
                    value: toDoListManager,
                    child: Details(index),
                );
            },
        ),
    );
},

With both approaches you don't need to create a new ChangeNotifierProvider in your details screen.

于 2019-09-13T09:25:44.933 回答