Flutter Changenotifier 类需要始终在我的函数中传递

时间:2021-04-07 09:09:06

标签: flutter flutter-provider

我有一个 FutureBuilder 从函数接收值。这是我的 FutureBuilder,带有新的 context.watch 语法

final dataNotifier = Provider.of<DataNotifier>(context, listen: false);
    returnFutureBuilder(
                future: DataService().getData(dataNotifier),
                // ignore: missing_return
                builder: (context, snapshot) {
                  switch (snapshot.connectionState) {
                    case ConnectionState.none:
                      return Center(child: Text('No status', style: TextStyle(color: Colors.white),));
                      break;
                    case ConnectionState.waiting:
                      return Center(child: CircularProgressIndicator());
                      break;
                    case ConnectionState.done:
                    
    
                    return Center(
                      child:  Column(
                                    children: [
                                      Text(context.watch<Data>().myList[0].id, style: TextStyle(color: Colors.white)),
                                      Text(context.watch<Data>().myList[0].name, style: TextStyle(color: Colors.white))
                                    ],
                    ));
                   
                       //Center(child: Text('Data', style: TextStyle(color: Colors.white),));
                      break;
                    default:
                  }
                },
              ),

只要我总是在每个函数中传递 dataNotifier,一切都很好。我还不太熟悉提供程序,如何在不总是通过 dataNotifier 的情况下完成这项工作?

我假设我必须在我的 Changenotifier 类中添加一些东西?我的未来函数 getData(dataNotifier) 以以下内容结尾:

dataNotifier.myList = _myList;

还有我的 Changenotifier 班级 DataNotifier

class DataNotifier with ChangeNotifier {


      List<Data> _myList = [];
      UnmodifiableListView<Data> get myList => UnmodifiableListView(_myList);
      set myList(List<Data> myList){
        _myList = myList;
        notifyListeners();
      }

1 个答案:

答案 0 :(得分:1)

具有 MVVM(模型、视图、视图模型)架构的最简单的工作提供者示例如下所示。

加载数据后,应用会更新以显示新值。

您可以用您喜欢的任何内容替换字符串数据,例如项目列表。

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

void main() {
  runApp(MaterialApp(
      home: Material(
    child: ChangeNotifierProvider<DataNotifier>(
        create: (_) => DataNotifier(), child: MyApp()),
  )));
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final dataNotifier = Provider.of<DataNotifier>(context);
    if (dataNotifier.dataLoaded) return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      mainAxisSize: MainAxisSize.max,
      children: [
      Text(dataNotifier.data),
      Text(
      dataNotifier.listData.fold("LIST: ", (previousValue, e) => "$previousValue [${e.id} ${e.name}]"),
    )]);
    return Text("Waiting...");
  }
}

class DataNotifier with ChangeNotifier {
  bool _dataLoaded;
  bool get dataLoaded => _dataLoaded;
  DataService _service;
  String _data;
  String get data => _data;
  List<SampleData> _listData;
  List<SampleData> get listData => _listData;

  DataNotifier() {
    _dataLoaded = false;
    _service = DataService();
    getData();
  }

  void getData() async {
    _data = await _service.getData();
    _listData = await _service.getListData();
    _dataLoaded = true;
    notifyListeners();
  }
}

class DataService {
  Future<String> getData() async {
    return Future<String>.delayed(
      const Duration(seconds: 5),
      () => 'Data Loaded',
    );
  }

  Future<List<SampleData>> getListData() async {
    return Future<List<SampleData>>.delayed(
      const Duration(seconds: 5),
      () => List.generate(100, (index) => SampleData(index, "name_$index")),
    );
  }
}

class SampleData {
  int id;
  String name;

  SampleData(this.id, this.name);
}